// File: crates/router/src/routes/customers.rs
// Module: router
// Public functions: 11

use actix_web::{web, HttpRequest, HttpResponse, Responder};
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};

use super::app::AppState;
use crate::{
    core::{api_locking, customers::*},
    services::{api, authentication as auth, authorization::permissions::Permission},
    types::{api::customers, domain},
};
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersCreate;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        json_payload.into_inner(),
        |state, auth: auth::AuthenticationData, req, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            create_customer(state, merchant_context, req, None)
        },
        auth::auth_type(
            &auth::V2ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customers_create(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<customers::CustomerRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersCreate;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        json_payload.into_inner(),
        |state, auth: auth::AuthenticationData, req, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            create_customer(state, merchant_context, req, None)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            }),
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
    let flow = Flow::CustomersRetrieve;

    let customer_id = path.into_inner();

    let auth = if auth::is_jwt_auth(req.headers()) {
        Box::new(auth::JWTAuth {
            permission: Permission::MerchantCustomerRead,
        })
    } else {
        let api_auth = auth::ApiKeyAuth::default();
        match auth::is_ephemeral_auth(req.headers(), api_auth) {
            Ok(auth) => auth,
            Err(err) => return api::log_and_return_error_response(err),
        }
    };

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        customer_id,
        |state, auth: auth::AuthenticationData, customer_id, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            retrieve_customer(state, merchant_context, auth.profile_id, customer_id)
        },
        &*auth,
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customers_retrieve(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::GlobalCustomerId>,
) -> HttpResponse {
    use crate::services::authentication::api_or_client_auth;

    let flow = Flow::CustomersRetrieve;

    let id = path.into_inner();

    let v2_client_auth = auth::V2ClientAuth(
        common_utils::types::authentication::ResourceId::Customer(id.clone()),
    );
    let auth = if auth::is_jwt_auth(req.headers()) {
        &auth::JWTAuth {
            permission: Permission::MerchantCustomerRead,
        }
    } else {
        api_or_client_auth(
            &auth::V2ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &v2_client_auth,
            req.headers(),
        )
    };

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        id,
        |state, auth: auth::AuthenticationData, id, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            retrieve_customer(state, merchant_context, id)
        },
        auth,
        api_locking::LockAction::NotApplicable,
    ))
    .await
}
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
    state: web::Data<AppState>,
    req: HttpRequest,
    query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersList;
    let payload = query.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        payload,
        |state, auth: auth::AuthenticationData, request, _| {
            list_customers(
                state,
                auth.merchant_account.get_id().to_owned(),
                None,
                auth.key_store,
                request,
            )
        },
        auth::auth_type(
            &auth::V2ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerRead,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
pub async fn customers_list(
    state: web::Data<AppState>,
    req: HttpRequest,
    query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersList;
    let payload = query.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        payload,
        |state, auth: auth::AuthenticationData, request, _| {
            list_customers(
                state,
                auth.merchant_account.get_id().to_owned(),
                None,
                auth.key_store,
                request,
            )
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            }),
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerRead,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::CustomerId>,
    json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersUpdate;
    let customer_id = path.into_inner();
    let request = json_payload.into_inner();
    let request_internal = customers::CustomerUpdateRequestInternal {
        customer_id,
        request,
    };

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        request_internal,
        |state, auth: auth::AuthenticationData, request_internal, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            update_customer(state, merchant_context, request_internal)
        },
        auth::auth_type(
            &auth::ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
pub async fn customers_update(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::GlobalCustomerId>,
    json_payload: web::Json<customers::CustomerUpdateRequest>,
) -> HttpResponse {
    let flow = Flow::CustomersUpdate;
    let id = path.into_inner();
    let request = json_payload.into_inner();
    let request_internal = customers::CustomerUpdateRequestInternal { id, request };

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        request_internal,
        |state, auth: auth::AuthenticationData, request_internal, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            update_customer(state, merchant_context, request_internal)
        },
        auth::auth_type(
            &auth::V2ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::GlobalCustomerId>,
) -> impl Responder {
    let flow = Flow::CustomersDelete;
    let id = path.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        id,
        |state, auth: auth::AuthenticationData, id, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            delete_customer(state, merchant_context, id)
        },
        auth::auth_type(
            &auth::V2ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            },
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customers_delete(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::CustomerId>,
) -> impl Responder {
    let flow = Flow::CustomersDelete;
    let customer_id = path.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        customer_id,
        |state, auth: auth::AuthenticationData, customer_id, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            delete_customer(state, merchant_context, customer_id)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            }),
            &auth::JWTAuth {
                permission: Permission::MerchantCustomerWrite,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersGetMandates))]
pub async fn get_customer_mandates(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<id_type::CustomerId>,
) -> impl Responder {
    let flow = Flow::CustomersGetMandates;
    let customer_id = path.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        customer_id,
        |state, auth: auth::AuthenticationData, customer_id, _| {
            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            crate::core::mandate::get_customer_mandates(state, merchant_context, customer_id)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                is_connected_allowed: false,
                is_platform_allowed: false,
            }),
            &auth::JWTAuth {
                permission: Permission::MerchantMandateRead,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}


// Implementation: impl api::UasAuthentication for for Juspaythreedsserver
// File: crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::UasAuthentication for for Juspaythreedsserver


// Struct: PaymentRedirectCompleteAuthorize
// File: crates/router/src/core/payments.rs
// Module: router
// Implementations: 1
// Traits: PaymentRedirectFlow

pub struct PaymentRedirectCompleteAuthorize


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

impl RefundSync for for Cybersource


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

pub struct DisputeTransaction


// Function: find_by_algorithm_id_merchant_id
// File: crates/diesel_models/src/query/routing_algorithm.rs
// Module: diesel_models

pub fn find_by_algorithm_id_merchant_id(
        conn: &PgPooledConn,
        algorithm_id: &common_utils::id_type::RoutingId,
        merchant_id: &common_utils::id_type::MerchantId,
    ) -> StorageResult<Self>


// File: crates/diesel_models/src/query/events.rs
// Module: diesel_models
// Public functions: 11

use std::collections::HashSet;

use diesel::{
    associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
};

use super::generics;
use crate::{
    events::{Event, EventNew, EventUpdateInternal},
    schema::events::dsl,
    PgPooledConn, StorageResult,
};

impl EventNew {
    pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> {
        generics::generic_insert(conn, self).await
    }
}

impl Event {
    pub async fn find_by_merchant_id_event_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        event_id: &str,
    ) -> StorageResult<Self> {
        generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
            conn,
            dsl::merchant_id
                .eq(merchant_id.to_owned())
                .and(dsl::event_id.eq(event_id.to_owned())),
        )
        .await
    }

    pub async fn find_by_merchant_id_idempotent_event_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        idempotent_event_id: &str,
    ) -> StorageResult<Self> {
        generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
            conn,
            dsl::merchant_id
                .eq(merchant_id.to_owned())
                .and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())),
        )
        .await
    }

    pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        primary_object_id: &str,
    ) -> StorageResult<Vec<Self>> {
        generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
            conn,
            dsl::event_id
                .nullable()
                .eq(dsl::initial_attempt_id) // Filter initial attempts only
                .and(dsl::merchant_id.eq(merchant_id.to_owned()))
                .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
            None,
            None,
            Some(dsl::created_at.desc()),
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn list_initial_attempts_by_merchant_id_constraints(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        created_after: time::PrimitiveDateTime,
        created_before: time::PrimitiveDateTime,
        limit: Option<i64>,
        offset: Option<i64>,
        event_types: HashSet<common_enums::EventType>,
        is_delivered: Option<bool>,
    ) -> StorageResult<Vec<Self>> {
        use async_bb8_diesel::AsyncRunQueryDsl;
        use diesel::{debug_query, pg::Pg, QueryDsl};
        use error_stack::ResultExt;
        use router_env::logger;

        use super::generics::db_metrics::{track_database_call, DatabaseOperation};
        use crate::errors::DatabaseError;

        let mut query = Self::table()
            .filter(
                dsl::event_id
                    .nullable()
                    .eq(dsl::initial_attempt_id) // Filter initial attempts only
                    .and(dsl::merchant_id.eq(merchant_id.to_owned())),
            )
            .order(dsl::created_at.desc())
            .into_boxed();

        query = Self::apply_filters(
            query,
            None,
            (dsl::created_at, created_after, created_before),
            limit,
            offset,
            event_types,
            is_delivered,
        );

        logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());

        track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
            .await
            .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
            .attach_printable("Error filtering events by constraints")
    }

    pub async fn list_by_merchant_id_initial_attempt_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        initial_attempt_id: &str,
    ) -> StorageResult<Vec<Self>> {
        generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
            conn,
            dsl::merchant_id
                .eq(merchant_id.to_owned())
                .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
            None,
            None,
            Some(dsl::created_at.desc()),
        )
        .await
    }

    pub async fn list_initial_attempts_by_profile_id_primary_object_id(
        conn: &PgPooledConn,
        profile_id: &common_utils::id_type::ProfileId,
        primary_object_id: &str,
    ) -> StorageResult<Vec<Self>> {
        generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
            conn,
            dsl::event_id
                .nullable()
                .eq(dsl::initial_attempt_id) // Filter initial attempts only
                .and(dsl::business_profile_id.eq(profile_id.to_owned()))
                .and(dsl::primary_object_id.eq(primary_object_id.to_owned())),
            None,
            None,
            Some(dsl::created_at.desc()),
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn list_initial_attempts_by_profile_id_constraints(
        conn: &PgPooledConn,
        profile_id: &common_utils::id_type::ProfileId,
        created_after: time::PrimitiveDateTime,
        created_before: time::PrimitiveDateTime,
        limit: Option<i64>,
        offset: Option<i64>,
        event_types: HashSet<common_enums::EventType>,
        is_delivered: Option<bool>,
    ) -> StorageResult<Vec<Self>> {
        use async_bb8_diesel::AsyncRunQueryDsl;
        use diesel::{debug_query, pg::Pg, QueryDsl};
        use error_stack::ResultExt;
        use router_env::logger;

        use super::generics::db_metrics::{track_database_call, DatabaseOperation};
        use crate::errors::DatabaseError;

        let mut query = Self::table()
            .filter(
                dsl::event_id
                    .nullable()
                    .eq(dsl::initial_attempt_id) // Filter initial attempts only
                    .and(dsl::business_profile_id.eq(profile_id.to_owned())),
            )
            .order(dsl::created_at.desc())
            .into_boxed();

        query = Self::apply_filters(
            query,
            None,
            (dsl::created_at, created_after, created_before),
            limit,
            offset,
            event_types,
            is_delivered,
        );

        logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());

        track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
            .await
            .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found
            .attach_printable("Error filtering events by constraints")
    }

    pub async fn list_by_profile_id_initial_attempt_id(
        conn: &PgPooledConn,
        profile_id: &common_utils::id_type::ProfileId,
        initial_attempt_id: &str,
    ) -> StorageResult<Vec<Self>> {
        generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
            conn,
            dsl::business_profile_id
                .eq(profile_id.to_owned())
                .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())),
            None,
            None,
            Some(dsl::created_at.desc()),
        )
        .await
    }

    pub async fn update_by_merchant_id_event_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        event_id: &str,
        event: EventUpdateInternal,
    ) -> StorageResult<Self> {
        generics::generic_update_with_unique_predicate_get_result::<
            <Self as HasTable>::Table,
            _,
            _,
            _,
        >(
            conn,
            dsl::merchant_id
                .eq(merchant_id.to_owned())
                .and(dsl::event_id.eq(event_id.to_owned())),
            event,
        )
        .await
    }

    fn apply_filters<T>(
        mut query: T,
        profile_id: Option<common_utils::id_type::ProfileId>,
        (column, created_after, created_before): (
            dsl::created_at,
            time::PrimitiveDateTime,
            time::PrimitiveDateTime,
        ),
        limit: Option<i64>,
        offset: Option<i64>,
        event_types: HashSet<common_enums::EventType>,
        is_delivered: Option<bool>,
    ) -> T
    where
        T: diesel::query_dsl::methods::LimitDsl<Output = T>
            + diesel::query_dsl::methods::OffsetDsl<Output = T>,
        T: diesel::query_dsl::methods::FilterDsl<
            diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>,
            Output = T,
        >,
        T: diesel::query_dsl::methods::FilterDsl<
            diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>,
            Output = T,
        >,
        T: diesel::query_dsl::methods::FilterDsl<
            diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>,
            Output = T,
        >,
        T: diesel::query_dsl::methods::FilterDsl<
            diesel::dsl::EqAny<dsl::event_type, HashSet<common_enums::EventType>>,
            Output = T,
        >,
        T: diesel::query_dsl::methods::FilterDsl<
            diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>,
            Output = T,
        >,
    {
        if let Some(profile_id) = profile_id {
            query = query.filter(dsl::business_profile_id.eq(profile_id));
        }

        query = query
            .filter(column.ge(created_after))
            .filter(column.le(created_before));

        if let Some(limit) = limit {
            query = query.limit(limit);
        }

        if let Some(offset) = offset {
            query = query.offset(offset);
        }

        if !event_types.is_empty() {
            query = query.filter(dsl::event_type.eq_any(event_types));
        }

        if let Some(is_delivered) = is_delivered {
            query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered));
        }

        query
    }

    pub async fn count_initial_attempts_by_constraints(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        profile_id: Option<common_utils::id_type::ProfileId>,
        created_after: time::PrimitiveDateTime,
        created_before: time::PrimitiveDateTime,
        event_types: HashSet<common_enums::EventType>,
        is_delivered: Option<bool>,
    ) -> StorageResult<i64> {
        use async_bb8_diesel::AsyncRunQueryDsl;
        use diesel::{debug_query, pg::Pg, QueryDsl};
        use error_stack::ResultExt;
        use router_env::logger;

        use super::generics::db_metrics::{track_database_call, DatabaseOperation};
        use crate::errors::DatabaseError;

        let mut query = Self::table()
            .count()
            .filter(
                dsl::event_id
                    .nullable()
                    .eq(dsl::initial_attempt_id) // Filter initial attempts only
                    .and(dsl::merchant_id.eq(merchant_id.to_owned())),
            )
            .into_boxed();

        query = Self::apply_filters(
            query,
            profile_id,
            (dsl::created_at, created_after, created_before),
            None,
            None,
            event_types,
            is_delivered,
        );

        logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());

        track_database_call::<Self, _, _>(
            query.get_result_async::<i64>(conn),
            DatabaseOperation::Count,
        )
        .await
        .change_context(DatabaseError::Others)
        .attach_printable("Error counting events by constraints")
    }
}


// Struct: PaymentMethodId
// File: crates/hyperswitch_connectors/src/connectors/moneris/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PaymentMethodId


// Implementation: impl Deref for for ExtendedAuthorizationAppliedBool
// File: crates/common_types/src/primitive_wrappers.rs
// Module: common_types
// Methods: 1 total (0 public)

impl Deref for for ExtendedAuthorizationAppliedBool


// Function: list_by_merchant_id_initial_attempt_id
// File: crates/diesel_models/src/query/events.rs
// Module: diesel_models

pub fn list_by_merchant_id_initial_attempt_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        initial_attempt_id: &str,
    ) -> StorageResult<Vec<Self>>


// Struct: EligiblePaymentMethods
// File: crates/payment_methods/src/configs/settings.rs
// Module: payment_methods
// Implementations: 0

pub struct EligiblePaymentMethods


// File: crates/hyperswitch_domain_models/src/chat.rs
// Module: hyperswitch_domain_models
// Public structs: 2

use common_utils::id_type;
use masking::Secret;

#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct GetDataMessage {
    pub message: Secret<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct HyperswitchAiDataRequest {
    pub merchant_id: id_type::MerchantId,
    pub profile_id: id_type::ProfileId,
    pub org_id: id_type::OrganizationId,
    pub query: GetDataMessage,
    pub entity_type: common_enums::EntityType,
}


// Implementation: impl NewUser
// File: crates/router/src/types/domain/user.rs
// Module: router
// Methods: 10 total (6 public)

impl NewUser


// File: crates/payment_methods/src/configs/payment_connector_required_fields.rs
// Module: payment_methods
// Public functions: 3

use std::collections::{HashMap, HashSet};

use api_models::{
    enums::{self, Connector, FieldType},
    payment_methods::RequiredFieldInfo,
};

use crate::configs::settings::{
    BankRedirectConfig, ConnectorFields, Mandates, RequiredFieldFinal,
    SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate,
    SupportedPaymentMethodsForMandate, ZeroMandates,
};
#[cfg(feature = "v1")]
use crate::configs::settings::{PaymentMethodType, RequiredFields};

impl Default for ZeroMandates {
    fn default() -> Self {
        Self {
            supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::new()),
        }
    }
}

impl Default for Mandates {
    fn default() -> Self {
        Self {
            supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::from([
                (
                    enums::PaymentMethod::PayLater,
                    SupportedPaymentMethodTypesForMandate(HashMap::from([(
                        enums::PaymentMethodType::Klarna,
                        SupportedConnectorsForMandate {
                            connector_list: HashSet::from([Connector::Adyen]),
                        },
                    )])),
                ),
                (
                    enums::PaymentMethod::Wallet,
                    SupportedPaymentMethodTypesForMandate(HashMap::from([
                        (
                            enums::PaymentMethodType::GooglePay,
                            SupportedConnectorsForMandate {
                                connector_list: HashSet::from([
                                    Connector::Stripe,
                                    Connector::Adyen,
                                    Connector::Globalpay,
                                    Connector::Multisafepay,
                                    Connector::Bankofamerica,
                                    Connector::Novalnet,
                                    Connector::Noon,
                                    Connector::Cybersource,
                                    Connector::Wellsfargo,
                                ]),
                            },
                        ),
                        (
                            enums::PaymentMethodType::ApplePay,
                            SupportedConnectorsForMandate {
                                connector_list: HashSet::from([
                                    Connector::Stripe,
                                    Connector::Adyen,
                                    Connector::Bankofamerica,
                                    Connector::Cybersource,
                                    Connector::Novalnet,
                                    Connector::Wellsfargo,
                                ]),
                            },
                        ),
                        (
                            enums::PaymentMethodType::SamsungPay,
                            SupportedConnectorsForMandate {
                                connector_list: HashSet::from([Connector::Cybersource]),
                            },
                        ),
                    ])),
                ),
                (
                    enums::PaymentMethod::Card,
                    SupportedPaymentMethodTypesForMandate(HashMap::from([
                        (
                            enums::PaymentMethodType::Credit,
                            SupportedConnectorsForMandate {
                                connector_list: HashSet::from([
                                    Connector::Aci,
                                    Connector::Adyen,
                                    Connector::Authorizedotnet,
                                    Connector::Globalpay,
                                    Connector::Worldpay,
                                    Connector::Fiuu,
                                    Connector::Multisafepay,
                                    Connector::Nexinets,
                                    Connector::Noon,
                                    Connector::Novalnet,
                                    Connector::Payme,
                                    Connector::Stripe,
                                    Connector::Bankofamerica,
                                    Connector::Cybersource,
                                    Connector::Wellsfargo,
                                ]),
                            },
                        ),
                        (
                            enums::PaymentMethodType::Debit,
                            SupportedConnectorsForMandate {
                                connector_list: HashSet::from([
                                    Connector::Aci,
                                    Connector::Adyen,
                                    Connector::Authorizedotnet,
                                    Connector::Globalpay,
                                    Connector::Worldpay,
                                    Connector::Fiuu,
                                    Connector::Multisafepay,
                                    Connector::Nexinets,
                                    Connector::Noon,
                                    Connector::Novalnet,
                                    Connector::Payme,
                                    Connector::Stripe,
                                ]),
                            },
                        ),
                    ])),
                ),
            ])),
            update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()),
        }
    }
}

#[derive(Clone, serde::Serialize)]
#[cfg_attr(feature = "v2", allow(dead_code))] // multiple variants are never constructed for v2
enum RequiredField {
    CardNumber,
    CardExpMonth,
    CardExpYear,
    CardCvc,
    CardNetwork,
    BillingUserFirstName,
    BillingUserLastName,
    /// display name and field type for billing first name
    BillingFirstName(&'static str, FieldType),
    /// display name and field type for billing last name
    BillingLastName(&'static str, FieldType),
    BillingEmail,
    Email,
    BillingPhone,
    BillingPhoneCountryCode,
    BillingAddressLine1,
    BillingAddressLine2,
    BillingAddressCity,
    BillingAddressState,
    BillingAddressZip,
    BillingCountries(Vec<&'static str>),
    BillingAddressCountries(Vec<&'static str>),
    ShippingFirstName,
    ShippingLastName,
    ShippingAddressCity,
    ShippingAddressState,
    ShippingAddressZip,
    ShippingCountries(Vec<&'static str>),
    ShippingAddressCountries(Vec<&'static str>),
    ShippingAddressLine1,
    ShippingAddressLine2,
    ShippingPhone,
    ShippingPhoneCountryCode,
    ShippingEmail,
    OpenBankingUkIssuer,
    OpenBankingCzechRepublicIssuer,
    OpenBankingPolandIssuer,
    OpenBankingSlovakiaIssuer,
    OpenBankingFpxIssuer,
    OpenBankingThailandIssuer,
    BanContactCardNumber,
    BanContactCardExpMonth,
    BanContactCardExpYear,
    IdealBankName,
    EpsBankName,
    EpsBankOptions(HashSet<enums::BankNames>),
    BlikCode,
    MifinityDateOfBirth,
    MifinityLanguagePreference(Vec<&'static str>),
    CryptoNetwork,
    CyptoPayCurrency(Vec<&'static str>),
    BoletoSocialSecurityNumber,
    UpiCollectVpaId,
    AchBankDebitAccountNumber,
    AchBankDebitRoutingNumber,
    AchBankDebitBankType(Vec<enums::BankType>),
    AchBankDebitBankAccountHolderName,
    SepaBankDebitIban,
    BacsBankDebitAccountNumber,
    BacsBankDebitSortCode,
    BecsBankDebitAccountNumber,
    BecsBankDebitBsbNumber,
    BecsBankDebitSortCode,
    PixKey,
    PixCnpj,
    PixCpf,
    PixSourceBankAccountId,
    GiftCardNumber,
    GiftCardCvc,
    DcbMsisdn,
    DcbClientUid,
    OrderDetailsProductName,
    Description,
}

impl RequiredField {
    fn to_tuple(&self) -> (String, RequiredFieldInfo) {
        match self {
            Self::CardNumber => (
                "payment_method_data.card.card_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.card.card_number".to_string(),
                    display_name: "card_number".to_string(),
                    field_type: FieldType::UserCardNumber,
                    value: None,
                },
            ),
            Self::CardExpMonth => (
                "payment_method_data.card.card_exp_month".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.card.card_exp_month".to_string(),
                    display_name: "card_exp_month".to_string(),
                    field_type: FieldType::UserCardExpiryMonth,
                    value: None,
                },
            ),
            Self::CardExpYear => (
                "payment_method_data.card.card_exp_year".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.card.card_exp_year".to_string(),
                    display_name: "card_exp_year".to_string(),
                    field_type: FieldType::UserCardExpiryYear,
                    value: None,
                },
            ),
            Self::CardCvc => (
                "payment_method_data.card.card_cvc".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.card.card_cvc".to_string(),
                    display_name: "card_cvc".to_string(),
                    field_type: FieldType::UserCardCvc,
                    value: None,
                },
            ),
            Self::CardNetwork => (
                "payment_method_data.card.card_network".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.card.card_network".to_string(),
                    display_name: "card_network".to_string(),
                    field_type: FieldType::UserCardNetwork,
                    value: None,
                },
            ),
            Self::BillingUserFirstName => (
                "billing.address.first_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.first_name".to_string(),
                    display_name: "card_holder_name".to_string(),
                    field_type: FieldType::UserFullName,
                    value: None,
                },
            ),
            Self::BillingUserLastName => (
                "billing.address.last_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.last_name".to_string(),
                    display_name: "card_holder_name".to_string(),
                    field_type: FieldType::UserFullName,
                    value: None,
                },
            ),
            Self::BillingFirstName(display_name, field_type) => (
                "billing.address.first_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.first_name".to_string(),
                    display_name: display_name.to_string(),
                    field_type: field_type.clone(),
                    value: None,
                },
            ),
            Self::BillingLastName(display_name, field_type) => (
                "billing.address.last_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.last_name".to_string(),
                    display_name: display_name.to_string(),
                    field_type: field_type.clone(),
                    value: None,
                },
            ),
            Self::Email => (
                "email".to_string(),
                RequiredFieldInfo {
                    required_field: "email".to_string(),
                    display_name: "email".to_string(),
                    field_type: FieldType::UserEmailAddress,
                    value: None,
                },
            ),
            Self::BillingEmail => (
                "billing.email".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.email".to_string(),
                    display_name: "email".to_string(),
                    field_type: FieldType::UserEmailAddress,
                    value: None,
                },
            ),
            Self::BillingPhone => (
                "billing.phone.number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.phone.number".to_string(),
                    display_name: "phone".to_string(),
                    field_type: FieldType::UserPhoneNumber,
                    value: None,
                },
            ),
            Self::BillingPhoneCountryCode => (
                "billing.phone.country_code".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.phone.country_code".to_string(),
                    display_name: "dialing_code".to_string(),
                    field_type: FieldType::UserPhoneNumberCountryCode,
                    value: None,
                },
            ),
            Self::BillingAddressLine1 => (
                "billing.address.line1".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.line1".to_string(),
                    display_name: "line1".to_string(),
                    field_type: FieldType::UserAddressLine1,
                    value: None,
                },
            ),
            Self::BillingAddressLine2 => (
                "billing.address.line2".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.line2".to_string(),
                    display_name: "line2".to_string(),
                    field_type: FieldType::UserAddressLine2,
                    value: None,
                },
            ),
            Self::BillingAddressCity => (
                "billing.address.city".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.city".to_string(),
                    display_name: "city".to_string(),
                    field_type: FieldType::UserAddressCity,
                    value: None,
                },
            ),
            Self::BillingAddressState => (
                "billing.address.state".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.state".to_string(),
                    display_name: "state".to_string(),
                    field_type: FieldType::UserAddressState,
                    value: None,
                },
            ),
            Self::BillingAddressZip => (
                "billing.address.zip".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.zip".to_string(),
                    display_name: "zip".to_string(),
                    field_type: FieldType::UserAddressPincode,
                    value: None,
                },
            ),
            Self::BillingCountries(countries) => (
                "billing.address.country".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.country".to_string(),
                    display_name: "country".to_string(),
                    field_type: FieldType::UserCountry {
                        options: countries.iter().map(|c| c.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::BillingAddressCountries(countries) => (
                "billing.address.country".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.billing.address.country".to_string(),
                    display_name: "country".to_string(),
                    field_type: FieldType::UserAddressCountry {
                        options: countries.iter().map(|c| c.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::ShippingFirstName => (
                "shipping.address.first_name".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.first_name".to_string(),
                    display_name: "shipping_first_name".to_string(),
                    field_type: FieldType::UserShippingName,
                    value: None,
                },
            ),
            Self::ShippingLastName => (
                "shipping.address.last_name".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.last_name".to_string(),
                    display_name: "shipping_last_name".to_string(),
                    field_type: FieldType::UserShippingName,
                    value: None,
                },
            ),
            Self::ShippingAddressCity => (
                "shipping.address.city".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.city".to_string(),
                    display_name: "city".to_string(),
                    field_type: FieldType::UserShippingAddressCity,
                    value: None,
                },
            ),
            Self::ShippingAddressState => (
                "shipping.address.state".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.state".to_string(),
                    display_name: "state".to_string(),
                    field_type: FieldType::UserShippingAddressState,
                    value: None,
                },
            ),
            Self::ShippingAddressZip => (
                "shipping.address.zip".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.zip".to_string(),
                    display_name: "zip".to_string(),
                    field_type: FieldType::UserShippingAddressPincode,
                    value: None,
                },
            ),
            Self::ShippingCountries(countries) => (
                "shipping.address.country".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.country".to_string(),
                    display_name: "country".to_string(),
                    field_type: FieldType::UserCountry {
                        options: countries.iter().map(|c| c.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::ShippingAddressCountries(countries) => (
                "shipping.address.country".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.country".to_string(),
                    display_name: "country".to_string(),
                    field_type: FieldType::UserShippingAddressCountry {
                        options: countries.iter().map(|c| c.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::ShippingAddressLine1 => (
                "shipping.address.line1".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.line1".to_string(),
                    display_name: "line1".to_string(),
                    field_type: FieldType::UserShippingAddressLine1,
                    value: None,
                },
            ),
            Self::ShippingAddressLine2 => (
                "shipping.address.line2".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.address.line2".to_string(),
                    display_name: "line2".to_string(),
                    field_type: FieldType::UserShippingAddressLine2,
                    value: None,
                },
            ),
            Self::ShippingPhone => (
                "shipping.phone.number".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.phone.number".to_string(),
                    display_name: "phone_number".to_string(),
                    field_type: FieldType::UserPhoneNumber,
                    value: None,
                },
            ),
            Self::ShippingPhoneCountryCode => (
                "shipping.phone.country_code".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.phone.country_code".to_string(),
                    display_name: "dialing_code".to_string(),
                    field_type: FieldType::UserPhoneNumberCountryCode,
                    value: None,
                },
            ),
            Self::ShippingEmail => (
                "shipping.email".to_string(),
                RequiredFieldInfo {
                    required_field: "shipping.email".to_string(),
                    display_name: "email".to_string(),
                    field_type: FieldType::UserEmailAddress,
                    value: None,
                },
            ),
            Self::OpenBankingUkIssuer => (
                "payment_method_data.bank_redirect.open_banking_uk.issuer".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.open_banking_uk.issuer"
                        .to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::OpenBankingCzechRepublicIssuer => (
                "payment_method_data.bank_redirect.open_banking_czech_republic.issuer".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.open_banking_czech_republic.issuer"
                            .to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::OpenBankingPolandIssuer => (
                "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::OpenBankingSlovakiaIssuer => (
                "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::OpenBankingFpxIssuer => (
                "payment_method_data.bank_redirect.open_banking_fpx.issuer".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.open_banking_fpx.issuer"
                        .to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::OpenBankingThailandIssuer => (
                "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(),
                    display_name: "issuer".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::BanContactCardNumber => (
                "payment_method_data.bank_redirect.bancontact_card.card_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.bancontact_card.card_number"
                        .to_string(),
                    display_name: "card_number".to_string(),
                    field_type: FieldType::UserCardNumber,
                    value: None,
                },
            ),
            Self::BanContactCardExpMonth => (
                "payment_method_data.bank_redirect.bancontact_card.card_exp_month".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.bancontact_card.card_exp_month"
                            .to_string(),
                    display_name: "card_exp_month".to_string(),
                    field_type: FieldType::UserCardExpiryMonth,
                    value: None,
                },
            ),
            Self::BanContactCardExpYear => (
                "payment_method_data.bank_redirect.bancontact_card.card_exp_year".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_redirect.bancontact_card.card_exp_year"
                            .to_string(),
                    display_name: "card_exp_year".to_string(),
                    field_type: FieldType::UserCardExpiryYear,
                    value: None,
                },
            ),
            Self::IdealBankName => (
                "payment_method_data.bank_redirect.ideal.bank_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(),
                    display_name: "bank_name".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::EpsBankName => (
                "payment_method_data.bank_redirect.eps.bank_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(),
                    display_name: "bank_name".to_string(),
                    field_type: FieldType::UserBank,
                    value: None,
                },
            ),
            Self::EpsBankOptions(bank) => (
                "payment_method_data.bank_redirect.eps.bank_name".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(),
                    display_name: "bank_name".to_string(),
                    field_type: FieldType::UserBankOptions {
                        options: bank.iter().map(|bank| bank.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::BlikCode => (
                "payment_method_data.bank_redirect.blik.blik_code".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_redirect.blik.blik_code".to_string(),
                    display_name: "blik_code".to_string(),
                    field_type: FieldType::UserBlikCode,
                    value: None,
                },
            ),
            Self::MifinityDateOfBirth => (
                "payment_method_data.wallet.mifinity.date_of_birth".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.wallet.mifinity.date_of_birth".to_string(),
                    display_name: "date_of_birth".to_string(),
                    field_type: FieldType::UserDateOfBirth,
                    value: None,
                },
            ),
            Self::MifinityLanguagePreference(languages) => (
                "payment_method_data.wallet.mifinity.language_preference".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.wallet.mifinity.language_preference"
                        .to_string(),
                    display_name: "language_preference".to_string(),
                    field_type: FieldType::LanguagePreference {
                        options: languages.iter().map(|l| l.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::CryptoNetwork => (
                "payment_method_data.crypto.network".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.crypto.network".to_string(),
                    display_name: "network".to_string(),
                    field_type: FieldType::UserCryptoCurrencyNetwork,
                    value: None,
                },
            ),
            Self::CyptoPayCurrency(currencies) => (
                "payment_method_data.crypto.pay_currency".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.crypto.pay_currency".to_string(),
                    display_name: "currency".to_string(),
                    field_type: FieldType::UserCurrency {
                        options: currencies.iter().map(|c| c.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::BoletoSocialSecurityNumber => (
                "payment_method_data.voucher.boleto.social_security_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.voucher.boleto.social_security_number"
                        .to_string(),
                    display_name: "social_security_number".to_string(),
                    field_type: FieldType::UserSocialSecurityNumber,
                    value: None,
                },
            ),
            Self::UpiCollectVpaId => (
                "payment_method_data.upi.upi_collect.vpa_id".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.upi.upi_collect.vpa_id".to_string(),
                    display_name: "vpa_id".to_string(),
                    field_type: FieldType::UserVpaId,
                    value: None,
                },
            ),
            Self::AchBankDebitAccountNumber => (
                "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number"
                        .to_string(),
                    display_name: "bank_account_number".to_string(),
                    field_type: FieldType::UserBankAccountNumber,
                    value: None,
                },
            ),
            Self::AchBankDebitRoutingNumber => (
                "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number"
                        .to_string(),
                    display_name: "bank_routing_number".to_string(),
                    field_type: FieldType::UserBankRoutingNumber,
                    value: None,
                },
            ),
            Self::AchBankDebitBankType(bank_type) => (
                "payment_method_data.bank_debit.ach_bank_debit.bank_type".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_type"
                        .to_string(),
                    display_name: "bank_type".to_string(),
                    field_type: FieldType::UserBankType {
                        options: bank_type.iter().map(|bt| bt.to_string()).collect(),
                    },
                    value: None,
                },
            ),
            Self::AchBankDebitBankAccountHolderName => (
                "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name"
                    .to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name"
                            .to_string(),
                    display_name: "bank_account_holder_name".to_string(),
                    field_type: FieldType::UserBankAccountHolderName,
                    value: None,
                },
            ),
            Self::SepaBankDebitIban => (
                "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban"
                        .to_string(),
                    display_name: "iban".to_string(),
                    field_type: FieldType::UserIban,
                    value: None,
                },
            ),
            Self::BacsBankDebitAccountNumber => (
                "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number"
                        .to_string(),
                    display_name: "bank_account_number".to_string(),
                    field_type: FieldType::UserBankAccountNumber,
                    value: None,
                },
            ),
            Self::BacsBankDebitSortCode => (
                "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code"
                        .to_string(),
                    display_name: "bank_sort_code".to_string(),
                    field_type: FieldType::UserBankSortCode,
                    value: None,
                },
            ),
            Self::BecsBankDebitAccountNumber => (
                "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number"
                        .to_string(),
                    display_name: "bank_account_number".to_string(),
                    field_type: FieldType::UserBankAccountNumber,
                    value: None,
                },
            ),
            Self::BecsBankDebitBsbNumber => (
                "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.becs_bank_debit.bsb_number"
                        .to_string(),
                    display_name: "bsb_number".to_string(),
                    field_type: FieldType::UserBsbNumber,
                    value: None,
                },
            ),
            Self::BecsBankDebitSortCode => (
                "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_debit.becs_bank_debit.sort_code"
                        .to_string(),
                    display_name: "bank_sort_code".to_string(),
                    field_type: FieldType::UserBankSortCode,
                    value: None,
                },
            ),
            Self::PixKey => (
                "payment_method_data.bank_transfer.pix.pix_key".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_transfer.pix.pix_key".to_string(),
                    display_name: "pix_key".to_string(),
                    field_type: FieldType::UserPixKey,
                    value: None,
                },
            ),
            Self::PixCnpj => (
                "payment_method_data.bank_transfer.pix.cnpj".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_transfer.pix.cnpj".to_string(),
                    display_name: "cnpj".to_string(),
                    field_type: FieldType::UserCnpj,
                    value: None,
                },
            ),
            Self::PixCpf => (
                "payment_method_data.bank_transfer.pix.cpf".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_transfer.pix.cpf".to_string(),
                    display_name: "cpf".to_string(),
                    field_type: FieldType::UserCpf,
                    value: None,
                },
            ),
            Self::PixSourceBankAccountId => (
                "payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.bank_transfer.pix.source_bank_account_id"
                        .to_string(),
                    display_name: "source_bank_account_id".to_string(),
                    field_type: FieldType::UserSourceBankAccountId,
                    value: None,
                },
            ),
            Self::GiftCardNumber => (
                "payment_method_data.gift_card.number".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.gift_card.givex.number".to_string(),
                    display_name: "gift_card_number".to_string(),
                    field_type: FieldType::UserCardNumber,
                    value: None,
                },
            ),
            Self::GiftCardCvc => (
                "payment_method_data.gift_card.cvc".to_string(),
                RequiredFieldInfo {
                    required_field: "payment_method_data.gift_card.givex.cvc".to_string(),
                    display_name: "gift_card_cvc".to_string(),
                    field_type: FieldType::UserCardCvc,
                    value: None,
                },
            ),
            Self::DcbMsisdn => (
                "payment_method_data.mobile_payment.direct_carrier_billing.msisdn".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.mobile_payment.direct_carrier_billing.msisdn"
                            .to_string(),
                    display_name: "mobile_number".to_string(),
                    field_type: FieldType::UserMsisdn,
                    value: None,
                },
            ),
            Self::DcbClientUid => (
                "payment_method_data.mobile_payment.direct_carrier_billing.client_uid".to_string(),
                RequiredFieldInfo {
                    required_field:
                        "payment_method_data.mobile_payment.direct_carrier_billing.client_uid"
                            .to_string(),
                    display_name: "client_identifier".to_string(),
                    field_type: FieldType::UserClientIdentifier,
                    value: None,
                },
            ),
            Self::OrderDetailsProductName => (
                "order_details.0.product_name".to_string(),
                RequiredFieldInfo {
                    required_field: "order_details.0.product_name".to_string(),
                    display_name: "product_name".to_string(),
                    field_type: FieldType::OrderDetailsProductName,
                    value: None,
                },
            ),
            Self::Description => (
                "description".to_string(),
                RequiredFieldInfo {
                    required_field: "description".to_string(),
                    display_name: "description".to_string(),
                    field_type: FieldType::Text,
                    value: None,
                },
            ),
        }
    }
}

// Define helper functions for common field groups
#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn card_basic() -> Vec<RequiredField> {
    vec![
        RequiredField::CardNumber,
        RequiredField::CardExpMonth,
        RequiredField::CardExpYear,
        RequiredField::CardCvc,
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn full_name() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingUserFirstName,
        RequiredField::BillingUserLastName,
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_name() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
        RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_billing_name() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingEmail,
        RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
        RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_billing_name_phone() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName),
        RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName),
        RequiredField::BillingEmail,
        RequiredField::BillingPhone,
        RequiredField::BillingPhoneCountryCode,
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn email() -> Vec<RequiredField> {
    [RequiredField::Email].to_vec()
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email() -> Vec<RequiredField> {
    [RequiredField::BillingEmail].to_vec()
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn card_with_name() -> Vec<RequiredField> {
    [card_basic(), full_name()].concat()
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_email_name() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingEmail,
        RequiredField::BillingUserFirstName,
        RequiredField::BillingUserLastName,
    ]
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn billing_address() -> Vec<RequiredField> {
    vec![
        RequiredField::BillingAddressCity,
        RequiredField::BillingAddressState,
        RequiredField::BillingAddressZip,
        RequiredField::BillingAddressCountries(vec!["ALL"]),
        RequiredField::BillingAddressLine1,
    ]
}

/// Define the mandate, non-mandate, and common required fields for a connector
/// Eg: fields(vec![RequiredField::CardNumber], vec![RequiredField::BillingEmail], vec![RequiredField::BillingAddressCity])
#[cfg(feature = "v1")]
fn fields(
    mandate: Vec<RequiredField>,
    non_mandate: Vec<RequiredField>,
    common: Vec<RequiredField>,
) -> RequiredFieldFinal {
    let mandate_fields: HashMap<_, _> = mandate.iter().map(|f| f.to_tuple()).collect();
    let non_mandate_fields: HashMap<_, _> = non_mandate.iter().map(|f| f.to_tuple()).collect();
    let common_fields: HashMap<_, _> = common.iter().map(|f| f.to_tuple()).collect();
    RequiredFieldFinal {
        mandate: mandate_fields,
        non_mandate: non_mandate_fields,
        common: common_fields,
    }
}

#[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2
fn connectors(connectors: Vec<(Connector, RequiredFieldFinal)>) -> ConnectorFields {
    ConnectorFields {
        fields: connectors.into_iter().collect(),
    }
}

pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> {
    HashMap::from([
        RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName)
            .to_tuple(),
        RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName).to_tuple(),
        RequiredField::BillingAddressCity.to_tuple(),
        RequiredField::BillingAddressState.to_tuple(),
        RequiredField::BillingAddressZip.to_tuple(),
        RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(),
        RequiredField::BillingAddressLine1.to_tuple(),
        RequiredField::BillingAddressLine2.to_tuple(),
        RequiredField::BillingPhone.to_tuple(),
        RequiredField::BillingPhoneCountryCode.to_tuple(),
        RequiredField::BillingEmail.to_tuple(),
    ])
}

pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
    HashMap::from([
        RequiredField::ShippingFirstName.to_tuple(),
        RequiredField::ShippingLastName.to_tuple(),
        RequiredField::ShippingAddressCity.to_tuple(),
        RequiredField::ShippingAddressState.to_tuple(),
        RequiredField::ShippingAddressZip.to_tuple(),
        RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(),
        RequiredField::ShippingAddressLine1.to_tuple(),
        RequiredField::ShippingPhone.to_tuple(),


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

pub fn perform_session_token_routing<F, D>(
    state: SessionState,
    merchant_context: &domain::MerchantContext,
    business_profile: &domain::Profile,
    payment_data: &mut D,
    connectors: api::SessionConnectorDatas,
) -> RouterResult<api::SessionConnectorDatas>
where
    F: Clone,
    D: OperationSessionGetters<F> + OperationSessionSetters<F>,


// Struct: NestedErrorStack
// File: crates/router/src/core/errors.rs
// Module: router
// Implementations: 0

pub struct NestedErrorStack<'a>


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

impl ConnectorValidation for for Facilitapay


// Struct: CurrentFlow
// File: crates/router/src/types/domain/user/decision_manager.rs
// Module: router
// Implementations: 1

pub struct CurrentFlow


// Struct: EncryptedJsonType
// File: crates/hyperswitch_domain_models/src/type_encryption.rs
// Module: hyperswitch_domain_models
// Implementations: 3
// Traits: std::ops::Deref

pub struct EncryptedJsonType<T>


// Implementation: impl masking::SerializableSecret for for OrderDetailsWithAmount
// File: crates/diesel_models/src/types.rs
// Module: diesel_models
// Methods: 0 total (0 public)

impl masking::SerializableSecret for for OrderDetailsWithAmount


// Implementation: impl SessionState
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 4 total (4 public)

impl SessionState


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

pub fn update_conditional_config_id(&mut self, ids: String)


// Implementation: impl OrganizationBridge for for Organization
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
// Methods: 3 total (0 public)

impl OrganizationBridge for for Organization


// Struct: NetceteraAuthenticationSuccessResponse
// File: crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NetceteraAuthenticationSuccessResponse


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

pub fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError>


// Implementation: impl api::PaymentsPreProcessing for for Trustpay
// File: crates/hyperswitch_connectors/src/connectors/trustpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentsPreProcessing for for Trustpay


// Function: get_profile_outgoing_webhook_events
// File: crates/router/src/analytics.rs
// Module: router

pub fn get_profile_outgoing_webhook_events(
        state: web::Data<AppState>,
        req: actix_web::HttpRequest,
        json_payload: web::Query<
            api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest,
        >,
    ) -> impl Responder


// Struct: NoonCard
// File: crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NoonCard


// Function: apply_changeset
// File: crates/diesel_models/src/business_profile.rs
// Module: diesel_models

pub fn apply_changeset(self, source: Profile) -> Profile


// Function: customers_list
// File: crates/router/src/routes/customers.rs
// Module: router

pub fn customers_list(
    state: web::Data<AppState>,
    req: HttpRequest,
    query: web::Query<customers::CustomerListRequest>,
) -> HttpResponse


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

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


// Struct: PaymentOptions
// File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PaymentOptions


// Module Structure
// File: crates/router/src/core/user.rs
// Module: router

// Public submodules:
pub mod dashboard_metadata;
pub mod sample_data;
pub mod theme;


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

impl api::PaymentCapture for for Inespay


// Implementation: impl api::PaymentVoid for for Paysafe
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentVoid for for Paysafe


// Function: deep_health_check
// File: crates/drainer/src/health_check.rs
// Module: drainer

pub fn deep_health_check(
    conf: web::Data<Settings>,
    stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder


// File: crates/api_models/src/user_role.rs
// Module: api_models
// Public structs: 9

use common_enums::{ParentGroup, PermissionGroup};
use common_utils::pii;
use masking::Secret;

pub mod role;

#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);

#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum AuthorizationInfo {
    Group(GroupInfo),
    GroupWithTag(ParentInfo),
}

// TODO: To be deprecated
#[derive(Debug, serde::Serialize)]
pub struct GroupInfo {
    pub group: PermissionGroup,
    pub description: &'static str,
}

#[derive(Debug, serde::Serialize, Clone)]
pub struct ParentInfo {
    pub name: ParentGroup,
    pub description: &'static str,
    pub groups: Vec<PermissionGroup>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserRoleRequest {
    pub email: pii::Email,
    pub role_id: String,
}

#[derive(Debug, serde::Serialize)]
pub enum UserStatus {
    Active,
    InvitationSent,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
    pub email: pii::Email,
}

#[derive(Debug, serde::Serialize)]
pub struct ListUsersInEntityResponse {
    pub email: pii::Email,
    pub roles: Vec<role::MinimalRoleInfo>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListInvitationForUserResponse {
    pub entity_id: String,
    pub entity_type: common_enums::EntityType,
    pub entity_name: Option<Secret<String>>,
    pub role_id: String,
}

pub type AcceptInvitationsV2Request = Vec<Entity>;
pub type AcceptInvitationsPreAuthRequest = Vec<Entity>;

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Entity {
    pub entity_id: String,
    pub entity_type: common_enums::EntityType,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListUsersInEntityRequest {
    pub entity_type: Option<common_enums::EntityType>,
}


// Implementation: impl api::RefundExecute for for Paytm
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::RefundExecute for for Paytm


// Implementation: impl api::PaymentVoid for for Checkout
// File: crates/hyperswitch_connectors/src/connectors/checkout.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentVoid for for Checkout


// Implementation: impl OrganizationBridge for for OrganizationNew
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
// Methods: 3 total (0 public)

impl OrganizationBridge for for OrganizationNew