// File: crates/api_models/src/analytics.rs
// Module: api_models
// Public functions: 1
// Public structs: 54

use std::collections::HashSet;

pub use common_utils::types::TimeRange;
use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo};
use masking::Secret;

use self::{
    active_payments::ActivePaymentsMetrics,
    api_event::{ApiEventDimensions, ApiEventMetrics},
    auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics},
    disputes::{DisputeDimensions, DisputeMetrics},
    frm::{FrmDimensions, FrmMetrics},
    payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics},
    payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
    refunds::{RefundDimensions, RefundDistributions, RefundMetrics},
    sdk_events::{SdkEventDimensions, SdkEventMetrics},
};
pub mod active_payments;
pub mod api_event;
pub mod auth_events;
pub mod connector_events;
pub mod disputes;
pub mod frm;
pub mod outgoing_webhook_event;
pub mod payment_intents;
pub mod payments;
pub mod refunds;
pub mod routing_events;
pub mod sdk_events;
pub mod search;

#[derive(Debug, serde::Serialize)]
pub struct NameDescription {
    pub name: String,
    pub desc: String,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetInfoResponse {
    pub metrics: Vec<NameDescription>,
    pub download_dimensions: Option<Vec<NameDescription>>,
    pub dimensions: Vec<NameDescription>,
}

#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub struct TimeSeries {
    pub granularity: Granularity,
}

#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub enum Granularity {
    #[serde(rename = "G_ONEMIN")]
    OneMin,
    #[serde(rename = "G_FIVEMIN")]
    FiveMin,
    #[serde(rename = "G_FIFTEENMIN")]
    FifteenMin,
    #[serde(rename = "G_THIRTYMIN")]
    ThirtyMin,
    #[serde(rename = "G_ONEHOUR")]
    OneHour,
    #[serde(rename = "G_ONEDAY")]
    OneDay,
}
pub trait ForexMetric {
    fn is_forex_metric(&self) -> bool;
}

#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AnalyticsRequest {
    pub payment_intent: Option<GetPaymentIntentMetricRequest>,
    pub payment_attempt: Option<GetPaymentMetricRequest>,
    pub refund: Option<GetRefundMetricRequest>,
    pub dispute: Option<GetDisputeMetricRequest>,
}

impl AnalyticsRequest {
    pub fn requires_forex_functionality(&self) -> bool {
        self.payment_attempt
            .as_ref()
            .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
            .unwrap_or_default()
            || self
                .payment_intent
                .as_ref()
                .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
                .unwrap_or_default()
            || self
                .refund
                .as_ref()
                .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
                .unwrap_or_default()
            || self
                .dispute
                .as_ref()
                .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric()))
                .unwrap_or_default()
    }
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<PaymentDimensions>,
    #[serde(default)]
    pub filters: payments::PaymentFilters,
    pub metrics: HashSet<PaymentMetrics>,
    pub distribution: Option<PaymentDistributionBody>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)]
pub enum QueryLimit {
    #[serde(rename = "TOP_5")]
    Top5,
    #[serde(rename = "TOP_10")]
    Top10,
}

#[allow(clippy::from_over_into)]
impl Into<u64> for QueryLimit {
    fn into(self) -> u64 {
        match self {
            Self::Top5 => 5,
            Self::Top10 => 10,
        }
    }
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentDistributionBody {
    pub distribution_for: PaymentDistributions,
    pub distribution_cardinality: QueryLimit,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundDistributionBody {
    pub distribution_for: RefundDistributions,
    pub distribution_cardinality: QueryLimit,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
    pub time_range: TimeRange,
    pub emails: Option<Vec<Secret<String, EmailStrategy>>>,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateReportRequest {
    pub request: ReportRequest,
    pub merchant_id: Option<common_utils::id_type::MerchantId>,
    pub auth: AuthInfo,
    pub email: Secret<String, EmailStrategy>,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentIntentMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<PaymentIntentDimensions>,
    #[serde(default)]
    pub filters: payment_intents::PaymentIntentFilters,
    pub metrics: HashSet<PaymentIntentMetrics>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRefundMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<RefundDimensions>,
    #[serde(default)]
    pub filters: refunds::RefundFilters,
    pub metrics: HashSet<RefundMetrics>,
    pub distribution: Option<RefundDistributionBody>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFrmMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<FrmDimensions>,
    #[serde(default)]
    pub filters: frm::FrmFilters,
    pub metrics: HashSet<FrmMetrics>,
    #[serde(default)]
    pub delta: bool,
}

impl ApiEventMetric for GetFrmMetricRequest {}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<SdkEventDimensions>,
    #[serde(default)]
    pub filters: sdk_events::SdkEventFilters,
    pub metrics: HashSet<SdkEventMetrics>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthEventMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<AuthEventDimensions>,
    #[serde(default)]
    pub filters: AuthEventFilters,
    #[serde(default)]
    pub metrics: HashSet<AuthEventMetrics>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetActivePaymentsMetricRequest {
    #[serde(default)]
    pub metrics: HashSet<ActivePaymentsMetrics>,
    pub time_range: TimeRange,
}

#[derive(Debug, serde::Serialize)]
pub struct AnalyticsMetadata {
    pub current_time_range: TimeRange,
}

#[derive(Debug, serde::Serialize)]
pub struct PaymentsAnalyticsMetadata {
    pub total_payment_processed_amount: Option<u64>,
    pub total_payment_processed_amount_in_usd: Option<u64>,
    pub total_payment_processed_amount_without_smart_retries: Option<u64>,
    pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>,
    pub total_payment_processed_count: Option<u64>,
    pub total_payment_processed_count_without_smart_retries: Option<u64>,
    pub total_failure_reasons_count: Option<u64>,
    pub total_failure_reasons_count_without_smart_retries: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct PaymentIntentsAnalyticsMetadata {
    pub total_success_rate: Option<f64>,
    pub total_success_rate_without_smart_retries: Option<f64>,
    pub total_smart_retried_amount: Option<u64>,
    pub total_smart_retried_amount_without_smart_retries: Option<u64>,
    pub total_payment_processed_amount: Option<u64>,
    pub total_payment_processed_amount_without_smart_retries: Option<u64>,
    pub total_smart_retried_amount_in_usd: Option<u64>,
    pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
    pub total_payment_processed_amount_in_usd: Option<u64>,
    pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>,
    pub total_payment_processed_count: Option<u64>,
    pub total_payment_processed_count_without_smart_retries: Option<u64>,
}

#[derive(Debug, serde::Serialize)]
pub struct RefundsAnalyticsMetadata {
    pub total_refund_success_rate: Option<f64>,
    pub total_refund_processed_amount: Option<u64>,
    pub total_refund_processed_amount_in_usd: Option<u64>,
    pub total_refund_processed_count: Option<u64>,
    pub total_refund_reason_count: Option<u64>,
    pub total_refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentFiltersRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<PaymentDimensions>,
}

#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentFiltersResponse {
    pub query_data: Vec<FilterValue>,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FilterValue {
    pub dimension: PaymentDimensions,
    pub values: Vec<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentIntentFiltersRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<PaymentIntentDimensions>,
}

#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentFiltersResponse {
    pub query_data: Vec<PaymentIntentFilterValue>,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentFilterValue {
    pub dimension: PaymentIntentDimensions,
    pub values: Vec<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRefundFilterRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<RefundDimensions>,
}

#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundFiltersResponse {
    pub query_data: Vec<RefundFilterValue>,
}

#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RefundFilterValue {
    pub dimension: RefundDimensions,
    pub values: Vec<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFrmFilterRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<FrmDimensions>,
}

impl ApiEventMetric for GetFrmFilterRequest {}

#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FrmFiltersResponse {
    pub query_data: Vec<FrmFilterValue>,
}

impl ApiEventMetric for FrmFiltersResponse {}

#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FrmFilterValue {
    pub dimension: FrmDimensions,
    pub values: Vec<String>,
}

impl ApiEventMetric for FrmFilterValue {}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventFiltersRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<SdkEventDimensions>,
}

#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventFiltersResponse {
    pub query_data: Vec<SdkEventFilterValue>,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SdkEventFilterValue {
    pub dimension: SdkEventDimensions,
    pub values: Vec<String>,
}

#[derive(Debug, serde::Serialize)]
pub struct DisputesAnalyticsMetadata {
    pub total_disputed_amount: Option<u64>,
    pub total_dispute_lost_amount: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [AnalyticsMetadata; 1],
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentsMetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [PaymentsAnalyticsMetadata; 1],
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentIntentsMetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [PaymentIntentsAnalyticsMetadata; 1],
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundsMetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [RefundsAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DisputesMetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [DisputesAnalyticsMetadata; 1],
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<ApiEventDimensions>,
}

#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiEventFiltersResponse {
    pub query_data: Vec<ApiEventFilterValue>,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiEventFilterValue {
    pub dimension: ApiEventDimensions,
    pub values: Vec<String>,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<ApiEventDimensions>,
    #[serde(default)]
    pub filters: api_event::ApiEventFilters,
    pub metrics: HashSet<ApiEventMetrics>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDisputeFilterRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<DisputeDimensions>,
}

#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DisputeFiltersResponse {
    pub query_data: Vec<DisputeFilterValue>,
}

#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DisputeFilterValue {
    pub dimension: DisputeDimensions,
    pub values: Vec<String>,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDisputeMetricRequest {
    pub time_series: Option<TimeSeries>,
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<DisputeDimensions>,
    #[serde(default)]
    pub filters: disputes::DisputeFilters,
    pub metrics: HashSet<DisputeMetrics>,
    #[serde(default)]
    pub delta: bool,
}

#[derive(Clone, Debug, Default, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SankeyResponse {
    pub count: i64,
    pub status: String,
    pub refunds_status: Option<String>,
    pub dispute_status: Option<String>,
    pub first_attempt: i64,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAuthEventFilterRequest {
    pub time_range: TimeRange,
    #[serde(default)]
    pub group_by_names: Vec<AuthEventDimensions>,
}

#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventFiltersResponse {
    pub query_data: Vec<AuthEventFilterValue>,
}

#[derive(Debug, serde::Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventFilterValue {
    pub dimension: AuthEventDimensions,
    pub values: Vec<String>,
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthEventMetricsResponse<T> {
    pub query_data: Vec<T>,
    pub meta_data: [AuthEventsAnalyticsMetadata; 1],
}

#[derive(Debug, serde::Serialize)]
pub struct AuthEventsAnalyticsMetadata {
    pub total_error_message_count: Option<u64>,
}


// File: crates/router/src/core/external_service_auth.rs
// Module: router
// Public functions: 3

use api_models::external_service_auth as external_service_auth_api;
use common_utils::fp_utils;
use error_stack::ResultExt;
use masking::ExposeInterface;

use crate::{
    core::errors::{self, RouterResponse},
    services::{
        api as service_api,
        authentication::{self, ExternalServiceType, ExternalToken},
    },
    SessionState,
};

pub async fn generate_external_token(
    state: SessionState,
    user: authentication::UserFromToken,
    external_service_type: ExternalServiceType,
) -> RouterResponse<external_service_auth_api::ExternalTokenResponse> {
    let token = ExternalToken::new_token(
        user.user_id.clone(),
        user.merchant_id.clone(),
        &state.conf,
        external_service_type.clone(),
    )
    .await
    .change_context(errors::ApiErrorResponse::InternalServerError)
    .attach_printable_lazy(|| {
        format!(
            "Failed to create external token for params [user_id, mid, external_service_type] [{}, {:?}, {:?}]",
            user.user_id, user.merchant_id, external_service_type,
        )
    })?;

    Ok(service_api::ApplicationResponse::Json(
        external_service_auth_api::ExternalTokenResponse {
            token: token.into(),
        },
    ))
}

pub async fn signout_external_token(
    state: SessionState,
    json_payload: external_service_auth_api::ExternalSignoutTokenRequest,
) -> RouterResponse<()> {
    let token = authentication::decode_jwt::<ExternalToken>(&json_payload.token.expose(), &state)
        .await
        .change_context(errors::ApiErrorResponse::Unauthorized)?;

    authentication::blacklist::insert_user_in_blacklist(&state, &token.user_id)
        .await
        .change_context(errors::ApiErrorResponse::InvalidJwtToken)?;

    Ok(service_api::ApplicationResponse::StatusOk)
}

pub async fn verify_external_token(
    state: SessionState,
    json_payload: external_service_auth_api::ExternalVerifyTokenRequest,
    external_service_type: ExternalServiceType,
) -> RouterResponse<external_service_auth_api::ExternalVerifyTokenResponse> {
    let token_from_payload = json_payload.token.expose();

    let token = authentication::decode_jwt::<ExternalToken>(&token_from_payload, &state)
        .await
        .change_context(errors::ApiErrorResponse::Unauthorized)?;

    fp_utils::when(
        authentication::blacklist::check_user_in_blacklist(&state, &token.user_id, token.exp)
            .await?,
        || Err(errors::ApiErrorResponse::InvalidJwtToken),
    )?;

    token.check_service_type(&external_service_type)?;

    let user_in_db = state
        .global_store
        .find_user_by_id(&token.user_id)
        .await
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("User not found in database")?;

    let email = user_in_db.email.clone();
    let name = user_in_db.name;

    Ok(service_api::ApplicationResponse::Json(
        external_service_auth_api::ExternalVerifyTokenResponse::Hypersense {
            user_id: user_in_db.user_id,
            merchant_id: token.merchant_id,
            name,
            email,
        },
    ))
}


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

pub struct Authipay

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


// Implementation: impl Responder
// File: crates/router/src/routes/payment_link.rs
// Module: router
// Methods: 0 total (0 public)

impl Responder


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

pub struct PaypalWebooksEventType


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

pub fn revoke_api_key(
    state: &SessionState,
    api_key: Secret<String>,
) -> CustomResult<(), ApiClientError>


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

pub struct Worldline

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


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

pub fn update_connector_customer_in_customers(
    connector_label: &str,
    customer: Option<&domain::Customer>,
    connector_customer_id: Option<String>,
) -> Option<storage::CustomerUpdate>


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

pub fn new() -> &'static Self


// Function: tenant_unaware_key
// File: crates/redis_interface/src/types.rs
// Module: redis_interface

pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String


// Function: decrypt_oidc_private_config
// File: crates/router/src/utils/user.rs
// Module: router

pub fn decrypt_oidc_private_config(
    state: &SessionState,
    encrypted_config: Option<Encryption>,
    id: String,
) -> UserResult<user_api::OpenIdConnectPrivateConfig>


// Struct: Vault
// File: crates/router/src/core/payment_methods/vault.rs
// Module: router
// Implementations: 1

pub struct Vault


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

pub struct NoonErrorResponse


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

// Public submodules:
pub mod transformers;


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

impl api::PaymentVoid for for Globepay


// Struct: VgsErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct VgsErrorResponse


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

impl PayoutsInterface for for KafkaStore


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

pub fn verify_email_token_only_flow(
    state: SessionState,
    user_token: auth::UserFromSinglePurposeToken,
    req: user_api::VerifyEmailRequest,
) -> UserResponse<user_api::TokenResponse>


// Struct: CalGlobalSuccessRateEventRequest
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 0

pub struct CalGlobalSuccessRateEventRequest


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

pub struct NoonRefundResponseResult


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

pub fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
    T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
    Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
    R: Send + 'static,


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

pub fn apply_routing_decision<F, D>(&self, payment_data: &mut D)


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

impl api::PaymentSync for for Chargebee


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

impl std::fmt::Display for for RoutingApproach


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

impl ConnectorSpecifications for for Iatapay


// File: crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 24

use std::collections::HashMap;

use api_models::payments::PollConfig;
use common_enums::enums;
use common_utils::{
    errors::CustomResult,
    pii::{self, Email, IpAddress},
    types::MinorUnit,
};
use hyperswitch_domain_models::{
    payment_method_data::{PaymentMethodData, UpiData},
    router_data::{ConnectorAuthType, RouterData},
    router_flow_types::refunds::{Execute, RSync},
    router_request_types::{PaymentsAuthorizeData, ResponseId},
    router_response_types::{PaymentsResponseData, RefundsResponseData},
    types,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};

use crate::{
    types::{CreateOrderResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
    utils::{
        get_unimplemented_payment_method_error_message, missing_field_err,
        PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
    },
};

pub struct RazorpayRouterData<T> {
    pub amount: MinorUnit,
    pub router_data: T,
}

impl<T> TryFrom<(MinorUnit, T)> for RazorpayRouterData<T> {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
        Ok(Self {
            amount,
            router_data: item,
        })
    }
}

pub const VERSION: i32 = 1;

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderRequest {
    pub amount: MinorUnit,
    pub currency: enums::Currency,
    pub receipt: String,
    pub partial_payment: Option<bool>,
    pub first_payment_min_amount: Option<MinorUnit>,
    pub notes: Option<RazorpayNotes>,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RazorpayNotes {
    Map(HashMap<String, String>),
    EmptyMap(HashMap<String, String>),
}

impl TryFrom<&RazorpayRouterData<&types::CreateOrderRouterData>> for RazorpayOrderRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: &RazorpayRouterData<&types::CreateOrderRouterData>,
    ) -> Result<Self, Self::Error> {
        let currency = item.router_data.request.currency;
        let receipt = item.router_data.connector_request_reference_id.clone();

        Ok(Self {
            amount: item.amount,
            currency,
            receipt,
            partial_payment: None,
            first_payment_min_amount: None,
            notes: None,
        })
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RazorpayMetaData {
    pub order_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderResponse {
    pub id: String,
}

impl TryFrom<CreateOrderResponseRouterData<RazorpayOrderResponse>>
    for types::CreateOrderRouterData
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: CreateOrderResponseRouterData<RazorpayOrderResponse>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(PaymentsResponseData::PaymentsCreateOrderResponse {
                order_id: item.response.id.clone(),
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiDetails {
    flow: UpiFlow,
    vpa: Secret<String, pii::UpiVpaMaskingStrategy>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiFlow {
    Collect,
    Intent,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPaymentsRequest {
    amount: MinorUnit,
    currency: enums::Currency,
    order_id: String,
    email: Email,
    contact: Secret<String>,
    method: RazorpayPaymentMethod,
    upi: UpiDetails,
    #[serde(skip_serializing_if = "Option::is_none")]
    ip: Option<Secret<String, IpAddress>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_agent: Option<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayPaymentMethod {
    Upi,
}

impl TryFrom<&RazorpayRouterData<&types::PaymentsAuthorizeRouterData>> for RazorpayPaymentsRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: &RazorpayRouterData<&types::PaymentsAuthorizeRouterData>,
    ) -> Result<Self, Self::Error> {
        let payment_router_data = item.router_data;
        let router_request = &payment_router_data.request;
        let payment_method_data = &router_request.payment_method_data;

        let (razorpay_payment_method, upi_details) = match payment_method_data {
            PaymentMethodData::Upi(upi_type_data) => match upi_type_data {
                UpiData::UpiCollect(upi_collect_data) => {
                    let vpa_secret = upi_collect_data
                        .vpa_id
                        .clone()
                        .ok_or_else(missing_field_err("payment_method_data.upi.collect.vpa_id"))?;
                    (
                        RazorpayPaymentMethod::Upi,
                        UpiDetails {
                            flow: UpiFlow::Collect,
                            vpa: vpa_secret,
                        },
                    )
                }
                UpiData::UpiIntent(_upi_intent_data) => {
                    Err(errors::ConnectorError::NotImplemented(
                        get_unimplemented_payment_method_error_message("razorpay"),
                    ))?
                }
            },
            _ => Err(errors::ConnectorError::NotImplemented(
                get_unimplemented_payment_method_error_message("razorpay"),
            ))?,
        };

        let contact_number = item.router_data.get_billing_phone_number()?;
        let order_id = router_request.get_order_id()?;
        let email = item.router_data.get_billing_email()?;
        let ip = router_request.get_ip_address_as_optional();
        let user_agent = router_request.get_optional_user_agent();

        Ok(Self {
            amount: item.amount,
            currency: router_request.currency,
            order_id,
            email,
            contact: contact_number,
            method: razorpay_payment_method,
            upi: upi_details,
            ip,
            user_agent,
        })
    }
}

pub struct RazorpayAuthType {
    pub(super) razorpay_id: Secret<String>,
    pub(super) razorpay_secret: Secret<String>,
}

impl TryFrom<&ConnectorAuthType> for RazorpayAuthType {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
        match auth_type {
            ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
                razorpay_id: api_key.to_owned(),
                razorpay_secret: key1.to_owned(),
            }),
            _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NextAction {
    pub action: String,
    pub url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RazorpayPaymentsResponse {
    pub razorpay_payment_id: String,
}

impl<F>
    TryFrom<
        ResponseRouterData<
            F,
            RazorpayPaymentsResponse,
            PaymentsAuthorizeData,
            PaymentsResponseData,
        >,
    > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: ResponseRouterData<
            F,
            RazorpayPaymentsResponse,
            PaymentsAuthorizeData,
            PaymentsResponseData,
        >,
    ) -> Result<Self, Self::Error> {
        let connector_metadata = get_wait_screen_metadata()?;
        let order_id = item.data.request.get_order_id()?;
        Ok(Self {
            status: enums::AttemptStatus::AuthenticationPending,
            response: Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(
                    item.response.razorpay_payment_id.clone(),
                ),
                redirection_data: Box::new(None),
                mandate_reference: Box::new(None),
                connector_metadata,
                network_txn_id: None,
                connector_response_reference_id: Some(order_id),
                incremental_authorization_allowed: None,
                charges: None,
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WaitScreenData {
    display_from_timestamp: i128,
    display_to_timestamp: Option<i128>,
    poll_config: Option<PollConfig>,
}

pub fn get_wait_screen_metadata() -> CustomResult<Option<serde_json::Value>, errors::ConnectorError>
{
    let current_time = OffsetDateTime::now_utc().unix_timestamp_nanos();
    Ok(Some(serde_json::json!(WaitScreenData {
        display_from_timestamp: current_time,
        display_to_timestamp: Some(current_time + Duration::minutes(5).whole_nanoseconds()),
        poll_config: Some(PollConfig {
            delay_in_secs: 5,
            frequency: 5,
        }),
    })))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncResponse {
    items: Vec<RazorpaySyncItem>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpaySyncItem {
    id: String,
    status: RazorpayStatus,
}

#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayStatus {
    Created,
    Authorized,
    Captured,
    Refunded,
    Failed,
}

fn get_psync_razorpay_payment_status(razorpay_status: RazorpayStatus) -> enums::AttemptStatus {
    match razorpay_status {
        RazorpayStatus::Created => enums::AttemptStatus::Pending,
        RazorpayStatus::Authorized => enums::AttemptStatus::Authorized,
        RazorpayStatus::Captured | RazorpayStatus::Refunded => enums::AttemptStatus::Charged,
        RazorpayStatus::Failed => enums::AttemptStatus::Failure,
    }
}

impl<F, T> TryFrom<ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>>
    for RouterData<F, T, PaymentsResponseData>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, RazorpaySyncResponse, T, PaymentsResponseData>,
    ) -> Result<Self, Self::Error> {
        let status = match item.response.items.last() {
            Some(last_item) => {
                let razorpay_status = last_item.status;
                get_psync_razorpay_payment_status(razorpay_status)
            }
            None => item.data.status,
        };
        Ok(Self {
            status,
            response: Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::NoResponseId,
                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(Default, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundRequest {
    pub amount: MinorUnit,
}

impl<F> TryFrom<&RazorpayRouterData<&types::RefundsRouterData<F>>> for RazorpayRefundRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: &RazorpayRouterData<&types::RefundsRouterData<F>>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            amount: item.amount,
        })
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundResponse {
    pub id: String,
    pub status: RazorpayRefundStatus,
}

#[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayRefundStatus {
    Created,
    Processed,
    Failed,
    Pending,
}

impl From<RazorpayRefundStatus> for enums::RefundStatus {
    fn from(item: RazorpayRefundStatus) -> Self {
        match item {
            RazorpayRefundStatus::Processed => Self::Success,
            RazorpayRefundStatus::Pending | RazorpayRefundStatus::Created => Self::Pending,
            RazorpayRefundStatus::Failed => Self::Failure,
        }
    }
}

impl TryFrom<RefundsResponseRouterData<Execute, RazorpayRefundResponse>>
    for types::RefundsRouterData<Execute>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: RefundsResponseRouterData<Execute, RazorpayRefundResponse>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(RefundsResponseData {
                connector_refund_id: item.response.id.to_string(),
                refund_status: enums::RefundStatus::from(item.response.status),
            }),
            ..item.data
        })
    }
}

// This code can be used later when Razorpay webhooks are implemented

// #[derive(Debug, Deserialize, Serialize)]
// #[serde(untagged)]
// pub enum RazorpayPaymentsResponseData {
//     PsyncResponse(RazorpaySyncResponse),
//     WebhookResponse(WebhookPaymentEntity),
// }

// impl From<RazorpayWebhookPaymentStatus> for enums::AttemptStatus {
//     fn from(status: RazorpayWebhookPaymentStatus) -> Self {
//         match status {
//             RazorpayWebhookPaymentStatus::Authorized => Self::Authorized,
//             RazorpayWebhookPaymentStatus::Captured => Self::Charged,
//             RazorpayWebhookPaymentStatus::Failed => Self::Failure,
//         }
//     }
// }

// impl<F, T> TryFrom<ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>>
//     for RouterData<F, T, PaymentsResponseData>
// {
//     type Error = error_stack::Report<errors::ConnectorError>;
//     fn try_from(
//         item: ResponseRouterData<F, RazorpayPaymentsResponseData, T, PaymentsResponseData>,
//     ) -> Result<Self, Self::Error> {
//         match item.response {
//             RazorpayPaymentsResponseData::PsyncResponse(sync_response) => {
//                 let status = get_psync_razorpay_payment_status(sync_response.status.clone());
//                 Ok(Self {
//                     status,
//                     response: if is_payment_failure(status) {
//                         Err(RouterErrorResponse {
//                             code: sync_response.status.clone().to_string(),
//                             message: sync_response.status.clone().to_string(),
//                             reason: Some(sync_response.status.to_string()),
//                             status_code: item.http_code,
//                             attempt_status: Some(status),
//                             connector_transaction_id: None,
//                             network_advice_code: None,
//                             network_decline_code: None,
//                             network_error_message: None,
//                         })
//                     } else {
//                         Ok(PaymentsResponseData::TransactionResponse {
//                             resource_id: ResponseId::NoResponseId,
//                             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
//                 })
//             }
//             RazorpayPaymentsResponseData::WebhookResponse(webhook_payment_entity) => {
//                 let razorpay_status = webhook_payment_entity.status;
//                 let status = enums::AttemptStatus::from(razorpay_status.clone());

//                 Ok(Self {
//                     status,
//                     response: if is_payment_failure(status) {
//                         Err(RouterErrorResponse {
//                             code: razorpay_status.clone().to_string(),
//                             message: razorpay_status.clone().to_string(),
//                             reason: Some(razorpay_status.to_string()),
//                             status_code: item.http_code,
//                             attempt_status: Some(status),
//                             connector_transaction_id: Some(webhook_payment_entity.id.clone()),
//                             network_advice_code: None,
//                             network_decline_code: None,
//                             network_error_message: None,
//                         })
//                     } else {
//                         Ok(PaymentsResponseData::TransactionResponse {
//                             resource_id: ResponseId::ConnectorTransactionId(
//                                 webhook_payment_entity.id.clone(),
//                             ),
//                             redirection_data: Box::new(None),
//                             mandate_reference: Box::new(None),
//                             connector_metadata: None,
//                             network_txn_id: None,
//                             connector_response_reference_id: Some(webhook_payment_entity.id),
//                             incremental_authorization_allowed: None,
//                             charges: None,
//                         })
//                     },
//                     ..item.data
//                 })
//             }
//         }
//     }
// }

impl TryFrom<RefundsResponseRouterData<RSync, RazorpayRefundResponse>>
    for types::RefundsRouterData<RSync>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: RefundsResponseRouterData<RSync, RazorpayRefundResponse>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            response: Ok(RefundsResponseData {
                connector_refund_id: item.response.id.to_string(),
                refund_status: enums::RefundStatus::from(item.response.status),
            }),
            ..item.data
        })
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ErrorResponse {
    RazorpayErrorResponse(RazorpayErrorResponse),
    RazorpayStringError(String),
    RazorpayError(RazorpayErrorMessage),
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorMessage {
    pub message: String,
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayErrorResponse {
    pub error: RazorpayError,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayError {
    pub code: String,
    pub description: String,
    pub source: Option<String>,
    pub step: Option<String>,
    pub reason: Option<String>,
    pub metadata: Option<Metadata>,
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Metadata {
    pub order_id: Option<String>,
}

// This code can be used later when Razorpay webhooks are implemented

// #[derive(Debug, Serialize, Deserialize)]

// pub struct RazorpayWebhookPayload {
//     pub event: RazorpayWebhookEventType,
//     pub payload: RazorpayWebhookPayloadBody,
// }

// #[derive(Debug, Serialize, Deserialize)]
// #[serde(untagged)]
// pub enum RazorpayWebhookEventType {
//     Payments(RazorpayWebhookPaymentEvent),
//     Refunds(RazorpayWebhookRefundEvent),
// }

// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayWebhookPayloadBody {
//     pub refund: Option<RazorpayRefundWebhookPayload>,
//     pub payment: RazorpayPaymentWebhookPayload,
// }

// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayPaymentWebhookPayload {
//     pub entity: WebhookPaymentEntity,
// }

// #[derive(Debug, Serialize, Deserialize)]
// pub struct RazorpayRefundWebhookPayload {
//     pub entity: WebhookRefundEntity,
// }

// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookRefundEntity {
//     pub id: String,
//     pub status: RazorpayWebhookRefundEvent,
// }

// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookRefundEvent {
//     #[serde(rename = "refund.created")]
//     Created,
//     #[serde(rename = "refund.processed")]
//     Processed,
//     #[serde(rename = "refund.failed")]
//     Failed,
//     #[serde(rename = "refund.speed_change")]
//     SpeedChange,
// }

// #[derive(Debug, Serialize, Deserialize)]
// pub struct WebhookPaymentEntity {
//     pub id: String,
//     pub status: RazorpayWebhookPaymentStatus,
// }

// #[derive(Debug, Serialize, Eq, PartialEq, Clone, Deserialize)]
// #[serde(rename_all = "snake_case")]
// pub enum RazorpayWebhookPaymentStatus {
//     Authorized,
//     Captured,
//     Failed,
// }

// #[derive(Debug, Serialize, Eq, PartialEq, Deserialize)]
// pub enum RazorpayWebhookPaymentEvent {
//     #[serde(rename = "payment.authorized")]
//     Authorized,
//     #[serde(rename = "payment.captured")]
//     Captured,
//     #[serde(rename = "payment.failed")]
//     Failed,
// }

// impl TryFrom<RazorpayWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
//     type Error = errors::ConnectorError;

//     fn try_from(event_type: RazorpayWebhookEventType) -> Result<Self, Self::Error> {
//         match event_type {
//             RazorpayWebhookEventType::Payments(payment_event) => match payment_event {
//                 RazorpayWebhookPaymentEvent::Authorized => {
//                     Ok(Self::PaymentIntentAuthorizationSuccess)
//                 }
//                 RazorpayWebhookPaymentEvent::Captured => Ok(Self::PaymentIntentSuccess),
//                 RazorpayWebhookPaymentEvent::Failed => Ok(Self::PaymentIntentFailure),
//             },
//             RazorpayWebhookEventType::Refunds(refund_event) => match refund_event {
//                 RazorpayWebhookRefundEvent::Processed => Ok(Self::RefundSuccess),
//                 RazorpayWebhookRefundEvent::Created => Ok(Self::RefundSuccess),
//                 RazorpayWebhookRefundEvent::Failed => Ok(Self::RefundFailure),
//                 RazorpayWebhookRefundEvent::SpeedChange => Ok(Self::EventNotSupported),
//             },
//         }
//     }
// }


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

impl api::RefundExecute for for Finix


// Struct: PlaidBankAccountCredentialsNumbers
// File: crates/pm_auth/src/connector/plaid/transformers.rs
// Module: pm_auth
// Implementations: 0

pub struct PlaidBankAccountCredentialsNumbers


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

impl api::PaymentVoid for for Breadpay


// Implementation: impl Responder
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 0 total (0 public)

impl Responder


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

pub struct RefundResponse


// Struct: CardsNon3DSRequest
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CardsNon3DSRequest


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

pub fn get_amount_field(&self, index: SearchIndex) -> &str


// Implementation: impl CaptureUpdate
// File: crates/diesel_models/src/capture.rs
// Module: diesel_models
// Methods: 1 total (1 public)

impl CaptureUpdate


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

pub struct Session


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

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


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

pub fn get_attempt_merchant_connector_account_id(
        &self,
    ) -> CustomResult<
        id_type::MerchantConnectorAccountId,
        errors::api_error_response::ApiErrorResponse,
    >


// Struct: HyperswitchVault
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
// Module: hyperswitch_connectors
// Implementations: 18
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, api::ExternalVaultCreate, api::ConnectorCustomer, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications

pub struct HyperswitchVault

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


// Function: capture_status_from_transaction_state
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
// Module: hyperswitch_connectors

pub fn capture_status_from_transaction_state(getnet_status: GetnetPaymentStatus) -> AttemptStatus


// Struct: InvoiceUpdate
// File: crates/diesel_models/src/invoice.rs
// Module: diesel_models
// Implementations: 1

pub struct InvoiceUpdate


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

pub fn refresh_connector_auth(
    state: &SessionState,
    connector: &api_types::ConnectorData,
    _merchant_context: &domain::MerchantContext,
    router_data: &types::RouterData<
        api_types::AccessTokenAuth,
        types::AccessTokenRequestData,
        types::AccessToken,
    >,
) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>>


// Implementation: impl IncomingWebhook for for Bamboraapac
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)

impl IncomingWebhook for for Bamboraapac


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

pub struct FiuuWebhookSignature


// Struct: RefundFilterRow
// File: crates/analytics/src/refunds/filters.rs
// Module: analytics
// Implementations: 0

pub struct RefundFilterRow


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

pub struct OpensearchErrorDetails


// Struct: LimitByClause
// File: crates/analytics/src/query.rs
// Module: analytics
// Implementations: 1
// Traits: fmt::Display

pub struct LimitByClause


// Function: find_by_merchant_id_dispute_id
// File: crates/diesel_models/src/query/dispute.rs
// Module: diesel_models

pub fn find_by_merchant_id_dispute_id(
        conn: &PgPooledConn,
        merchant_id: &common_utils::id_type::MerchantId,
        dispute_id: &str,
    ) -> StorageResult<Self>


// Struct: EventLinks
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct EventLinks


// File: crates/router/src/types/storage/locker_mock_up.rs
// Module: router

pub use diesel_models::locker_mock_up::{LockerMockUp, LockerMockUpNew};


// Struct: CybersourceConsumerAuthValidateResponse
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct CybersourceConsumerAuthValidateResponse


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

use serde;
use utoipa::ToSchema;

#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProductType {
    #[default]
    Physical,
    Digital,
    Travel,
    Ride,
    Event,
    Accommodation,
}


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

// Public submodules:
pub mod transformers;


// Struct: PayoutAttempt
// File: crates/diesel_models/src/payout_attempt.rs
// Module: diesel_models
// Implementations: 0

pub struct PayoutAttempt


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

impl PaypalAuthType


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

impl common_utils::events::ApiEventMetric for for RelayRetrieveBody


// Struct: UploadFileResponse
// File: crates/hyperswitch_domain_models/src/router_response_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct UploadFileResponse


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

pub struct RefundResponse


// Struct: DigitalvirgoConfirmRequest
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct DigitalvirgoConfirmRequest


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

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


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

impl MerchantConnectorResponse


// Struct: MerchantCountryCode
// File: crates/common_types/src/payments.rs
// Module: common_types
// Implementations: 1

pub struct MerchantCountryCode


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

pub struct SdkEventFilters


// Implementation: impl WorldpayErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)

impl WorldpayErrorResponse


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

pub struct Address


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

impl webhooks::IncomingWebhook for for Wellsfargo


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

pub struct ThreeDs


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

pub struct Links


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

impl api::PaymentSync for for Deutschebank


// Implementation: impl Action
// File: crates/router/src/core/revenue_recovery/types.rs
// Module: router
// Methods: 5 total (0 public)

impl Action


// Struct: BacsBankTransferAdditionalData
// File: crates/common_utils/src/payout_method_utils.rs
// Module: common_utils
// Implementations: 0

pub struct BacsBankTransferAdditionalData


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

// Documentation: Returns the token string if encrypted data exists, otherwise returns an error

pub fn get_encrypted_google_pay_token(&self) -> Result<String, errors::ValidationError>


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

pub struct NovalnetRefundTransaction


// Function: email_config
// File: crates/diesel_models/src/user/theme.rs
// Module: diesel_models

pub fn email_config(&self) -> EmailThemeConfig


// Struct: PaymentMethodsEnabledForConnector
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Module: hyperswitch_domain_models
// Implementations: 0

pub struct PaymentMethodsEnabledForConnector


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

pub struct BecsBankDebitAdditionalData


// Struct: AuthorizationUpdateInternal
// File: crates/diesel_models/src/authorization.rs
// Module: diesel_models
// Implementations: 1

pub struct AuthorizationUpdateInternal


// Struct: BokuRsyncResponse
// File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct BokuRsyncResponse


// File: crates/router/src/routes/chat.rs
// Module: router
// Public functions: 2

use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "olap")]
use api_models::chat as chat_api;
use router_env::{instrument, tracing, Flow};

use super::AppState;
use crate::{
    core::{api_locking, chat as chat_core},
    routes::metrics,
    services::{
        api,
        authentication::{self as auth},
        authorization::permissions::Permission,
    },
};

#[instrument(skip_all)]
pub async fn get_data_from_hyperswitch_ai_workflow(
    state: web::Data<AppState>,
    http_req: HttpRequest,
    payload: web::Json<chat_api::ChatRequest>,
) -> HttpResponse {
    let flow = Flow::GetDataFromHyperswitchAiFlow;
    let session_id = http_req
        .headers()
        .get(common_utils::consts::X_CHAT_SESSION_ID)
        .and_then(|header_value| header_value.to_str().ok());
    Box::pin(api::server_wrap(
        flow.clone(),
        state,
        &http_req,
        payload.into_inner(),
        |state, user: auth::UserFromToken, payload, _| {
            metrics::CHAT_REQUEST_COUNT.add(
                1,
                router_env::metric_attributes!(("merchant_id", user.merchant_id.clone())),
            );
            chat_core::get_data_from_hyperswitch_ai_workflow(state, user, payload, session_id)
        },
        // At present, the AI service retrieves data scoped to the merchant level
        &auth::JWTAuth {
            permission: Permission::MerchantPaymentRead,
        },
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[instrument(skip_all)]
pub async fn get_all_conversations(
    state: web::Data<AppState>,
    http_req: HttpRequest,
    payload: web::Query<chat_api::ChatListRequest>,
) -> HttpResponse {
    let flow = Flow::ListAllChatInteractions;
    Box::pin(api::server_wrap(
        flow.clone(),
        state,
        &http_req,
        payload.into_inner(),
        |state, user: auth::UserFromToken, payload, _| {
            chat_core::list_chat_conversations(state, user, payload)
        },
        &auth::DashboardNoPermissionAuth,
        api_locking::LockAction::NotApplicable,
    ))
    .await
}


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

pub struct PaymentsCancelData


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

impl api::UnifiedAuthenticationServiceV2 for for Recurly


// Struct: PaymeErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0

pub struct PaymeErrorResponse


// Struct: ClientSecretType
// File: crates/diesel_models/src/ephemeral_key.rs
// Module: diesel_models
// Implementations: 1

pub struct ClientSecretType


// Implementation: impl ConnectorErrorTypeMapping for for Payone
// File: crates/hyperswitch_connectors/src/connectors/payone.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)

impl ConnectorErrorTypeMapping for for Payone


// Function: create_subscription
// File: crates/router/src/core/subscription.rs
// Module: router

pub fn create_subscription(
    state: SessionState,
    merchant_context: MerchantContext,
    profile_id: String,
    request: subscription_types::CreateSubscriptionRequest,
) -> RouterResponse<CreateSubscriptionResponse>


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

pub struct FluidData


// Function: default
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors

pub fn default(status_code: u16) -> Self


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

impl api::ConnectorAccessToken for for Wellsfargopayout


// Struct: PollResponse
// File: crates/api_models/src/poll.rs
// Module: api_models
// Implementations: 1
// Traits: ApiEventMetric

pub struct PollResponse


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

impl api::PaymentSession for for Klarna


                "Blackburn with Darwen" => Ok(Self::BlackburnWithDarwen),
                "Blackpool" => Ok(Self::Blackpool),
                "Blaenau Gwent County Borough" => Ok(Self::BlaenauGwentCountyBorough),
                "Bolton" => Ok(Self::Bolton),
                "Bournemouth" => Ok(Self::Bournemouth),
                "Bracknell Forest" => Ok(Self::BracknellForest),
                "Bradford" => Ok(Self::Bradford),
                "Bridgend County Borough" => Ok(Self::BridgendCountyBorough),
                "Brighton and Hove" => Ok(Self::BrightonAndHove),
                "Buckinghamshire" => Ok(Self::Buckinghamshire),
                "Bury" => Ok(Self::Bury),
                "Caerphilly County Borough" => Ok(Self::CaerphillyCountyBorough),
                "Calderdale" => Ok(Self::Calderdale),
                "Cambridgeshire" => Ok(Self::Cambridgeshire),
                "Carmarthenshire" => Ok(Self::Carmarthenshire),
                "Carrickfergus Borough Council" => Ok(Self::CarrickfergusBoroughCouncil),
                "Castlereagh" => Ok(Self::Castlereagh),
                "Causeway Coast and Glens" => Ok(Self::CausewayCoastAndGlens),
                "Central Bedfordshire" => Ok(Self::CentralBedfordshire),
                "Ceredigion" => Ok(Self::Ceredigion),
                "Cheshire East" => Ok(Self::CheshireEast),
                "Cheshire West and Chester" => Ok(Self::CheshireWestAndChester),
                "City and County of Cardiff" => Ok(Self::CityAndCountyOfCardiff),
                "City and County of Swansea" => Ok(Self::CityAndCountyOfSwansea),
                "City of Bristol" => Ok(Self::CityOfBristol),
                "City of Derby" => Ok(Self::CityOfDerby),
                "City of Kingston upon Hull" => Ok(Self::CityOfKingstonUponHull),
                "City of Leicester" => Ok(Self::CityOfLeicester),
                "City of London" => Ok(Self::CityOfLondon),
                "City of Nottingham" => Ok(Self::CityOfNottingham),
                "City of Peterborough" => Ok(Self::CityOfPeterborough),
                "City of Plymouth" => Ok(Self::CityOfPlymouth),
                "City of Portsmouth" => Ok(Self::CityOfPortsmouth),
                "City of Southampton" => Ok(Self::CityOfSouthampton),
                "City of Stoke-on-Trent" => Ok(Self::CityOfStokeOnTrent),
                "City of Sunderland" => Ok(Self::CityOfSunderland),
                "City of Westminster" => Ok(Self::CityOfWestminster),
                "City of Wolverhampton" => Ok(Self::CityOfWolverhampton),
                "City of York" => Ok(Self::CityOfYork),
                "Clackmannanshire" => Ok(Self::Clackmannanshire),
                "Coleraine Borough Council" => Ok(Self::ColeraineBoroughCouncil),
                "Conwy County Borough" => Ok(Self::ConwyCountyBorough),
                "Cookstown District Council" => Ok(Self::CookstownDistrictCouncil),
                "Cornwall" => Ok(Self::Cornwall),
                "County Durham" => Ok(Self::CountyDurham),
                "Coventry" => Ok(Self::Coventry),
                "Craigavon Borough Council" => Ok(Self::CraigavonBoroughCouncil),
                "Cumbria" => Ok(Self::Cumbria),
                "Darlington" => Ok(Self::Darlington),
                "Denbighshire" => Ok(Self::Denbighshire),
                "Derbyshire" => Ok(Self::Derbyshire),
                "Derry City and Strabane" => Ok(Self::DerryCityAndStrabane),
                "Derry City Council" => Ok(Self::DerryCityCouncil),
                "Devon" => Ok(Self::Devon),
                "Doncaster" => Ok(Self::Doncaster),
                "Dorset" => Ok(Self::Dorset),
                "Down District Council" => Ok(Self::DownDistrictCouncil),
                "Dudley" => Ok(Self::Dudley),
                "Dumfries and Galloway" => Ok(Self::DumfriesAndGalloway),
                "Dundee" => Ok(Self::Dundee),
                "Dungannon and South Tyrone Borough Council" => {
                    Ok(Self::DungannonAndSouthTyroneBoroughCouncil)
                }
                "East Ayrshire" => Ok(Self::EastAyrshire),
                "East Dunbartonshire" => Ok(Self::EastDunbartonshire),
                "East Lothian" => Ok(Self::EastLothian),
                "East Renfrewshire" => Ok(Self::EastRenfrewshire),
                "East Riding of Yorkshire" => Ok(Self::EastRidingOfYorkshire),
                "East Sussex" => Ok(Self::EastSussex),
                "Edinburgh" => Ok(Self::Edinburgh),
                "England" => Ok(Self::England),
                "Essex" => Ok(Self::Essex),
                "Falkirk" => Ok(Self::Falkirk),
                "Fermanagh and Omagh" => Ok(Self::FermanaghAndOmagh),
                "Fermanagh District Council" => Ok(Self::FermanaghDistrictCouncil),
                "Fife" => Ok(Self::Fife),
                "Flintshire" => Ok(Self::Flintshire),
                "Gateshead" => Ok(Self::Gateshead),
                "Glasgow" => Ok(Self::Glasgow),
                "Gloucestershire" => Ok(Self::Gloucestershire),
                "Gwynedd" => Ok(Self::Gwynedd),
                "Halton" => Ok(Self::Halton),
                "Hampshire" => Ok(Self::Hampshire),
                "Hartlepool" => Ok(Self::Hartlepool),
                "Herefordshire" => Ok(Self::Herefordshire),
                "Hertfordshire" => Ok(Self::Hertfordshire),
                "Highland" => Ok(Self::Highland),
                "Inverclyde" => Ok(Self::Inverclyde),
                "Isle of Wight" => Ok(Self::IsleOfWight),
                "Isles of Scilly" => Ok(Self::IslesOfScilly),
                "Kent" => Ok(Self::Kent),
                "Kirklees" => Ok(Self::Kirklees),
                "Knowsley" => Ok(Self::Knowsley),
                "Lancashire" => Ok(Self::Lancashire),
                "Larne Borough Council" => Ok(Self::LarneBoroughCouncil),
                "Leeds" => Ok(Self::Leeds),
                "Leicestershire" => Ok(Self::Leicestershire),
                "Limavady Borough Council" => Ok(Self::LimavadyBoroughCouncil),
                "Lincolnshire" => Ok(Self::Lincolnshire),
                "Lisburn and Castlereagh" => Ok(Self::LisburnAndCastlereagh),
                "Lisburn City Council" => Ok(Self::LisburnCityCouncil),
                "Liverpool" => Ok(Self::Liverpool),
                "London Borough of Barking and Dagenham" => {
                    Ok(Self::LondonBoroughOfBarkingAndDagenham)
                }
                "London Borough of Barnet" => Ok(Self::LondonBoroughOfBarnet),
                "London Borough of Bexley" => Ok(Self::LondonBoroughOfBexley),
                "London Borough of Brent" => Ok(Self::LondonBoroughOfBrent),
                "London Borough of Bromley" => Ok(Self::LondonBoroughOfBromley),
                "London Borough of Camden" => Ok(Self::LondonBoroughOfCamden),
                "London Borough of Croydon" => Ok(Self::LondonBoroughOfCroydon),
                "London Borough of Ealing" => Ok(Self::LondonBoroughOfEaling),
                "London Borough of Enfield" => Ok(Self::LondonBoroughOfEnfield),
                "London Borough of Hackney" => Ok(Self::LondonBoroughOfHackney),
                "London Borough of Hammersmith and Fulham" => {
                    Ok(Self::LondonBoroughOfHammersmithAndFulham)
                }
                "London Borough of Haringey" => Ok(Self::LondonBoroughOfHaringey),
                "London Borough of Harrow" => Ok(Self::LondonBoroughOfHarrow),
                "London Borough of Havering" => Ok(Self::LondonBoroughOfHavering),
                "London Borough of Hillingdon" => Ok(Self::LondonBoroughOfHillingdon),
                "London Borough of Hounslow" => Ok(Self::LondonBoroughOfHounslow),
                "London Borough of Islington" => Ok(Self::LondonBoroughOfIslington),
                "London Borough of Lambeth" => Ok(Self::LondonBoroughOfLambeth),
                "London Borough of Lewisham" => Ok(Self::LondonBoroughOfLewisham),
                "London Borough of Merton" => Ok(Self::LondonBoroughOfMerton),
                "London Borough of Newham" => Ok(Self::LondonBoroughOfNewham),
                "London Borough of Redbridge" => Ok(Self::LondonBoroughOfRedbridge),
                "London Borough of Richmond upon Thames" => {
                    Ok(Self::LondonBoroughOfRichmondUponThames)
                }
                "London Borough of Southwark" => Ok(Self::LondonBoroughOfSouthwark),
                "London Borough of Sutton" => Ok(Self::LondonBoroughOfSutton),
                "London Borough of Tower Hamlets" => Ok(Self::LondonBoroughOfTowerHamlets),
                "London Borough of Waltham Forest" => Ok(Self::LondonBoroughOfWalthamForest),
                "London Borough of Wandsworth" => Ok(Self::LondonBoroughOfWandsworth),
                "Magherafelt District Council" => Ok(Self::MagherafeltDistrictCouncil),
                "Manchester" => Ok(Self::Manchester),
                "Medway" => Ok(Self::Medway),
                "Merthyr Tydfil County Borough" => Ok(Self::MerthyrTydfilCountyBorough),
                "Metropolitan Borough of Wigan" => Ok(Self::MetropolitanBoroughOfWigan),
                "Mid and East Antrim" => Ok(Self::MidAndEastAntrim),
                "Mid Ulster" => Ok(Self::MidUlster),
                "Middlesbrough" => Ok(Self::Middlesbrough),
                "Midlothian" => Ok(Self::Midlothian),
                "Milton Keynes" => Ok(Self::MiltonKeynes),
                "Monmouthshire" => Ok(Self::Monmouthshire),
                "Moray" => Ok(Self::Moray),
                "Moyle District Council" => Ok(Self::MoyleDistrictCouncil),
                "Neath Port Talbot County Borough" => Ok(Self::NeathPortTalbotCountyBorough),
                "Newcastle upon Tyne" => Ok(Self::NewcastleUponTyne),
                "Newport" => Ok(Self::Newport),
                "Newry and Mourne District Council" => Ok(Self::NewryAndMourneDistrictCouncil),
                "Newry, Mourne and Down" => Ok(Self::NewryMourneAndDown),
                "Newtownabbey Borough Council" => Ok(Self::NewtownabbeyBoroughCouncil),
                "Norfolk" => Ok(Self::Norfolk),
                "North Ayrshire" => Ok(Self::NorthAyrshire),
                "North Down Borough Council" => Ok(Self::NorthDownBoroughCouncil),
                "North East Lincolnshire" => Ok(Self::NorthEastLincolnshire),
                "North Lanarkshire" => Ok(Self::NorthLanarkshire),
                "North Lincolnshire" => Ok(Self::NorthLincolnshire),
                "North Somerset" => Ok(Self::NorthSomerset),
                "North Tyneside" => Ok(Self::NorthTyneside),
                "North Yorkshire" => Ok(Self::NorthYorkshire),
                "Northamptonshire" => Ok(Self::Northamptonshire),
                "Northern Ireland" => Ok(Self::NorthernIreland),
                "Northumberland" => Ok(Self::Northumberland),
                "Nottinghamshire" => Ok(Self::Nottinghamshire),
                "Oldham" => Ok(Self::Oldham),
                "Omagh District Council" => Ok(Self::OmaghDistrictCouncil),
                "Orkney Islands" => Ok(Self::OrkneyIslands),
                "Outer Hebrides" => Ok(Self::OuterHebrides),
                "Oxfordshire" => Ok(Self::Oxfordshire),
                "Pembrokeshire" => Ok(Self::Pembrokeshire),
                "Perth and Kinross" => Ok(Self::PerthAndKinross),
                "Poole" => Ok(Self::Poole),
                "Powys" => Ok(Self::Powys),
                "Reading" => Ok(Self::Reading),
                "Redcar and Cleveland" => Ok(Self::RedcarAndCleveland),
                "Renfrewshire" => Ok(Self::Renfrewshire),
                "Rhondda Cynon Taf" => Ok(Self::RhonddaCynonTaf),
                "Rochdale" => Ok(Self::Rochdale),
                "Rotherham" => Ok(Self::Rotherham),
                "Royal Borough of Greenwich" => Ok(Self::RoyalBoroughOfGreenwich),
                "Royal Borough of Kensington and Chelsea" => {
                    Ok(Self::RoyalBoroughOfKensingtonAndChelsea)
                }
                "Royal Borough of Kingston upon Thames" => {
                    Ok(Self::RoyalBoroughOfKingstonUponThames)
                }
                "Rutland" => Ok(Self::Rutland),
                "Saint Helena" => Ok(Self::SaintHelena),
                "Salford" => Ok(Self::Salford),
                "Sandwell" => Ok(Self::Sandwell),
                "Scotland" => Ok(Self::Scotland),
                "Scottish Borders" => Ok(Self::ScottishBorders),
                "Sefton" => Ok(Self::Sefton),
                "Sheffield" => Ok(Self::Sheffield),
                "Shetland Islands" => Ok(Self::ShetlandIslands),
                "Shropshire" => Ok(Self::Shropshire),
                "Slough" => Ok(Self::Slough),
                "Solihull" => Ok(Self::Solihull),
                "Somerset" => Ok(Self::Somerset),
                "South Ayrshire" => Ok(Self::SouthAyrshire),
                "South Gloucestershire" => Ok(Self::SouthGloucestershire),
                "South Lanarkshire" => Ok(Self::SouthLanarkshire),
                "South Tyneside" => Ok(Self::SouthTyneside),
                "Southend-on-Sea" => Ok(Self::SouthendOnSea),
                "St Helens" => Ok(Self::StHelens),
                "Staffordshire" => Ok(Self::Staffordshire),
                "Stirling" => Ok(Self::Stirling),
                "Stockport" => Ok(Self::Stockport),
                "Stockton-on-Tees" => Ok(Self::StocktonOnTees),
                "Strabane District Council" => Ok(Self::StrabaneDistrictCouncil),
                "Suffolk" => Ok(Self::Suffolk),
                "Surrey" => Ok(Self::Surrey),
                "Swindon" => Ok(Self::Swindon),
                "Tameside" => Ok(Self::Tameside),
                "Telford and Wrekin" => Ok(Self::TelfordAndWrekin),
                "Thurrock" => Ok(Self::Thurrock),
                "Torbay" => Ok(Self::Torbay),
                "Torfaen" => Ok(Self::Torfaen),
                "Trafford" => Ok(Self::Trafford),
                "United Kingdom" => Ok(Self::UnitedKingdom),
                "Vale of Glamorgan" => Ok(Self::ValeOfGlamorgan),
                "Wakefield" => Ok(Self::Wakefield),
                "Wales" => Ok(Self::Wales),
                "Walsall" => Ok(Self::Walsall),
                "Warrington" => Ok(Self::Warrington),
                "Warwickshire" => Ok(Self::Warwickshire),
                "West Berkshire" => Ok(Self::WestBerkshire),
                "West Dunbartonshire" => Ok(Self::WestDunbartonshire),
                "West Lothian" => Ok(Self::WestLothian),
                "West Sussex" => Ok(Self::WestSussex),
                "Wiltshire" => Ok(Self::Wiltshire),
                "Windsor and Maidenhead" => Ok(Self::WindsorAndMaidenhead),
                "Wirral" => Ok(Self::Wirral),
                "Wokingham" => Ok(Self::Wokingham),
                "Worcestershire" => Ok(Self::Worcestershire),
                "Wrexham County Borough" => Ok(Self::WrexhamCountyBorough),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for BelgiumStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "BelgiumStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Antwerp" => Ok(Self::Antwerp),
                "Brussels-Capital Region" => Ok(Self::BrusselsCapitalRegion),
                "East Flanders" => Ok(Self::EastFlanders),
                "Flanders" => Ok(Self::Flanders),
                "Flemish Brabant" => Ok(Self::FlemishBrabant),
                "Hainaut" => Ok(Self::Hainaut),
                "Limburg" => Ok(Self::Limburg),
                "Liège" => Ok(Self::Liege),
                "Luxembourg" => Ok(Self::Luxembourg),
                "Namur" => Ok(Self::Namur),
                "Wallonia" => Ok(Self::Wallonia),
                "Walloon Brabant" => Ok(Self::WalloonBrabant),
                "West Flanders" => Ok(Self::WestFlanders),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for LuxembourgStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "LuxembourgStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Canton of Capellen" => Ok(Self::CantonOfCapellen),
                "Canton of Clervaux" => Ok(Self::CantonOfClervaux),
                "Canton of Diekirch" => Ok(Self::CantonOfDiekirch),
                "Canton of Echternach" => Ok(Self::CantonOfEchternach),
                "Canton of Esch-sur-Alzette" => Ok(Self::CantonOfEschSurAlzette),
                "Canton of Grevenmacher" => Ok(Self::CantonOfGrevenmacher),
                "Canton of Luxembourg" => Ok(Self::CantonOfLuxembourg),
                "Canton of Mersch" => Ok(Self::CantonOfMersch),
                "Canton of Redange" => Ok(Self::CantonOfRedange),
                "Canton of Remich" => Ok(Self::CantonOfRemich),
                "Canton of Vianden" => Ok(Self::CantonOfVianden),
                "Canton of Wiltz" => Ok(Self::CantonOfWiltz),
                "Diekirch District" => Ok(Self::DiekirchDistrict),
                "Grevenmacher District" => Ok(Self::GrevenmacherDistrict),
                "Luxembourg District" => Ok(Self::LuxembourgDistrict),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for RussiaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "RussiaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Altai Krai" => Ok(Self::AltaiKrai),
                "Altai Republic" => Ok(Self::AltaiRepublic),
                "Amur Oblast" => Ok(Self::AmurOblast),
                "Arkhangelsk" => Ok(Self::Arkhangelsk),
                "Astrakhan Oblast" => Ok(Self::AstrakhanOblast),
                "Belgorod Oblast" => Ok(Self::BelgorodOblast),
                "Bryansk Oblast" => Ok(Self::BryanskOblast),
                "Chechen Republic" => Ok(Self::ChechenRepublic),
                "Chelyabinsk Oblast" => Ok(Self::ChelyabinskOblast),
                "Chukotka Autonomous Okrug" => Ok(Self::ChukotkaAutonomousOkrug),
                "Chuvash Republic" => Ok(Self::ChuvashRepublic),
                "Irkutsk" => Ok(Self::Irkutsk),
                "Ivanovo Oblast" => Ok(Self::IvanovoOblast),
                "Jewish Autonomous Oblast" => Ok(Self::JewishAutonomousOblast),
                "Kabardino-Balkar Republic" => Ok(Self::KabardinoBalkarRepublic),
                "Kaliningrad" => Ok(Self::Kaliningrad),
                "Kaluga Oblast" => Ok(Self::KalugaOblast),
                "Kamchatka Krai" => Ok(Self::KamchatkaKrai),
                "Karachay-Cherkess Republic" => Ok(Self::KarachayCherkessRepublic),
                "Kemerovo Oblast" => Ok(Self::KemerovoOblast),
                "Khabarovsk Krai" => Ok(Self::KhabarovskKrai),
                "Khanty-Mansi Autonomous Okrug" => Ok(Self::KhantyMansiAutonomousOkrug),
                "Kirov Oblast" => Ok(Self::KirovOblast),
                "Komi Republic" => Ok(Self::KomiRepublic),
                "Kostroma Oblast" => Ok(Self::KostromaOblast),
                "Krasnodar Krai" => Ok(Self::KrasnodarKrai),
                "Krasnoyarsk Krai" => Ok(Self::KrasnoyarskKrai),
                "Kurgan Oblast" => Ok(Self::KurganOblast),
                "Kursk Oblast" => Ok(Self::KurskOblast),
                "Leningrad Oblast" => Ok(Self::LeningradOblast),
                "Lipetsk Oblast" => Ok(Self::LipetskOblast),
                "Magadan Oblast" => Ok(Self::MagadanOblast),
                "Mari El Republic" => Ok(Self::MariElRepublic),
                "Moscow" => Ok(Self::Moscow),
                "Moscow Oblast" => Ok(Self::MoscowOblast),
                "Murmansk Oblast" => Ok(Self::MurmanskOblast),
                "Nenets Autonomous Okrug" => Ok(Self::NenetsAutonomousOkrug),
                "Nizhny Novgorod Oblast" => Ok(Self::NizhnyNovgorodOblast),
                "Novgorod Oblast" => Ok(Self::NovgorodOblast),
                "Novosibirsk" => Ok(Self::Novosibirsk),
                "Omsk Oblast" => Ok(Self::OmskOblast),
                "Orenburg Oblast" => Ok(Self::OrenburgOblast),
                "Oryol Oblast" => Ok(Self::OryolOblast),
                "Penza Oblast" => Ok(Self::PenzaOblast),
                "Perm Krai" => Ok(Self::PermKrai),
                "Primorsky Krai" => Ok(Self::PrimorskyKrai),
                "Pskov Oblast" => Ok(Self::PskovOblast),
                "Republic of Adygea" => Ok(Self::RepublicOfAdygea),
                "Republic of Bashkortostan" => Ok(Self::RepublicOfBashkortostan),
                "Republic of Buryatia" => Ok(Self::RepublicOfBuryatia),
                "Republic of Dagestan" => Ok(Self::RepublicOfDagestan),
                "Republic of Ingushetia" => Ok(Self::RepublicOfIngushetia),
                "Republic of Kalmykia" => Ok(Self::RepublicOfKalmykia),
                "Republic of Karelia" => Ok(Self::RepublicOfKarelia),
                "Republic of Khakassia" => Ok(Self::RepublicOfKhakassia),
                "Republic of Mordovia" => Ok(Self::RepublicOfMordovia),
                "Republic of North Ossetia-Alania" => Ok(Self::RepublicOfNorthOssetiaAlania),
                "Republic of Tatarstan" => Ok(Self::RepublicOfTatarstan),
                "Rostov Oblast" => Ok(Self::RostovOblast),
                "Ryazan Oblast" => Ok(Self::RyazanOblast),
                "Saint Petersburg" => Ok(Self::SaintPetersburg),
                "Sakha Republic" => Ok(Self::SakhaRepublic),
                "Sakhalin" => Ok(Self::Sakhalin),
                "Samara Oblast" => Ok(Self::SamaraOblast),
                "Saratov Oblast" => Ok(Self::SaratovOblast),
                "Sevastopol" => Ok(Self::Sevastopol),
                "Smolensk Oblast" => Ok(Self::SmolenskOblast),
                "Stavropol Krai" => Ok(Self::StavropolKrai),
                "Sverdlovsk" => Ok(Self::Sverdlovsk),
                "Tambov Oblast" => Ok(Self::TambovOblast),
                "Tomsk Oblast" => Ok(Self::TomskOblast),
                "Tula Oblast" => Ok(Self::TulaOblast),
                "Tuva Republic" => Ok(Self::TuvaRepublic),
                "Tver Oblast" => Ok(Self::TverOblast),
                "Tyumen Oblast" => Ok(Self::TyumenOblast),
                "Udmurt Republic" => Ok(Self::UdmurtRepublic),
                "Ulyanovsk Oblast" => Ok(Self::UlyanovskOblast),
                "Vladimir Oblast" => Ok(Self::VladimirOblast),
                "Vologda Oblast" => Ok(Self::VologdaOblast),
                "Voronezh Oblast" => Ok(Self::VoronezhOblast),
                "Yamalo-Nenets Autonomous Okrug" => Ok(Self::YamaloNenetsAutonomousOkrug),
                "Yaroslavl Oblast" => Ok(Self::YaroslavlOblast),
                "Zabaykalsky Krai" => Ok(Self::ZabaykalskyKrai),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SanMarinoStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SanMarinoStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Acquaviva" => Ok(Self::Acquaviva),
                "Borgo Maggiore" => Ok(Self::BorgoMaggiore),
                "Chiesanuova" => Ok(Self::Chiesanuova),
                "Domagnano" => Ok(Self::Domagnano),
                "Faetano" => Ok(Self::Faetano),
                "Fiorentino" => Ok(Self::Fiorentino),
                "Montegiardino" => Ok(Self::Montegiardino),
                "San Marino" => Ok(Self::SanMarino),
                "Serravalle" => Ok(Self::Serravalle),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SerbiaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SerbiaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Belgrade" => Ok(Self::Belgrade),
                "Bor District" => Ok(Self::BorDistrict),
                "Braničevo District" => Ok(Self::BraničevoDistrict),
                "Central Banat District" => Ok(Self::CentralBanatDistrict),
                "Jablanica District" => Ok(Self::JablanicaDistrict),
                "Kolubara District" => Ok(Self::KolubaraDistrict),
                "Mačva District" => Ok(Self::MačvaDistrict),
                "Moravica District" => Ok(Self::MoravicaDistrict),
                "Nišava District" => Ok(Self::NišavaDistrict),
                "North Banat District" => Ok(Self::NorthBanatDistrict),
                "North Bačka District" => Ok(Self::NorthBačkaDistrict),
                "Pirot District" => Ok(Self::PirotDistrict),
                "Podunavlje District" => Ok(Self::PodunavljeDistrict),
                "Pomoravlje District" => Ok(Self::PomoravljeDistrict),
                "Pčinja District" => Ok(Self::PčinjaDistrict),
                "Rasina District" => Ok(Self::RasinaDistrict),
                "Raška District" => Ok(Self::RaškaDistrict),
                "South Banat District" => Ok(Self::SouthBanatDistrict),
                "South Bačka District" => Ok(Self::SouthBačkaDistrict),
                "Srem District" => Ok(Self::SremDistrict),
                "Toplica District" => Ok(Self::ToplicaDistrict),
                "Vojvodina" => Ok(Self::Vojvodina),
                "West Bačka District" => Ok(Self::WestBačkaDistrict),
                "Zaječar District" => Ok(Self::ZaječarDistrict),
                "Zlatibor District" => Ok(Self::ZlatiborDistrict),
                "Šumadija District" => Ok(Self::ŠumadijaDistrict),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SlovakiaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SlovakiaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Banská Bystrica Region" => Ok(Self::BanskaBystricaRegion),
                "Bratislava Region" => Ok(Self::BratislavaRegion),
                "Košice Region" => Ok(Self::KosiceRegion),
                "Nitra Region" => Ok(Self::NitraRegion),
                "Prešov Region" => Ok(Self::PresovRegion),
                "Trenčín Region" => Ok(Self::TrencinRegion),
                "Trnava Region" => Ok(Self::TrnavaRegion),
                "Žilina Region" => Ok(Self::ZilinaRegion),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SwedenStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SwedenStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Blekinge" => Ok(Self::Blekinge),
                "Dalarna County" => Ok(Self::DalarnaCounty),
                "Gotland County" => Ok(Self::GotlandCounty),
                "Gävleborg County" => Ok(Self::GävleborgCounty),
                "Halland County" => Ok(Self::HallandCounty),
                "Jönköping County" => Ok(Self::JönköpingCounty),
                "Kalmar County" => Ok(Self::KalmarCounty),
                "Kronoberg County" => Ok(Self::KronobergCounty),
                "Norrbotten County" => Ok(Self::NorrbottenCounty),
                "Skåne County" => Ok(Self::SkåneCounty),
                "Stockholm County" => Ok(Self::StockholmCounty),
                "Södermanland County" => Ok(Self::SödermanlandCounty),
                "Uppsala County" => Ok(Self::UppsalaCounty),
                "Värmland County" => Ok(Self::VärmlandCounty),
                "Västerbotten County" => Ok(Self::VästerbottenCounty),
                "Västernorrland County" => Ok(Self::VästernorrlandCounty),
                "Västmanland County" => Ok(Self::VästmanlandCounty),
                "Västra Götaland County" => Ok(Self::VästraGötalandCounty),
                "Örebro County" => Ok(Self::ÖrebroCounty),
                "Östergötland County" => Ok(Self::ÖstergötlandCounty),
                _ => Err(errors::ConnectorError::InvalidDataFormat {
                    field_name: "address.state",
                }
                .into()),
            },
        }
    }
}

impl ForeignTryFrom<String> for SloveniaStatesAbbreviation {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
        let state_abbreviation_check =
            StringExt::<Self>::parse_enum(value.clone(), "SloveniaStatesAbbreviation");
        match state_abbreviation_check {
            Ok(state_abbreviation) => Ok(state_abbreviation),
            Err(_) => match value.as_str() {
                "Ajdovščina Municipality" => Ok(Self::Ajdovščina),
                "Ankaran Municipality" => Ok(Self::Ankaran),
                "Beltinci Municipality" => Ok(Self::Beltinci),
                "Benedikt Municipality" => Ok(Self::Benedikt),
                "Bistrica ob Sotli Municipality" => Ok(Self::BistricaObSotli),
                "Bled Municipality" => Ok(Self::Bled),
                "Bloke Municipality" => Ok(Self::Bloke),
                "Bohinj Municipality" => Ok(Self::Bohinj),
                "Borovnica Municipality" => Ok(Self::Borovnica),
                "Bovec Municipality" => Ok(Self::Bovec),
                "Braslovče Municipality" => Ok(Self::Braslovče),
                "Brda Municipality" => Ok(Self::Brda),
                "Brezovica Municipality" => Ok(Self::Brezovica),
                "Brežice Municipality" => Ok(Self::Brežice),
                "Cankova Municipality" => Ok(Self::Cankova),
                "Cerklje na Gorenjskem Municipality" => Ok(Self::CerkljeNaGorenjskem),
                "Cerknica Municipality" => Ok(Self::Cerknica),
                "Cerkno Municipality" => Ok(Self::Cerkno),


// Function: payments_post_session_tokens
// File: crates/openapi/src/routes/payments.rs
// Module: openapi

pub fn payments_post_session_tokens()