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

#[cfg(feature = "v2")]
use crate::business_profile::Profile;
#[cfg(feature = "v1")]
use crate::errors;

#[cfg(feature = "v1")]
pub struct RefundListConstraints {
    pub payment_id: Option<common_utils::id_type::PaymentId>,
    pub refund_id: Option<String>,
    pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
    pub limit: Option<i64>,
    pub offset: Option<i64>,
    pub time_range: Option<common_utils::types::TimeRange>,
    pub amount_filter: Option<api_models::payments::AmountFilter>,
    pub connector: Option<Vec<String>>,
    pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
    pub currency: Option<Vec<common_enums::Currency>>,
    pub refund_status: Option<Vec<common_enums::RefundStatus>>,
}

#[cfg(feature = "v2")]
pub struct RefundListConstraints {
    pub payment_id: Option<common_utils::id_type::GlobalPaymentId>,
    pub refund_id: Option<common_utils::id_type::GlobalRefundId>,
    pub profile_id: common_utils::id_type::ProfileId,
    pub limit: Option<i64>,
    pub offset: Option<i64>,
    pub time_range: Option<common_utils::types::TimeRange>,
    pub amount_filter: Option<api_models::payments::AmountFilter>,
    pub connector: Option<Vec<String>>,
    pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
    pub currency: Option<Vec<common_enums::Currency>>,
    pub refund_status: Option<Vec<common_enums::RefundStatus>>,
}

#[cfg(feature = "v1")]
impl
    TryFrom<(
        api_models::refunds::RefundListRequest,
        Option<Vec<common_utils::id_type::ProfileId>>,
    )> for RefundListConstraints
{
    type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;

    fn try_from(
        (value, auth_profile_id_list): (
            api_models::refunds::RefundListRequest,
            Option<Vec<common_utils::id_type::ProfileId>>,
        ),
    ) -> Result<Self, Self::Error> {
        let api_models::refunds::RefundListRequest {
            connector,
            currency,
            refund_status,
            payment_id,
            refund_id,
            profile_id,
            limit,
            offset,
            time_range,
            amount_filter,
            merchant_connector_id,
        } = value;
        let profile_id_from_request_body = profile_id;
        let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
            (None, None) => None,
            (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
            (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
            (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
                let profile_id_from_request_body_is_available_in_auth_profile_id_list =
                    auth_profile_id_list.contains(&profile_id_from_request_body);

                if profile_id_from_request_body_is_available_in_auth_profile_id_list {
                    Some(vec![profile_id_from_request_body])
                } else {
                    // This scenario is very unlikely to happen
                    return Err(error_stack::Report::new(
                        errors::api_error_response::ApiErrorResponse::PreconditionFailed {
                            message: format!(
                                "Access not available for the given profile_id {profile_id_from_request_body:?}",

                            ),
                        },
                    ));
                }
            }
        };
        Ok(Self {
            payment_id,
            refund_id,
            profile_id: profile_id_list,
            limit,
            offset,
            time_range,
            amount_filter,
            connector,
            merchant_connector_id,
            currency,
            refund_status,
        })
    }
}

#[cfg(feature = "v2")]
impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints {
    fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self {
        let api_models::refunds::RefundListRequest {
            payment_id,
            refund_id,
            connector,
            currency,
            refund_status,
            limit,
            offset,
            time_range,
            amount_filter,
            connector_id_list,
        } = value;

        Self {
            payment_id,
            refund_id,
            profile_id: profile.get_id().to_owned(),
            limit,
            offset,
            time_range,
            amount_filter,
            connector,
            connector_id_list,
            currency,
            refund_status,
        }
    }
}


// Struct: SdkPaymentsSessionUpdateData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct SdkPaymentsSessionUpdateData


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

pub struct PaypalConfirmRequest


// Implementation: impl super::KafkaMessage for for KafkaFraudCheck
// File: crates/router/src/services/kafka/fraud_check.rs
// Module: router
// Methods: 2 total (0 public)

impl super::KafkaMessage for for KafkaFraudCheck


// Struct: TaxjarRouterData
// File: crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct TaxjarRouterData<T>


// Struct: StripePaymentMethod
// File: crates/router/src/compatibility/stripe/setup_intents/types.rs
// Module: router
// Implementations: 0

pub struct StripePaymentMethod


// Struct: FieldError
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct FieldError


// Struct: Reject
// File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct Reject


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

pub struct MonerisAuthRequest


// File: crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
// Module: analytics

use std::collections::HashSet;

use api_models::analytics::{
    auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier},
    Granularity, TimeRange,
};
use common_enums::DecoupledAuthenticationType;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

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

#[derive(Default)]
pub(super) struct FrictionlessFlowCount;

#[async_trait::async_trait]
impl<T> super::AuthEventMetric<T> for FrictionlessFlowCount
where
    T: AnalyticsDataSource + super::AuthEventMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        auth: &AuthInfo,
        dimensions: &[AuthEventDimensions],
        filters: &AuthEventFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> {
        let mut query_builder: QueryBuilder<T> =
            QueryBuilder::new(AnalyticsCollection::Authentications);
        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()?;

        query_builder
            .add_filter_clause(
                "authentication_type",
                DecoupledAuthenticationType::Frictionless,
            )
            .switch()?;
        filters.set_filter_clause(&mut query_builder).switch()?;
        time_range
            .set_filter_clause(&mut query_builder)
            .attach_printable("Error filtering time range")
            .switch()?;
        auth.set_filter_clause(&mut query_builder).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::<AuthEventMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    AuthEventMetricsBucketIdentifier::new(
                        i.authentication_status.as_ref().map(|i| i.0),
                        i.trans_status.as_ref().map(|i| i.0.clone()),
                        i.authentication_type.as_ref().map(|i| i.0),
                        i.error_message.clone(),
                        i.authentication_connector.as_ref().map(|i| i.0),
                        i.message_version.clone(),
                        i.acs_reference_number.clone(),
                        i.mcc.clone(),
                        i.currency.as_ref().map(|i| i.0),
                        i.merchant_country.clone(),
                        i.billing_country.clone(),
                        i.shipping_country.clone(),
                        i.issuer_country.clone(),
                        i.earliest_supported_version.clone(),
                        i.latest_supported_version.clone(),
                        i.whitelist_decision,
                        i.device_manufacturer.clone(),
                        i.device_type.clone(),
                        i.device_brand.clone(),
                        i.device_os.clone(),
                        i.device_display.clone(),
                        i.browser_name.clone(),
                        i.browser_version.clone(),
                        i.issuer_id.clone(),
                        i.scheme_name.clone(),
                        i.exemption_requested,
                        i.exemption_accepted,
                        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<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>,
                crate::query::PostProcessingError,
            >>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


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

pub struct CustomerDetails


// Function: retry_sync_task
// File: crates/router/src/workflows/dispute_list.rs
// Module: router

// Documentation: Schedule the task for retry  Returns bool which indicates whether this was the last retry or not

pub fn retry_sync_task(
    db: &dyn StorageInterface,
    connector: String,
    merchant_id: common_utils::id_type::MerchantId,
    pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError>


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

pub struct SwitchOrganizationRequest


// File: crates/hyperswitch_interfaces/src/api/payments_v2.rs
// Module: hyperswitch_interfaces

//! Payments V2 interface

use hyperswitch_domain_models::{
    router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, PaymentFlowData},
    router_flow_types::{
        payments::{
            Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
            CreateConnectorCustomer, CreateOrder, ExternalVaultProxy, IncrementalAuthorization,
            PSync, PaymentMethodToken, PostCaptureVoid, PostProcessing, PostSessionTokens,
            PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
        },
        Authenticate, GiftCardBalanceCheck, PostAuthenticate, PreAuthenticate,
    },
    router_request_types::{
        AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
        CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData,
        PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthenticateData,
        PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData,
        PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData,
        PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,
        PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData,
        PaymentsTaxCalculationData, PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData,
        SetupMandateRequestData,
    },
    router_response_types::{
        GiftCardBalanceCheckResponseData, PaymentsResponseData, TaxCalculationResponseData,
    },
};

use crate::api::{
    ConnectorCommon, ConnectorIntegrationV2, ConnectorSpecifications, ConnectorValidation,
};

/// trait PaymentAuthorizeV2
pub trait PaymentAuthorizeV2:
    ConnectorIntegrationV2<Authorize, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData>
{
}

/// trait PaymentAuthorizeSessionTokenV2
pub trait PaymentAuthorizeSessionTokenV2:
    ConnectorIntegrationV2<
    AuthorizeSessionToken,
    PaymentFlowData,
    AuthorizeSessionTokenData,
    PaymentsResponseData,
>
{
}

/// trait PaymentSyncV2
pub trait PaymentSyncV2:
    ConnectorIntegrationV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
}

/// trait PaymentVoidV2
pub trait PaymentVoidV2:
    ConnectorIntegrationV2<Void, PaymentFlowData, PaymentsCancelData, PaymentsResponseData>
{
}

/// trait PaymentPostCaptureVoidV2
pub trait PaymentPostCaptureVoidV2:
    ConnectorIntegrationV2<
    PostCaptureVoid,
    PaymentFlowData,
    PaymentsCancelPostCaptureData,
    PaymentsResponseData,
>
{
}

/// trait PaymentApproveV2
pub trait PaymentApproveV2:
    ConnectorIntegrationV2<Approve, PaymentFlowData, PaymentsApproveData, PaymentsResponseData>
{
}

/// trait PaymentRejectV2
pub trait PaymentRejectV2:
    ConnectorIntegrationV2<Reject, PaymentFlowData, PaymentsRejectData, PaymentsResponseData>
{
}

/// trait PaymentCaptureV2
pub trait PaymentCaptureV2:
    ConnectorIntegrationV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
}

/// trait PaymentSessionV2
pub trait PaymentSessionV2:
    ConnectorIntegrationV2<Session, PaymentFlowData, PaymentsSessionData, PaymentsResponseData>
{
}

/// trait MandateSetupV2
pub trait MandateSetupV2:
    ConnectorIntegrationV2<SetupMandate, PaymentFlowData, SetupMandateRequestData, PaymentsResponseData>
{
}

/// trait PaymentIncrementalAuthorizationV2
pub trait PaymentIncrementalAuthorizationV2:
    ConnectorIntegrationV2<
    IncrementalAuthorization,
    PaymentFlowData,
    PaymentsIncrementalAuthorizationData,
    PaymentsResponseData,
>
{
}

///trait TaxCalculationV2
pub trait TaxCalculationV2:
    ConnectorIntegrationV2<
    CalculateTax,
    PaymentFlowData,
    PaymentsTaxCalculationData,
    TaxCalculationResponseData,
>
{
}

///trait PaymentSessionUpdateV2
pub trait PaymentSessionUpdateV2:
    ConnectorIntegrationV2<
    SdkSessionUpdate,
    PaymentFlowData,
    SdkPaymentsSessionUpdateData,
    PaymentsResponseData,
>
{
}

///trait PaymentPostSessionTokensV2
pub trait PaymentPostSessionTokensV2:
    ConnectorIntegrationV2<
    PostSessionTokens,
    PaymentFlowData,
    PaymentsPostSessionTokensData,
    PaymentsResponseData,
>
{
}

/// trait ConnectorCreateOrderV2
pub trait PaymentCreateOrderV2:
    ConnectorIntegrationV2<CreateOrder, PaymentFlowData, CreateOrderRequestData, PaymentsResponseData>
{
}

/// trait PaymentUpdateMetadataV2
pub trait PaymentUpdateMetadataV2:
    ConnectorIntegrationV2<
    UpdateMetadata,
    PaymentFlowData,
    PaymentsUpdateMetadataData,
    PaymentsResponseData,
>
{
}

/// trait PaymentsCompleteAuthorizeV2
pub trait PaymentsCompleteAuthorizeV2:
    ConnectorIntegrationV2<
    CompleteAuthorize,
    PaymentFlowData,
    CompleteAuthorizeData,
    PaymentsResponseData,
>
{
}

/// trait PaymentTokenV2
pub trait PaymentTokenV2:
    ConnectorIntegrationV2<
    PaymentMethodToken,
    PaymentFlowData,
    PaymentMethodTokenizationData,
    PaymentsResponseData,
>
{
}

/// trait ConnectorCustomerV2
pub trait ConnectorCustomerV2:
    ConnectorIntegrationV2<
    CreateConnectorCustomer,
    PaymentFlowData,
    ConnectorCustomerData,
    PaymentsResponseData,
>
{
}

/// trait PaymentsPreProcessingV2
pub trait PaymentsPreProcessingV2:
    ConnectorIntegrationV2<
    PreProcessing,
    PaymentFlowData,
    PaymentsPreProcessingData,
    PaymentsResponseData,
>
{
}

/// trait PaymentsGiftCardBalanceCheckV2
pub trait PaymentsGiftCardBalanceCheckV2:
    ConnectorIntegrationV2<
    GiftCardBalanceCheck,
    GiftCardBalanceCheckFlowData,
    GiftCardBalanceCheckRequestData,
    GiftCardBalanceCheckResponseData,
>
{
}

/// trait PaymentsPreAuthenticateV2
pub trait PaymentsPreAuthenticateV2:
    ConnectorIntegrationV2<
    PreAuthenticate,
    PaymentFlowData,
    PaymentsPreAuthenticateData,
    PaymentsResponseData,
>
{
}

/// trait PaymentsAuthenticateV2
pub trait PaymentsAuthenticateV2:
    ConnectorIntegrationV2<
    Authenticate,
    PaymentFlowData,
    PaymentsAuthenticateData,
    PaymentsResponseData,
>
{
}

/// trait PaymentsPostAuthenticateV2
pub trait PaymentsPostAuthenticateV2:
    ConnectorIntegrationV2<
    PostAuthenticate,
    PaymentFlowData,
    PaymentsPostAuthenticateData,
    PaymentsResponseData,
>
{
}
/// trait PaymentsPostProcessingV2
pub trait PaymentsPostProcessingV2:
    ConnectorIntegrationV2<
    PostProcessing,
    PaymentFlowData,
    PaymentsPostProcessingData,
    PaymentsResponseData,
>
{
}

/// trait ExternalVaultProxyPaymentsCreate
pub trait ExternalVaultProxyPaymentsCreate:
    ConnectorIntegrationV2<
    ExternalVaultProxy,
    PaymentFlowData,
    ExternalVaultProxyPaymentsData,
    PaymentsResponseData,
>
{
}

/// trait PaymentV2
pub trait PaymentV2:
    ConnectorCommon
    + ConnectorSpecifications
    + ConnectorValidation
    + PaymentAuthorizeV2
    + PaymentAuthorizeSessionTokenV2
    + PaymentsCompleteAuthorizeV2
    + PaymentSyncV2
    + PaymentCaptureV2
    + PaymentVoidV2
    + PaymentPostCaptureVoidV2
    + PaymentApproveV2
    + PaymentRejectV2
    + MandateSetupV2
    + PaymentSessionV2
    + PaymentTokenV2
    + PaymentsPreProcessingV2
    + PaymentsPostProcessingV2
    + ConnectorCustomerV2
    + PaymentIncrementalAuthorizationV2
    + TaxCalculationV2
    + PaymentSessionUpdateV2
    + PaymentPostSessionTokensV2
    + PaymentUpdateMetadataV2
    + PaymentCreateOrderV2
    + ExternalVaultProxyPaymentsCreate
    + PaymentsGiftCardBalanceCheckV2
{
}


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

pub fn get_merchant_auth_events_filters(
        state: web::Data<AppState>,
        req: actix_web::HttpRequest,
        json_payload: web::Json<GetAuthEventFilterRequest>,
    ) -> impl Responder


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

pub struct PaymentSuccessCount


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

impl api::Refund for for Multisafepay


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

impl MandateSetup for for Signifyd


// Implementation: impl api::UasPreAuthenticationV2 for for Recurly
// File: crates/hyperswitch_connectors/src/connectors/recurly.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::UasPreAuthenticationV2 for for Recurly


// Implementation: impl RequestIdStore for for KafkaStore
// File: crates/router/src/db.rs
// Module: router
// Methods: 1 total (0 public)

impl RequestIdStore for for KafkaStore


// Function: elimination_routing_update_configs
// File: crates/router/src/core/routing.rs
// Module: router

pub fn elimination_routing_update_configs(
    state: SessionState,
    request: routing_types::EliminationRoutingConfig,
    algorithm_id: common_utils::id_type::RoutingId,
    profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord>


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

pub fn get_scope(&self) -> RoleScope


// Function: get_metrics
// File: crates/analytics/src/refunds/core.rs
// Module: analytics

pub fn get_metrics(
    pool: &AnalyticsProvider,
    ex_rates: &Option<ExchangeRates>,
    auth: &AuthInfo,
    req: GetRefundMetricRequest,
) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>>


// Implementation: impl ClientSecretId
// File: crates/common_utils/src/id_type/client_secret.rs
// Module: common_utils
// Methods: 1 total (1 public)

impl ClientSecretId


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

impl api::PaymentToken for for Nexinets


// Implementation: impl std::fmt::Display for for TrustpaymentsErrorCode
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl std::fmt::Display for for TrustpaymentsErrorCode


// Struct: TaxjarErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct TaxjarErrorResponse


// File: crates/diesel_models/src/generic_link.rs
// Module: diesel_models
// Public functions: 2
// Public structs: 7

use common_utils::{
    consts,
    link_utils::{
        EnabledPaymentMethod, GenericLinkStatus, GenericLinkUiConfig, PaymentMethodCollectStatus,
        PayoutLinkData, PayoutLinkStatus,
    },
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Duration, PrimitiveDateTime};

use crate::{enums as storage_enums, schema::generic_link};

#[derive(
    Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = generic_link, primary_key(link_id), check_for_backend(diesel::pg::Pg))]
pub struct GenericLink {
    pub link_id: String,
    pub primary_reference: String,
    pub merchant_id: common_utils::id_type::MerchantId,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub created_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub last_modified_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub expiry: PrimitiveDateTime,
    pub link_data: serde_json::Value,
    pub link_status: GenericLinkStatus,
    pub link_type: storage_enums::GenericLinkType,
    pub url: Secret<String>,
    pub return_url: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GenericLinkState {
    pub link_id: String,
    pub primary_reference: String,
    pub merchant_id: common_utils::id_type::MerchantId,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub created_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub last_modified_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub expiry: PrimitiveDateTime,
    pub link_data: GenericLinkData,
    pub link_status: GenericLinkStatus,
    pub link_type: storage_enums::GenericLinkType,
    pub url: Secret<String>,
    pub return_url: Option<String>,
}

#[derive(
    Clone,
    Debug,
    Eq,
    PartialEq,
    Insertable,
    serde::Serialize,
    serde::Deserialize,
    router_derive::DebugAsDisplay,
)]
#[diesel(table_name = generic_link)]
pub struct GenericLinkNew {
    pub link_id: String,
    pub primary_reference: String,
    pub merchant_id: common_utils::id_type::MerchantId,
    #[serde(with = "common_utils::custom_serde::iso8601::option")]
    pub created_at: Option<PrimitiveDateTime>,
    #[serde(with = "common_utils::custom_serde::iso8601::option")]
    pub last_modified_at: Option<PrimitiveDateTime>,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub expiry: PrimitiveDateTime,
    pub link_data: serde_json::Value,
    pub link_status: GenericLinkStatus,
    pub link_type: storage_enums::GenericLinkType,
    pub url: Secret<String>,
    pub return_url: Option<String>,
}

impl Default for GenericLinkNew {
    fn default() -> Self {
        let now = common_utils::date_time::now();

        Self {
            link_id: String::default(),
            primary_reference: String::default(),
            merchant_id: common_utils::id_type::MerchantId::default(),
            created_at: Some(now),
            last_modified_at: Some(now),
            expiry: now + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY),
            link_data: serde_json::Value::default(),
            link_status: GenericLinkStatus::default(),
            link_type: common_enums::GenericLinkType::default(),
            url: Secret::default(),
            return_url: Option::default(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GenericLinkData {
    PaymentMethodCollect(PaymentMethodCollectLinkData),
    PayoutLink(PayoutLinkData),
}

impl GenericLinkData {
    pub fn get_payment_method_collect_data(&self) -> Result<&PaymentMethodCollectLinkData, String> {
        match self {
            Self::PaymentMethodCollect(pm) => Ok(pm),
            _ => Err("Invalid link type for fetching payment method collect data".to_string()),
        }
    }
    pub fn get_payout_link_data(&self) -> Result<&PayoutLinkData, String> {
        match self {
            Self::PayoutLink(pl) => Ok(pl),
            _ => Err("Invalid link type for fetching payout link data".to_string()),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentMethodCollectLink {
    pub link_id: String,
    pub primary_reference: String,
    pub merchant_id: common_utils::id_type::MerchantId,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub created_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub last_modified_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub expiry: PrimitiveDateTime,
    pub link_data: PaymentMethodCollectLinkData,
    pub link_status: PaymentMethodCollectStatus,
    pub link_type: storage_enums::GenericLinkType,
    pub url: Secret<String>,
    pub return_url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodCollectLinkData {
    pub pm_collect_link_id: String,
    pub customer_id: common_utils::id_type::CustomerId,
    pub link: Secret<String>,
    pub client_secret: Secret<String>,
    pub session_expiry: u32,
    #[serde(flatten)]
    pub ui_config: GenericLinkUiConfig,
    pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>,
}

#[derive(Clone, Debug, Identifiable, Queryable, Serialize, Deserialize)]
#[diesel(table_name = generic_link)]
#[diesel(primary_key(link_id))]
pub struct PayoutLink {
    pub link_id: String,
    pub primary_reference: common_utils::id_type::PayoutId,
    pub merchant_id: common_utils::id_type::MerchantId,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub created_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub last_modified_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub expiry: PrimitiveDateTime,
    pub link_data: PayoutLinkData,
    pub link_status: PayoutLinkStatus,
    pub link_type: storage_enums::GenericLinkType,
    pub url: Secret<String>,
    pub return_url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PayoutLinkUpdate {
    StatusUpdate { link_status: PayoutLinkStatus },
}

#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = generic_link)]
pub struct GenericLinkUpdateInternal {
    pub link_status: Option<GenericLinkStatus>,
}

impl From<PayoutLinkUpdate> for GenericLinkUpdateInternal {
    fn from(generic_link_update: PayoutLinkUpdate) -> Self {
        match generic_link_update {
            PayoutLinkUpdate::StatusUpdate { link_status } => Self {
                link_status: Some(GenericLinkStatus::PayoutLink(link_status)),
            },
        }
    }
}


// Function: get_error_reason
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors

pub fn get_error_reason(
    error_info: Option<String>,
    detailed_error_info: Option<String>,
    avs_error_info: Option<String>,
) -> Option<String>


// Implementation: impl PartialEq for for DisputeMetricsBucketIdentifier
// File: crates/api_models/src/analytics/disputes.rs
// Module: api_models
// Methods: 1 total (0 public)

impl PartialEq for for DisputeMetricsBucketIdentifier


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

pub fn call_multiple_connectors_service<F, Op, Req, D>(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    connectors: api::SessionConnectorDatas,
    _operation: &Op,
    mut payment_data: D,
    customer: &Option<domain::Customer>,
    _session_surcharge_details: Option<api::SessionSurchargeDetails>,
    business_profile: &domain::Profile,
    header_payload: HeaderPayload,
    return_raw_connector_response: Option<bool>,
) -> RouterResult<D>
where
    Op: Debug,
    F: Send + Clone + Sync,

    // To create connector flow specific interface data
    D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
    D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
    RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req>,

    // To construct connector flow specific api
    dyn api::Connector:
        services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,


// Struct: ApiKeyExpiryTrackingData
// File: crates/diesel_models/src/api_keys.rs
// Module: diesel_models
// Implementations: 0

pub struct ApiKeyExpiryTrackingData


// Implementation: impl Capturable for for PaymentsCaptureData
// File: crates/router/src/types.rs
// Module: router
// Methods: 2 total (0 public)

impl Capturable for for PaymentsCaptureData


// Struct: GigadatConnectorMetadataObject
// File: crates/hyperswitch_connectors/src/connectors/gigadat/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct GigadatConnectorMetadataObject


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

pub struct CeleroCustomer


// Implementation: impl BizEmailProd
// File: crates/router/src/services/email/types.rs
// Module: router
// Methods: 1 total (1 public)

impl BizEmailProd


// Implementation: impl api::PaymentAuthorizeSessionToken for for Square
// File: crates/hyperswitch_connectors/src/connectors/square.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)

impl api::PaymentAuthorizeSessionToken for for Square


// Struct: ResponseRouterData
// File: crates/router/src/types.rs
// Module: router
// Implementations: 0

pub struct ResponseRouterData<Flow, R, Request, Response>


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

impl PaymentCapture for for Threedsecureio


// Implementation: impl ValidateStatusForOperation for for ExternalVaultProxyPaymentIntent
// File: crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
// Module: router
// Methods: 1 total (0 public)

impl ValidateStatusForOperation for for ExternalVaultProxyPaymentIntent


// Struct: RoleInfo
// File: crates/router/src/services/authorization/roles.rs
// Module: router
// Implementations: 1

pub struct RoleInfo


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

impl api::PaymentToken for for Breadpay


// Struct: ThreedsecureioRouterData
// File: crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ThreedsecureioRouterData<T>


// Struct: VaultFingerprintRequest
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Implementations: 0

pub struct VaultFingerprintRequest


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

pub fn new() -> &'static Self


// Function: convert_from_prost_timestamp
// File: crates/external_services/src/lib.rs
// Module: external_services

// Documentation: Converts a `prost_types::Timestamp` to an `time::PrimitiveDateTime`.

pub fn convert_from_prost_timestamp(
        ts: &prost_types::Timestamp,
    ) -> error_stack::Result<time::PrimitiveDateTime, DateTimeConversionError>


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

impl api::PaymentVoid for for Flexiti


// Implementation: impl UserRoleInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 7 total (0 public)

impl UserRoleInterface for for KafkaStore


// Struct: FiuuPaymentSyncRequest
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct FiuuPaymentSyncRequest


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

impl Iterator for for IntoIter


// Implementation: impl Fiserv
// File: crates/hyperswitch_connectors/src/connectors/fiserv.rs
// Module: hyperswitch_connectors
// Methods: 2 total (2 public)

impl Fiserv


// Function: get_role_from_token_with_groups
// File: crates/router/src/core/user_role/role.rs
// Module: router

pub fn get_role_from_token_with_groups(
    state: SessionState,
    user_from_token: UserFromToken,
) -> UserResponse<Vec<PermissionGroup>>


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

impl FutureUsage


// Struct: Authenticate
// File: crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct Authenticate


// Struct: WelcomeToCommunity
// File: crates/router/src/services/email/types.rs
// Module: router
// Implementations: 1
// Traits: EmailData

pub struct WelcomeToCommunity


// Struct: ProfileCreate
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 0

pub struct ProfileCreate


// File: crates/router/src/core/mandate/utils.rs
// Module: router
// Public functions: 1

use std::marker::PhantomData;

use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use diesel_models::Mandate;
use error_stack::ResultExt;

use crate::{
    core::{errors, payments::helpers},
    types::{self, domain, PaymentAddress},
    SessionState,
};

const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str =
    "irrelevant_attempt_id_in_mandate_revoke_flow";

const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW: &str =
    "irrelevant_connector_request_reference_id_in_mandate_revoke_flow";

pub async fn construct_mandate_revoke_router_data(
    state: &SessionState,
    merchant_connector_account: helpers::MerchantConnectorAccountType,
    merchant_context: &domain::MerchantContext,
    mandate: Mandate,
) -> CustomResult<types::MandateRevokeRouterData, errors::ApiErrorResponse> {
    let auth_type: types::ConnectorAuthType = merchant_connector_account
        .get_connector_account_details()
        .parse_value("ConnectorAuthType")
        .change_context(errors::ApiErrorResponse::InternalServerError)?;
    let router_data = types::RouterData {
        flow: PhantomData,
        merchant_id: merchant_context.get_merchant_account().get_id().clone(),
        customer_id: Some(mandate.customer_id),
        tenant_id: state.tenant.tenant_id.clone(),
        connector_customer: None,
        connector: mandate.connector,
        payment_id: mandate
            .original_payment_id
            .unwrap_or_else(|| {
                common_utils::id_type::PaymentId::get_irrelevant_id("mandate_revoke")
            })
            .get_string_repr()
            .to_owned(),
        attempt_id: IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW.to_string(),
        status: diesel_models::enums::AttemptStatus::default(),
        payment_method: diesel_models::enums::PaymentMethod::default(),
        connector_auth_type: auth_type,
        description: None,
        address: PaymentAddress::default(),
        auth_type: diesel_models::enums::AuthenticationType::default(),
        connector_meta_data: None,
        connector_wallets_details: None,
        amount_captured: None,
        minor_amount_captured: None,
        access_token: None,
        session_token: None,
        reference_id: None,
        payment_method_token: None,
        recurring_mandate_payment_data: None,
        preprocessing_id: None,
        payment_method_balance: None,
        connector_api_version: None,
        payment_method_status: None,
        request: types::MandateRevokeRequestData {
            mandate_id: mandate.mandate_id,
            connector_mandate_id: mandate.connector_mandate_id,
        },
        response: Err(types::ErrorResponse::get_not_implemented()),
        connector_request_reference_id:
            IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW.to_string(),
        test_mode: None,
        connector_http_status_code: None,
        external_latency: None,
        apple_pay_flow: None,
        frm_metadata: None,
        #[cfg(feature = "payouts")]
        payout_method_data: None,
        #[cfg(feature = "payouts")]
        quote_id: 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)
}


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

pub struct TrustlyInfo


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

impl api::PaymentToken for for Hipay


// File: crates/api_models/src/user/sample_data.rs
// Module: api_models
// Public structs: 1

use common_enums::{AuthenticationType, CountryAlpha2};
use time::PrimitiveDateTime;

use crate::enums::Connector;

#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct SampleDataRequest {
    pub record: Option<usize>,
    pub connector: Option<Vec<Connector>>,
    #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
    pub start_time: Option<PrimitiveDateTime>,
    #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
    pub end_time: Option<PrimitiveDateTime>,
    // The amount for each sample will be between min_amount and max_amount (in dollars)
    pub min_amount: Option<i64>,
    pub max_amount: Option<i64>,
    pub currency: Option<Vec<common_enums::Currency>>,
    pub auth_type: Option<Vec<AuthenticationType>>,
    pub business_country: Option<CountryAlpha2>,
    pub business_label: Option<String>,
    pub profile_id: Option<common_utils::id_type::ProfileId>,
}


// Implementation: impl ConnectorCommon for for Hipay
// File: crates/hyperswitch_connectors/src/connectors/hipay.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)

impl ConnectorCommon for for Hipay


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

pub struct StripebillingRecordBackResponse


// Function: validate_amount_to_capture
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models

// Documentation: Validate the amount to capture that is sent in the request

pub fn validate_amount_to_capture(
        &self,
        request_amount_to_capture: MinorUnit,
    ) -> Result<(), ValidationError>


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

pub struct RefundResponse


// Struct: ExtractedPayload
// File: crates/router/src/services/authentication/detached.rs
// Module: router
// Implementations: 1

pub struct ExtractedPayload


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

pub fn find_by_global_customer_id_merchant_id_status(
        conn: &PgPooledConn,
        customer_id: &common_utils::id_type::GlobalCustomerId,
        merchant_id: &common_utils::id_type::MerchantId,
        status: storage_enums::PaymentMethodStatus,
        limit: Option<i64>,
    ) -> StorageResult<Vec<Self>>


// Implementation: impl ConnectorSpecifications for for Sift
// File: crates/hyperswitch_connectors/src/connectors/sift.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)

impl ConnectorSpecifications for for Sift


// File: crates/common_utils/src/signals.rs
// Module: common_utils
// Public functions: 6
// Public structs: 1

//! Provide Interface for worker services to handle signals

#[cfg(not(target_os = "windows"))]
use futures::StreamExt;
#[cfg(not(target_os = "windows"))]
use router_env::logger;
use tokio::sync::mpsc;

/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(not(target_os = "windows"))]
pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) {
    if let Some(signal) = sig.next().await {
        logger::info!(
            "Received signal: {:?}",
            signal_hook::low_level::signal_name(signal)
        );
        match signal {
            signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.try_send(())
            {
                Ok(_) => {
                    logger::info!("Request for force shutdown received")
                }
                Err(_) => {
                    logger::error!(
                        "The receiver is closed, a termination call might already be sent"
                    )
                }
            },
            _ => {}
        }
    }
}

/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(target_os = "windows")]
pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {}

/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(not(target_os = "windows"))]
pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> {
    signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT])
}

/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(target_os = "windows")]
pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> {
    Ok(DummySignal)
}

/// Dummy Signal Handler for windows
#[cfg(target_os = "windows")]
#[derive(Debug, Clone)]
pub struct DummySignal;

#[cfg(target_os = "windows")]
impl DummySignal {
    /// Dummy handler for signals in windows (empty)
    pub fn handle(&self) -> Self {
        self.clone()
    }

    /// Hollow implementation, for windows compatibility
    pub fn close(self) {}
}


// Struct: GetSubscriptionEstimateRequest
// File: crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct GetSubscriptionEstimateRequest


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

impl api::MandateSetup for for Sift


// Struct: HeaderPayload
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 1

pub struct HeaderPayload


// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/tesouro.rs
// Module: hyperswitch_connectors

// Public submodules:
pub mod transformers;


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

pub struct NoonSubscription


// Function: error_message
// File: crates/router_derive/src/macros/api_error.rs
// Module: router_derive

pub fn error_message(&self) -> String


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

impl api::PaymentSync for for Breadpay


// Struct: LinkTokenResponse
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0

pub struct LinkTokenResponse


// Function: sync_refund_with_gateway
// File: crates/router/src/core/refunds_v2.rs
// Module: router

pub fn sync_refund_with_gateway(
    state: &SessionState,
    merchant_context: &domain::MerchantContext,
    payment_attempt: &storage::PaymentAttempt,
    payment_intent: &storage::PaymentIntent,
    refund: &diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund>


// File: crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 8

use std::collections::HashMap;

use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
    errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
    router_data::{ConnectorAuthType, ErrorResponse, RouterData},
    router_request_types::{PaymentsAuthorizeData, ResponseId},
    router_response_types::{PaymentsResponseData, RedirectForm},
    types::PaymentsAuthorizeRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};

use crate::{
    types::ResponseRouterData,
    utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};

#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsRequest {
    amount: FloatMajorUnit,
    transaction_id: String,
    user_id: Secret<id_type::CustomerId>,
    currency: enums::Currency,
    first_name: Option<Secret<String>>,
    last_name: Option<Secret<String>>,
    user_alias: Secret<id_type::CustomerId>,
    requested_url: String,
    cancel_url: String,
    email: Option<Email>,
    mid: Secret<String>,
}

fn get_mid(
    connector_auth_type: &ConnectorAuthType,
    payment_method_type: Option<enums::PaymentMethodType>,
    currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
    match CashtocodeAuth::try_from((connector_auth_type, &currency)) {
        Ok(cashtocode_auth) => match payment_method_type {
            Some(enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth
                .merchant_id_classic
                .ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
            Some(enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth
                .merchant_id_evoucher
                .ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
            _ => Err(errors::ConnectorError::FailedToObtainAuthType),
        },
        Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?,
    }
}

impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
    ) -> Result<Self, Self::Error> {
        let customer_id = item.get_customer_id()?;
        let url = item.request.get_router_return_url()?;
        let mid = get_mid(
            &item.connector_auth_type,
            item.request.payment_method_type,
            item.request.currency,
        )?;
        match item.payment_method {
            enums::PaymentMethod::Reward => Ok(Self {
                amount,
                transaction_id: item.attempt_id.clone(),
                currency: item.request.currency,
                user_id: Secret::new(customer_id.to_owned()),
                first_name: None,
                last_name: None,
                user_alias: Secret::new(customer_id),
                requested_url: url.to_owned(),
                cancel_url: url,
                email: item.request.email.clone(),
                mid,
            }),
            _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
        }
    }
}

#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuthType {
    pub auths: HashMap<enums::Currency, CashtocodeAuth>,
}

#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuth {
    pub password_classic: Option<Secret<String>>,
    pub password_evoucher: Option<Secret<String>>,
    pub username_classic: Option<Secret<String>>,
    pub username_evoucher: Option<Secret<String>>,
    pub merchant_id_classic: Option<Secret<String>>,
    pub merchant_id_evoucher: Option<Secret<String>>,
}

impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
    type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type

    fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
        match auth_type {
            ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
                let transformed_auths = auth_key_map
                    .iter()
                    .map(|(currency, identity_auth_key)| {
                        let cashtocode_auth = identity_auth_key
                            .to_owned()
                            .parse_value::<CashtocodeAuth>("CashtocodeAuth")
                            .change_context(errors::ConnectorError::InvalidDataFormat {
                                field_name: "auth_key_map",
                            })?;

                        Ok((currency.to_owned(), cashtocode_auth))
                    })
                    .collect::<Result<_, Self::Error>>()?;

                Ok(Self {
                    auths: transformed_auths,
                })
            }
            _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
        }
    }
}

impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
    type Error = error_stack::Report<errors::ConnectorError>;

    fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
        let (auth_type, currency) = value;

        if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
            if let Some(identity_auth_key) = auth_key_map.get(currency) {
                let cashtocode_auth: Self = identity_auth_key
                    .to_owned()
                    .parse_value("CashtocodeAuth")
                    .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
                Ok(cashtocode_auth)
            } else {
                Err(errors::ConnectorError::CurrencyNotSupported {
                    message: currency.to_string(),
                    connector: "CashToCode",
                }
                .into())
            }
        } else {
            Err(errors::ConnectorError::FailedToObtainAuthType.into())
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CashtocodePaymentStatus {
    Succeeded,
    #[default]
    Processing,
}

impl From<CashtocodePaymentStatus> for enums::AttemptStatus {
    fn from(item: CashtocodePaymentStatus) -> Self {
        match item {
            CashtocodePaymentStatus::Succeeded => Self::Charged,
            CashtocodePaymentStatus::Processing => Self::AuthenticationPending,
        }
    }
}

#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
    pub message: String,
    pub path: String,
    #[serde(rename = "type")]
    pub event_type: String,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
    CashtoCodeError(CashtocodeErrorResponse),
    CashtoCodeData(CashtocodePaymentsResponseData),
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
    pub pay_url: url::Url,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
    pub transaction_id: String,
    pub amount: FloatMajorUnit,
}

fn get_redirect_form_data(
    payment_method_type: enums::PaymentMethodType,
    response_data: CashtocodePaymentsResponseData,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
    match payment_method_type {
        enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
            //redirect form is manually constructed because the connector for this pm type expects query params in the url
            endpoint: response_data.pay_url.to_string(),
            method: Method::Post,
            form_fields: Default::default(),
        }),
        enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
            //here the pay url gets parsed, and query params are sent as formfields as the connector expects
            response_data.pay_url,
            Method::Get,
        ))),
        _ => Err(errors::ConnectorError::NotImplemented(
            utils::get_unimplemented_payment_method_error_message("CashToCode"),
        ))?,
    }
}

impl<F>
    TryFrom<
        ResponseRouterData<
            F,
            CashtocodePaymentsResponse,
            PaymentsAuthorizeData,
            PaymentsResponseData,
        >,
    > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: ResponseRouterData<
            F,
            CashtocodePaymentsResponse,
            PaymentsAuthorizeData,
            PaymentsResponseData,
        >,
    ) -> Result<Self, Self::Error> {
        let (status, response) = match item.response {
            CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
                enums::AttemptStatus::Failure,
                Err(ErrorResponse {
                    code: error_data.error.to_string(),
                    status_code: item.http_code,
                    message: error_data.error_description.clone(),
                    reason: Some(error_data.error_description),
                    attempt_status: None,
                    connector_transaction_id: None,
                    network_advice_code: None,
                    network_decline_code: None,
                    network_error_message: None,
                    connector_metadata: None,
                }),
            ),
            CashtocodePaymentsResponse::CashtoCodeData(response_data) => {
                let payment_method_type = item
                    .data
                    .request
                    .payment_method_type
                    .ok_or(errors::ConnectorError::MissingPaymentMethodType)?;
                let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
                (
                    enums::AttemptStatus::AuthenticationPending,
                    Ok(PaymentsResponseData::TransactionResponse {
                        resource_id: ResponseId::ConnectorTransactionId(
                            item.data.attempt_id.clone(),
                        ),
                        redirection_data: Box::new(Some(redirection_data)),
                        mandate_reference: Box::new(None),
                        connector_metadata: None,
                        network_txn_id: None,
                        connector_response_reference_id: None,
                        incremental_authorization_allowed: None,
                        charges: None,
                    }),
                )
            }
        };

        Ok(Self {
            status,
            response,
            ..item.data
        })
    }
}

impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
    for RouterData<F, T, PaymentsResponseData>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
            response: Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(
                    item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
                ),
                redirection_data: Box::new(None),
                mandate_reference: Box::new(None),
                connector_metadata: None,
                network_txn_id: None,
                connector_response_reference_id: None,
                incremental_authorization_allowed: None,
                charges: None,
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
    pub error: serde_json::Value,
    pub error_description: String,
    pub errors: Option<Vec<CashtocodeErrors>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodeIncomingWebhook {
    pub amount: FloatMajorUnit,
    pub currency: String,
    pub foreign_transaction_id: String,
    #[serde(rename = "type")]
    pub event_type: String,
    pub transaction_id: String,
}


// Implementation: impl Default for for SuccessBasedRoutingConfig
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (0 public)

impl Default for for SuccessBasedRoutingConfig


// Struct: CashtoCodeCurrencyAuthKeyType
// File: crates/connector_configs/src/connector.rs
// Module: connector_configs
// Implementations: 0

pub struct CashtoCodeCurrencyAuthKeyType


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

pub fn list_by_profile_id_initial_attempt_id(
        conn: &PgPooledConn,
        profile_id: &common_utils::id_type::ProfileId,
        initial_attempt_id: &str,
    ) -> StorageResult<Vec<Self>>


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

pub fn retrieve_dispute(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<String>,
    json_payload: web::Query<dispute_models::DisputeRetrieveBody>,
) -> HttpResponse


// Struct: VirInterpreterBackend
// File: crates/euclid/src/backend/vir_interpreter.rs
// Module: euclid
// Implementations: 1

pub struct VirInterpreterBackend<O>


// Function: fetch_payment_method
// File: crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
// Module: router

pub fn fetch_payment_method(
        &self,
        payment_method_id: &str,
    ) -> RouterResult<domain::PaymentMethod>


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

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


// Implementation: impl DBOperation
// File: crates/diesel_models/src/kv.rs
// Module: diesel_models
// Methods: 1 total (0 public)

impl DBOperation


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

impl api::PaymentCapture for for Itaubank


// Function: check_payments_receivable
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router

pub fn check_payments_receivable(&self) -> Option<api::PayPalOnboardingStatus>


// Function: is_separate_authentication_supported
// File: crates/common_enums/src/connector_enums.rs
// Module: common_enums

pub fn is_separate_authentication_supported(self) -> bool


// Function: percentage
// File: crates/euclid/src/frontend/ast/parser.rs
// Module: euclid

pub fn percentage(input: &str) -> ParseResult<&str, u8>


// Implementation: impl DashboardMetadataInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 6 total (0 public)

impl DashboardMetadataInterface for for KafkaStore


// Function: get_string_repr
// File: crates/common_utils/src/id_type/global_id/payment_methods.rs
// Module: common_utils

// Documentation: Get the string representation of the id

pub fn get_string_repr(&self) -> &str


// Function: set_dynamic_routing_volume_split
// File: crates/router/src/routes/routing.rs
// Module: router

pub fn set_dynamic_routing_volume_split(
    state: web::Data<AppState>,
    req: HttpRequest,
    query: web::Query<api_models::routing::DynamicRoutingVolumeSplitQuery>,
    path: web::Path<routing_types::ToggleDynamicRoutingPath>,
) -> impl Responder


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

impl api::Refund for for Juspaythreedsserver


// 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


// Struct: CardCancelResponse
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CardCancelResponse


// Struct: VaultRequestData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct VaultRequestData


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

impl api::ConnectorAccessToken for for Trustpay


                storage_model.surcharge_amount,
                storage_model.tax_amount,
            ),
            payment_id: storage_model.payment_id,
            merchant_id: storage_model.merchant_id.clone(),
            attempt_id: storage_model.attempt_id,
            status: storage_model.status,
            currency: storage_model.currency,
            save_to_locker: storage_model.save_to_locker,
            connector: storage_model.connector,
            error_message: storage_model.error_message,
            offer_amount: storage_model.offer_amount,
            payment_method_id: storage_model.payment_method_id,
            payment_method: storage_model.payment_method,
            capture_method: storage_model.capture_method,
            capture_on: storage_model.capture_on,
            confirm: storage_model.confirm,
            authentication_type: storage_model.authentication_type,
            created_at: Some(storage_model.created_at),
            modified_at: Some(storage_model.modified_at),
            last_synced: storage_model.last_synced,
            cancellation_reason: storage_model.cancellation_reason,
            amount_to_capture: storage_model.amount_to_capture,
            mandate_id: storage_model.mandate_id,
            browser_info: storage_model.browser_info,
            payment_token: storage_model.payment_token,
            error_code: storage_model.error_code,
            connector_metadata: storage_model.connector_metadata,
            payment_experience: storage_model.payment_experience,
            payment_method_type: storage_model.payment_method_type,
            payment_method_data: storage_model.payment_method_data,
            business_sub_label: storage_model.business_sub_label,
            straight_through_algorithm: storage_model.straight_through_algorithm,
            preprocessing_step_id: storage_model.preprocessing_step_id,
            mandate_details: storage_model
                .mandate_details
                .map(MandateDataType::from_storage_model),
            error_reason: storage_model.error_reason,
            connector_response_reference_id: storage_model.connector_response_reference_id,
            multiple_capture_count: storage_model.multiple_capture_count,
            amount_capturable: storage_model.amount_capturable,
            updated_by: storage_model.updated_by,
            authentication_data: storage_model.authentication_data,
            encoded_data: storage_model.encoded_data,
            merchant_connector_id: storage_model.merchant_connector_id,
            unified_code: storage_model.unified_code,
            unified_message: storage_model.unified_message,
            external_three_ds_authentication_attempted: storage_model
                .external_three_ds_authentication_attempted,
            authentication_connector: storage_model.authentication_connector,
            authentication_id: storage_model.authentication_id,
            mandate_data: storage_model
                .mandate_data
                .map(MandateDetails::from_storage_model),
            payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
            fingerprint_id: storage_model.fingerprint_id,
            client_source: storage_model.client_source,
            client_version: storage_model.client_version,
            customer_acceptance: storage_model.customer_acceptance,
            organization_id: storage_model.organization_id,
            profile_id: storage_model.profile_id,
            connector_mandate_detail: storage_model.connector_mandate_detail,
            request_extended_authorization: storage_model.request_extended_authorization,
            extended_authorization_applied: storage_model.extended_authorization_applied,
            capture_before: storage_model.capture_before,
            card_discovery: storage_model.card_discovery,
            processor_merchant_id: storage_model
                .processor_merchant_id
                .unwrap_or(storage_model.merchant_id),
            created_by: storage_model
                .created_by
                .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
            setup_future_usage_applied: storage_model.setup_future_usage_applied,
            routing_approach: storage_model.routing_approach,
            connector_request_reference_id: storage_model.connector_request_reference_id,
            network_transaction_id: storage_model.network_transaction_id,
            network_details: storage_model.network_details,
            is_stored_credential: storage_model.is_stored_credential,
        }
    }
}

#[inline]
#[instrument(skip_all)]
async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
    store: &KVRouterStore<T>,
    key: &str,
    merchant_id: &common_utils::id_type::MerchantId,
    updated_attempt_attempt_id: &str,
    connector_transaction_id: &str,
    storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
    let field = format!("pa_{updated_attempt_attempt_id}");
    let reverse_lookup_new = ReverseLookupNew {
        lookup_id: format!(
            "pa_conn_trans_{}_{}",
            merchant_id.get_string_repr(),
            connector_transaction_id
        ),
        pk_id: key.to_owned(),
        sk_id: field.clone(),
        source: "payment_attempt".to_string(),
        updated_by: storage_scheme.to_string(),
    };
    store
        .insert_reverse_lookup(reverse_lookup_new, storage_scheme)
        .await
}

#[inline]
#[instrument(skip_all)]
async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>(
    store: &KVRouterStore<T>,
    key: &str,
    merchant_id: &common_utils::id_type::MerchantId,
    updated_attempt_attempt_id: &str,
    preprocessing_id: &str,
    storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
    let field = format!("pa_{updated_attempt_attempt_id}");
    let reverse_lookup_new = ReverseLookupNew {
        lookup_id: format!(
            "pa_preprocessing_{}_{}",
            merchant_id.get_string_repr(),
            preprocessing_id
        ),
        pk_id: key.to_owned(),
        sk_id: field.clone(),
        source: "payment_attempt".to_string(),
        updated_by: storage_scheme.to_string(),
    };
    store
        .insert_reverse_lookup(reverse_lookup_new, storage_scheme)
        .await
}

#[cfg(feature = "v2")]
mod label {
    pub(super) const MODEL_NAME: &str = "payment_attempt_v2";
    pub(super) const CLUSTER_LABEL: &str = "pa";

    pub(super) fn get_profile_id_connector_transaction_label(
        profile_id: &str,
        connector_transaction_id: &str,
    ) -> String {
        format!("profile_{profile_id}_conn_txn_{connector_transaction_id}")
    }

    pub(super) fn get_global_id_label(
        attempt_id: &common_utils::id_type::GlobalAttemptId,
    ) -> String {
        format!("attempt_global_id_{}", attempt_id.get_string_repr())
    }
}


// Struct: ProfileGeneralUpdate
// File: crates/hyperswitch_domain_models/src/business_profile.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct ProfileGeneralUpdate


// Implementation: impl common_utils::events::ApiEventMetric
        for for PaymentsGenericRequestWithResourceId
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 1 total (0 public)

impl common_utils::events::ApiEventMetric
        for for PaymentsGenericRequestWithResourceId


// Struct: Mollie
// File: crates/hyperswitch_connectors/src/connectors/mollie.rs
// Module: hyperswitch_connectors
// Implementations: 20
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentToken, api::PaymentAuthorize, api::PaymentsCompleteAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorSpecifications

pub struct Mollie

api::Payment api::PaymentSession api::ConnectorAccessToken api::MandateSetup api::PaymentToken api::PaymentAuthorize api::PaymentsCompleteAuthorize api::PaymentSync api::PaymentCapture api::PaymentVoid api::Refund api::RefundExecute api::RefundSync ConnectorCommon ConnectorValidation webhooks::IncomingWebhook ConnectorRedirectResponse ConnectorSpecifications ConnectorSpecifications


// Implementation: impl ConnectorCommon for for Forte
// File: crates/hyperswitch_connectors/src/connectors/forte.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)

impl ConnectorCommon for for Forte


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

pub fn list_initial_webhook_delivery_attempts_with_jwtauth(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<EventListConstraints>,
) -> impl Responder


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

pub fn refunds_retrieve_with_body(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<refunds::RefundsRetrieveRequest>,
) -> HttpResponse


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

impl ProphetpayTokenType


// Implementation: impl PartnerReferralRequest
// File: crates/router/src/types/api/connector_onboarding/paypal.rs
// Module: router
// Methods: 1 total (1 public)

impl PartnerReferralRequest


// Struct: NovalnetAuthorizationResponse
// File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct NovalnetAuthorizationResponse


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

impl RefundSync for for Signifyd


// Implementation: impl FromEncoded for for Secret
// File: crates/external_services/src/hashicorp_vault/core.rs
// Module: external_services
// Methods: 1 total (0 public)

impl FromEncoded for for Secret


// Trait: FromEncoded
// File: crates/external_services/src/hashicorp_vault/core.rs
// Module: external_services

// Documentation: A trait for types that can be constructed from encoded data in the form of a String.

pub trait FromEncoded: Sized


// Struct: AdyenStoredCardIdentification
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct AdyenStoredCardIdentification


// Function: get_schedule_time_based_on_retry_type
// File: crates/router/src/types/storage/revenue_recovery.rs
// Module: router

pub fn get_schedule_time_based_on_retry_type(
        &self,
        state: &SessionState,
        merchant_id: &id_type::MerchantId,
        retry_count: i32,
        payment_attempt: &PaymentAttempt,
        payment_intent: &PaymentIntent,
        is_hard_decline: bool,
    ) -> Option<time::PrimitiveDateTime>


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

pub struct ThreeD


// Function: new_normal
// File: crates/masking/src/maskable.rs
// Module: masking

// Documentation: Create a new non-masked data

pub fn new_normal(item: T) -> Self


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

impl api::PaymentVoid for for Helcim


// File: crates/router/src/compatibility/stripe.rs
// Module: router
// Public functions: 1
// Public structs: 1

pub mod app;
pub mod customers;
pub mod payment_intents;
pub mod refunds;
pub mod setup_intents;
pub mod webhooks;
#[cfg(feature = "v1")]
use actix_web::{web, Scope};
pub mod errors;
#[cfg(feature = "v1")]
use crate::routes;

#[cfg(feature = "v1")]
pub struct StripeApis;

#[cfg(feature = "v1")]
impl StripeApis {
    pub fn server(state: routes::AppState) -> Scope {
        let max_depth = 10;
        let strict = false;
        web::scope("/vs/v1")
            .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict)))
            .service(app::SetupIntents::server(state.clone()))
            .service(app::PaymentIntents::server(state.clone()))
            .service(app::Refunds::server(state.clone()))
            .service(app::Customers::server(state.clone()))
            .service(app::Webhooks::server(state.clone()))
            .service(app::Mandates::server(state))
    }
}


// Function: authentication_sync_core
// File: crates/router/src/core/unified_authentication_service.rs
// Module: router

pub fn authentication_sync_core(
    state: SessionState,
    merchant_context: domain::MerchantContext,
    auth_flow: AuthFlow,
    req: AuthenticationSyncRequest,
) -> RouterResponse<AuthenticationSyncResponse>


// Struct: ApplePayPaymentInformation
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct ApplePayPaymentInformation


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

use std::{fmt::Display, str::FromStr};

use common_utils::{
    errors::{CustomResult, ErrorSwitch, ParsingError},
    events::{ApiEventMetric, ApiEventsType},
    impl_api_event_type,
};
use error_stack::{report, Report, ResultExt};

use super::query::QueryBuildingError;
use crate::errors::AnalyticsError;

#[derive(serde::Deserialize, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AnalyticsDomain {
    Payments,
    Refunds,
    Frm,
    PaymentIntents,
    AuthEvents,
    SdkEvents,
    ApiEvents,
    Dispute,
    Routing,
}

#[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)]
pub enum AnalyticsCollection {
    Payment,
    PaymentSessionized,
    Refund,
    RefundSessionized,
    FraudCheck,
    SdkEvents,
    SdkEventsAnalytics,
    ApiEvents,
    PaymentIntent,
    PaymentIntentSessionized,
    ConnectorEvents,
    OutgoingWebhookEvent,
    Authentications,
    Dispute,
    DisputeSessionized,
    ApiEventsAnalytics,
    ActivePaymentsAnalytics,
    RoutingEvents,
}

#[allow(dead_code)]
#[derive(Debug)]
pub enum TableEngine {
    CollapsingMergeTree { sign: &'static str },
    BasicTree,
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, Hash)]
#[serde(transparent)]
pub struct DBEnumWrapper<T: FromStr + Display>(pub T);

impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> {
    fn default() -> Self {
        Self(T::default())
    }
}

impl<T> FromStr for DBEnumWrapper<T>
where
    T: FromStr + Display,
{
    type Err = Report<ParsingError>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        T::from_str(s)
            .map_err(|_er| report!(ParsingError::EnumParseFailure(std::any::type_name::<T>())))
            .map(DBEnumWrapper)
            .attach_printable_lazy(|| format!("raw_value: {s}"))
    }
}

#[async_trait::async_trait]
pub trait AnalyticsDataSource
where
    Self: Sized + Sync + Send,
{
    type Row;
    async fn load_results<T>(&self, query: &str) -> CustomResult<Vec<T>, QueryExecutionError>
    where
        Self: LoadRow<T>;

    fn get_table_engine(_table: AnalyticsCollection) -> TableEngine {
        TableEngine::BasicTree
    }
}

pub trait LoadRow<T>
where
    Self: AnalyticsDataSource,
    T: Sized,
{
    fn load_row(row: Self::Row) -> CustomResult<T, QueryExecutionError>;
}

#[derive(thiserror::Error, Debug)]
pub enum MetricsError {
    #[error("Error building query")]
    QueryBuildingError,
    #[error("Error running Query")]
    QueryExecutionFailure,
    #[error("Error processing query results")]
    PostProcessingFailure,
    #[allow(dead_code)]
    #[error("Not Implemented")]
    NotImplemented,
}

#[derive(Debug, thiserror::Error)]
pub enum QueryExecutionError {
    #[error("Failed to extract domain rows")]
    RowExtractionFailure,
    #[error("Database error")]
    DatabaseError,
}

pub type MetricsResult<T> = CustomResult<T, MetricsError>;

impl ErrorSwitch<MetricsError> for QueryBuildingError {
    fn switch(&self) -> MetricsError {
        MetricsError::QueryBuildingError
    }
}

pub type FiltersResult<T> = CustomResult<T, FiltersError>;

#[derive(thiserror::Error, Debug)]
pub enum FiltersError {
    #[error("Error building query")]
    QueryBuildingError,
    #[error("Error running Query")]
    QueryExecutionFailure,
    #[allow(dead_code)]
    #[error("Not Implemented: {0}")]
    NotImplemented(&'static str),
}

impl ErrorSwitch<FiltersError> for QueryBuildingError {
    fn switch(&self) -> FiltersError {
        FiltersError::QueryBuildingError
    }
}

impl ErrorSwitch<AnalyticsError> for FiltersError {
    fn switch(&self) -> AnalyticsError {
        match self {
            Self::QueryBuildingError | Self::QueryExecutionFailure => AnalyticsError::UnknownError,
            Self::NotImplemented(a) => AnalyticsError::NotImplemented(a),
        }
    }
}

impl_api_event_type!(Miscellaneous, (AnalyticsDomain));


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

impl api::PaymentsPostAuthenticate for for Cybersource


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

pub fn fetch_disputes(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<String>,
    json_payload: web::Query<dispute_types::DisputeFetchQueryData>,
) -> HttpResponse


// Implementation: impl CardsInfoInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 3 total (0 public)

impl CardsInfoInterface for for KafkaStore


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

pub fn create_user_theme(
    state: SessionState,
    user_from_token: UserFromToken,
    request: theme_api::CreateUserThemeRequest,
) -> UserResponse<theme_api::GetThemeResponse>


// Struct: QrRequestData
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct QrRequestData


// Function: perform_surcharge_decision_management_for_payment_method_list
// File: crates/router/src/core/payment_methods/surcharge_decision_configs.rs
// Module: router

pub fn perform_surcharge_decision_management_for_payment_method_list(
    state: &SessionState,
    algorithm_ref: routing::RoutingAlgorithmRef,
    payment_attempt: &storage::PaymentAttempt,
    payment_intent: &storage::PaymentIntent,
    billing_address: Option<hyperswitch_domain_models::address::Address>,
    response_payment_method_types: &mut [api_models::payment_methods::ResponsePaymentMethodsEnabled],
) -> ConditionalConfigResult<(
    types::SurchargeMetadata,
    surcharge_decision_configs::MerchantSurchargeConfigs,
)>


// Implementation: impl behaviour::Conversion for for PaymentIntent
// File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs
// Module: hyperswitch_domain_models
// Methods: 3 total (0 public)

impl behaviour::Conversion for for PaymentIntent


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

pub fn update(&mut self, new: Self)


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

pub struct BluesnapRefundRequest