File: crates/openapi/src/openapi.rs

use crate::routes;

#[derive(utoipa::OpenApi)]
#[openapi(
    info(
        title = "Hyperswitch - API Documentation",
        contact(
            name = "Hyperswitch Support",
            url = "https://hyperswitch.io",
            email = "hyperswitch@juspay.in"
        ),
        // terms_of_service = "https://www.juspay.io/terms",
        description = r#"
## Get started

Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.

You can consume the APIs directly using your favorite HTTP/REST library.

We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.

### Environment

Use the following base URLs when making requests to the APIs:

| Environment   |  Base URL                          |
|---------------|------------------------------------|
| Sandbox       | <https://sandbox.hyperswitch.io>   |
| Production    | <https://api.hyperswitch.io>       |

## Authentication

When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.

| Key             |  Description                                                                                |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key         | Private key. Used to authenticate all API requests from your merchant server                  |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client  |

Never share your secret api keys. Keep them guarded and secure.
"#,
    ),
    servers(
        (url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
    ),
    tags(
        (name = "Merchant Account", description = "Create and manage merchant accounts"),
        (name = "Profile", description = "Create and manage profiles"),
        (name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
        (name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
        (name = "Refunds", description = "Create and manage refunds for successful payments"),
        (name = "Mandates", description = "Manage mandates"),
        (name = "Customers", description = "Create and manage customers"),
        (name = "Payment Methods", description = "Create and manage payment methods of customers"),
        (name = "Disputes", description = "Manage disputes"),
        (name = "API Key", description = "Create and manage API Keys"),
        (name = "Payouts", description = "Create and manage payouts"),
        (name = "payment link", description = "Create payment link"),
        (name = "Routing", description = "Create and manage routing configurations"),
        (name = "Event", description = "Manage events"),
        (name = "Authentication", description = "Create and manage authentication")
    ),
    // The paths will be displayed in the same order as they are registered here
    paths(
        // Routes for payments
        routes::payments::payments_create,
        routes::payments::payments_update,
        routes::payments::payments_confirm,
        routes::payments::payments_retrieve,
        routes::payments::payments_capture,
        routes::payments::payments_connector_session,
        routes::payments::payments_cancel,
        routes::payments::payments_cancel_post_capture,
        routes::payments::payments_list,
        routes::payments::payments_incremental_authorization,
        routes::payment_link::payment_link_retrieve,
        routes::payments::payments_external_authentication,
        routes::payments::payments_complete_authorize,
        routes::payments::payments_post_session_tokens,
        routes::payments::payments_update_metadata,

        // Routes for relay
        routes::relay::relay,
        routes::relay::relay_retrieve,

        // Routes for refunds
        routes::refunds::refunds_create,
        routes::refunds::refunds_retrieve,
        routes::refunds::refunds_update,
        routes::refunds::refunds_list,

        // Routes for Organization
        routes::organization::organization_create,
        routes::organization::organization_retrieve,
        routes::organization::organization_update,

        // Routes for merchant account
        routes::merchant_account::merchant_account_create,
        routes::merchant_account::retrieve_merchant_account,
        routes::merchant_account::update_merchant_account,
        routes::merchant_account::delete_merchant_account,
        routes::merchant_account::merchant_account_kv_status,

        // Routes for merchant connector account
        routes::merchant_connector_account::connector_create,
        routes::merchant_connector_account::connector_retrieve,
        routes::merchant_connector_account::connector_list,
        routes::merchant_connector_account::connector_update,
        routes::merchant_connector_account::connector_delete,

        //Routes for gsm
        routes::gsm::create_gsm_rule,
        routes::gsm::get_gsm_rule,
        routes::gsm::update_gsm_rule,
        routes::gsm::delete_gsm_rule,

        // Routes for mandates
        routes::mandates::get_mandate,
        routes::mandates::revoke_mandate,
        routes::mandates::customers_mandates_list,

        //Routes for customers
        routes::customers::customers_create,
        routes::customers::customers_retrieve,
        routes::customers::customers_list,
        routes::customers::customers_update,
        routes::customers::customers_delete,

        //Routes for payment methods
        routes::payment_method::create_payment_method_api,
        routes::payment_method::list_payment_method_api,
        routes::payment_method::list_customer_payment_method_api,
        routes::payment_method::list_customer_payment_method_api_client,
        routes::payment_method::default_payment_method_set_api,
        routes::payment_method::payment_method_retrieve_api,
        routes::payment_method::payment_method_update_api,
        routes::payment_method::payment_method_delete_api,

        // Routes for Profile
        routes::profile::profile_create,
        routes::profile::profile_list,
        routes::profile::profile_retrieve,
        routes::profile::profile_update,
        routes::profile::profile_delete,

        // Routes for disputes
        routes::disputes::retrieve_dispute,
        routes::disputes::retrieve_disputes_list,

        // Routes for routing
        routes::routing::routing_create_config,
        routes::routing::routing_link_config,
        routes::routing::routing_retrieve_config,
        routes::routing::list_routing_configs,
        routes::routing::routing_unlink_config,
        routes::routing::routing_update_default_config,
        routes::routing::routing_retrieve_default_config,
        routes::routing::routing_retrieve_linked_config,
        routes::routing::routing_retrieve_default_config_for_profiles,
        routes::routing::routing_update_default_config_for_profile,
        routes::routing::success_based_routing_update_configs,
        routes::routing::toggle_success_based_routing,
        routes::routing::toggle_elimination_routing,
        routes::routing::contract_based_routing_setup_config,
        routes::routing::contract_based_routing_update_configs,
        routes::routing::call_decide_gateway_open_router,
        routes::routing::call_update_gateway_score_open_router,
        routes::routing::evaluate_routing_rule,

        // Routes for blocklist
        routes::blocklist::remove_entry_from_blocklist,
        routes::blocklist::list_blocked_payment_methods,
        routes::blocklist::add_entry_to_blocklist,
        routes::blocklist::toggle_blocklist_guard,

        // Routes for payouts
        routes::payouts::payouts_create,
        routes::payouts::payouts_retrieve,
        routes::payouts::payouts_update,
        routes::payouts::payouts_cancel,
        routes::payouts::payouts_fulfill,
        routes::payouts::payouts_list,
        routes::payouts::payouts_confirm,
        routes::payouts::payouts_list_filters,
        routes::payouts::payouts_list_by_filter,

        // Routes for api keys
        routes::api_keys::api_key_create,
        routes::api_keys::api_key_retrieve,
        routes::api_keys::api_key_update,
        routes::api_keys::api_key_revoke,
        routes::api_keys::api_key_list,

        // Routes for events
        routes::webhook_events::list_initial_webhook_delivery_attempts,
        routes::webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth,
        routes::webhook_events::list_webhook_delivery_attempts,
        routes::webhook_events::retry_webhook_delivery_attempt,

        // Routes for poll apis
        routes::poll::retrieve_poll_status,

        // Routes for profile acquirer account
        routes::profile_acquirer::profile_acquirer_create,
        routes::profile_acquirer::profile_acquirer_update,

        // Routes for 3DS Decision Rule
        routes::three_ds_decision_rule::three_ds_decision_rule_execute,

        // Routes for authentication
        routes::authentication::authentication_create,

        // Routes for platform account
        routes::platform::create_platform_account,
    ),
    components(schemas(
        common_utils::types::MinorUnit,
        common_utils::types::StringMinorUnit,
        common_utils::types::TimeRange,
        common_utils::link_utils::GenericLinkUiConfig,
        common_utils::link_utils::EnabledPaymentMethod,
        common_utils::payout_method_utils::AdditionalPayoutMethodData,
        common_utils::payout_method_utils::CardAdditionalData,
        common_utils::payout_method_utils::BankAdditionalData,
        common_utils::payout_method_utils::WalletAdditionalData,
        common_utils::payout_method_utils::AchBankTransferAdditionalData,
        common_utils::payout_method_utils::BacsBankTransferAdditionalData,
        common_utils::payout_method_utils::SepaBankTransferAdditionalData,
        common_utils::payout_method_utils::PixBankTransferAdditionalData,
        common_utils::payout_method_utils::PaypalAdditionalData,
        common_utils::payout_method_utils::VenmoAdditionalData,
        common_types::payments::SplitPaymentsRequest,
        common_types::payments::GpayTokenizationData,
        common_types::payments::GPayPredecryptData,
        common_types::payments::GpayEcryptedTokenizationData,
        common_types::payments::ApplePayPaymentData,
        common_types::payments::ApplePayPredecryptData,
        common_types::payments::ApplePayCryptogramData,
        common_types::payments::StripeSplitPaymentRequest,
        common_types::domain::AdyenSplitData,
        common_types::domain::AdyenSplitItem,
        common_types::payments::AcceptanceType,
        common_types::payments::CustomerAcceptance,
        common_types::payments::OnlineMandate,
        common_types::payments::XenditSplitRequest,
        common_types::payments::XenditSplitRoute,
        common_types::payments::XenditChargeResponseData,
        common_types::payments::XenditMultipleSplitResponse,
        common_types::payments::XenditMultipleSplitRequest,
        common_types::domain::XenditSplitSubMerchantData,
        common_utils::types::ChargeRefunds,
        common_types::refunds::SplitRefund,
        common_types::refunds::StripeSplitRefundRequest,
        common_types::payments::ConnectorChargeResponseData,
        common_types::payments::StripeChargeResponseData,
        common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
        common_types::three_ds_decision_rule_engine::ThreeDSDecision,
        common_types::payments::MerchantCountryCode,
        api_models::enums::PaymentChannel,
        api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
        api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse,
        api_models::three_ds_decision_rule::PaymentData,
        api_models::three_ds_decision_rule::PaymentMethodMetaData,
        api_models::three_ds_decision_rule::CustomerDeviceData,
        api_models::three_ds_decision_rule::IssuerData,
        api_models::three_ds_decision_rule::AcquirerData,
        api_models::refunds::RefundRequest,
        api_models::refunds::RefundType,
        api_models::refunds::RefundResponse,
        api_models::refunds::RefundStatus,
        api_models::refunds::RefundUpdateRequest,
        api_models::organization::OrganizationCreateRequest,
        api_models::organization::OrganizationUpdateRequest,
        api_models::organization::OrganizationResponse,
        api_models::admin::MerchantAccountCreate,
        api_models::admin::MerchantAccountUpdate,
        api_models::admin::MerchantAccountDeleteResponse,
        api_models::admin::MerchantConnectorDeleteResponse,
        api_models::admin::MerchantConnectorResponse,
        api_models::admin::MerchantConnectorListResponse,
        api_models::admin::AuthenticationConnectorDetails,
        api_models::admin::ExtendedCardInfoConfig,
        api_models::admin::BusinessGenericLinkConfig,
        api_models::admin::BusinessCollectLinkConfig,
        api_models::admin::BusinessPayoutLinkConfig,
        api_models::admin::CardTestingGuardConfig,
        api_models::admin::CardTestingGuardStatus,
        api_models::customers::CustomerRequest,
        api_models::customers::CustomerUpdateRequest,
        api_models::customers::CustomerDeleteResponse,
        api_models::payment_methods::PaymentMethodCreate,
        api_models::payment_methods::PaymentMethodResponse,
        api_models::payment_methods::CustomerPaymentMethod,
        common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
        common_types::domain::AcquirerConfigMap,
        common_types::domain::AcquirerConfig,
        api_models::payment_methods::PaymentMethodListResponse,
        api_models::payment_methods::ResponsePaymentMethodsEnabled,
        api_models::payment_methods::ResponsePaymentMethodTypes,
        api_models::payment_methods::PaymentExperienceTypes,
        api_models::payment_methods::CardNetworkTypes,
        api_models::payment_methods::BankDebitTypes,
        api_models::payment_methods::BankTransferTypes,
        api_models::payment_methods::CustomerPaymentMethodsListResponse,
        api_models::payment_methods::PaymentMethodDeleteResponse,
        api_models::payment_methods::PaymentMethodUpdate,
        api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
        api_models::payment_methods::CardDetailFromLocker,
        api_models::payment_methods::PaymentMethodCreateData,
        api_models::payment_methods::CardDetail,
        api_models::payment_methods::CardDetailUpdate,
        api_models::payment_methods::RequestPaymentMethodTypes,
        api_models::poll::PollResponse,
        api_models::poll::PollStatus,
        api_models::customers::CustomerResponse,
        api_models::admin::AcceptedCountries,
        api_models::admin::AcceptedCurrencies,
        api_models::enums::AdyenSplitType,
        api_models::enums::PaymentType,
        api_models::enums::ScaExemptionType,
        api_models::enums::PaymentMethod,
        api_models::enums::TriggeredBy,
        api_models::enums::TokenDataType,
        api_models::enums::PaymentMethodType,
        api_models::enums::ConnectorType,
        api_models::enums::PayoutConnectors,
        api_models::enums::AuthenticationConnectors,
        api_models::enums::Currency,
        api_models::enums::DocumentKind,
        api_models::enums::IntentStatus,
        api_models::enums::CaptureMethod,
        api_models::enums::FutureUsage,
        api_models::enums::AuthenticationType,
        api_models::enums::Connector,
        api_models::enums::PaymentMethod,
        api_models::enums::PaymentMethodIssuerCode,
        api_models::enums::TaxStatus,
        api_models::enums::MandateStatus,
        api_models::enums::PaymentExperience,
        api_models::enums::BankNames,
        api_models::enums::BankType,
        api_models::enums::BankHolderType,
        api_models::enums::CardNetwork,
        api_models::enums::MerchantCategoryCode,
        api_models::enums::DisputeStage,
        api_models::enums::DisputeStatus,
        api_models::enums::CountryAlpha2,
        api_models::enums::Country,
        api_models::enums::CountryAlpha3,
        api_models::enums::FieldType,
        api_models::enums::FrmAction,
        api_models::enums::FrmPreferredFlowTypes,
        api_models::enums::RetryAction,
        api_models::enums::AttemptStatus,
        api_models::enums::CaptureStatus,
        api_models::enums::ReconStatus,
        api_models::enums::ConnectorStatus,
        api_models::enums::AuthorizationStatus,
        api_models::enums::ElementPosition,
        api_models::enums::ElementSize,
        api_models::enums::SizeVariants,
        api_models::enums::MerchantProductType,
        api_models::enums::PaymentLinkDetailsLayout,
        api_models::enums::PaymentMethodStatus,
        api_models::enums::UIWidgetFormLayout,
        api_models::enums::MerchantProductType,
        api_models::enums::HyperswitchConnectorCategory,
        api_models::enums::ConnectorIntegrationStatus,
        api_models::enums::CardDiscovery,
        api_models::enums::FeatureStatus,
        api_models::enums::MerchantProductType,
        api_models::enums::CtpServiceProvider,
        api_models::enums::PaymentLinkSdkLabelType,
        api_models::enums::OrganizationType,
        api_models::enums::PaymentLinkShowSdkTerms,
        api_models::admin::MerchantConnectorCreate,
        api_models::admin::AdditionalMerchantData,
        api_models::admin::ConnectorWalletDetails,
        api_models::admin::MerchantRecipientData,
        api_models::admin::MerchantAccountData,
        api_models::admin::MerchantConnectorUpdate,
        api_models::admin::PrimaryBusinessDetails,
        api_models::admin::FrmConfigs,
        api_models::admin::FrmPaymentMethod,
        api_models::admin::FrmPaymentMethodType,
        api_models::admin::PaymentMethodsEnabled,
        api_models::admin::MerchantConnectorDetailsWrap,
        api_models::admin::MerchantConnectorDetails,
        api_models::admin::MerchantConnectorWebhookDetails,
        api_models::admin::ProfileCreate,
        api_models::admin::ProfileResponse,
        api_models::admin::BusinessPaymentLinkConfig,
        api_models::admin::PaymentLinkBackgroundImageConfig,
        api_models::admin::PaymentLinkConfigRequest,
        api_models::admin::PaymentLinkConfig,
        api_models::admin::PaymentLinkTransactionDetails,
        api_models::admin::TransactionDetailsUiConfiguration,
        api_models::disputes::DisputeResponse,
        api_models::disputes::DisputeResponsePaymentsRetrieve,
        api_models::gsm::GsmCreateRequest,
        api_models::gsm::GsmRetrieveRequest,
        api_models::gsm::GsmUpdateRequest,
        api_models::gsm::GsmDeleteRequest,
        api_models::gsm::GsmDeleteResponse,
        api_models::gsm::GsmResponse,
        api_models::enums::GsmDecision,
        api_models::enums::GsmFeature,
        common_types::domain::GsmFeatureData,
        common_types::domain::RetryFeatureData,
        api_models::payments::AddressDetails,
        api_models::payments::BankDebitData,
        api_models::payments::AliPayQr,
        api_models::payments::AliPayRedirection,
        api_models::payments::MomoRedirection,
        api_models::payments::TouchNGoRedirection,
        api_models::payments::GcashRedirection,
        api_models::payments::KakaoPayRedirection,
        api_models::payments::AliPayHkRedirection,
        api_models::payments::GoPayRedirection,
        api_models::payments::MbWayRedirection,
        api_models::payments::MobilePayRedirection,
        api_models::payments::WeChatPayRedirection,
        api_models::payments::WeChatPayQr,
        api_models::payments::BankDebitBilling,
        api_models::payments::CryptoData,
        api_models::payments::RewardData,
        api_models::payments::UpiData,
        api_models::payments::UpiCollectData,
        api_models::payments::UpiIntentData,
        api_models::payments::VoucherData,
        api_models::payments::BoletoVoucherData,
        api_models::payments::AlfamartVoucherData,
        api_models::payments::IndomaretVoucherData,
        api_models::payments::Address,
        api_models::payments::VoucherData,
        api_models::payments::JCSVoucherData,
        api_models::payments::AlfamartVoucherData,
        api_models::payments::IndomaretVoucherData,
        api_models::payments::BankRedirectData,
        api_models::payments::RealTimePaymentData,
        api_models::payments::BankRedirectBilling,
        api_models::payments::BankRedirectBilling,
        api_models::payments::ConnectorMetadata,
        api_models::payments::FeatureMetadata,
        api_models::payments::ApplepayConnectorMetadataRequest,
        api_models::payments::SessionTokenInfo,
        api_models::payments::PaymentProcessingDetailsAt,
        api_models::payments::ApplepayInitiative,
        api_models::payments::PaymentProcessingDetails,
        api_models::payments::PaymentMethodDataResponseWithBilling,
        api_models::payments::PaymentMethodDataResponse,
        api_models::payments::CardResponse,
        api_models::payments::PaylaterResponse,
        api_models::payments::KlarnaSdkPaymentMethodResponse,
        api_models::payments::SwishQrData,
        api_models::payments::RevolutPayData,
        api_models::payments::AirwallexData,
        api_models::payments::BraintreeData,
        api_models::payments::NoonData,
        api_models::payments::OrderDetailsWithAmount,
        api_models::payments::NextActionType,
        api_models::payments::WalletData,
        api_models::payments::NextActionData,
        api_models::payments::PayLaterData,
        api_models::payments::MandateData,
        api_models::payments::PhoneDetails,
        api_models::payments::PaymentMethodData,
        api_models::payments::PaymentMethodDataRequest,
        api_models::payments::MandateType,
        api_models::payments::MandateAmountData,
        api_models::payments::Card,
        api_models::payments::CardRedirectData,
        api_models::payments::CardToken,
        api_models::payments::PaymentsRequest,
        api_models::payments::PaymentsCreateRequest,
        api_models::payments::PaymentsUpdateRequest,
        api_models::payments::PaymentsConfirmRequest,
        api_models::payments::PaymentsResponse,
        api_models::payments::PaymentsCreateResponseOpenApi,
        api_models::errors::types::GenericErrorResponseOpenApi,
        api_models::payments::PaymentRetrieveBody,
        api_models::payments::PaymentsRetrieveRequest,
        api_models::payments::PaymentsCaptureRequest,
        api_models::payments::PaymentsSessionRequest,
        api_models::payments::PaymentsSessionResponse,
        api_models::payments::PazeWalletData,
        api_models::payments::SessionToken,
        api_models::payments::ApplePaySessionResponse,
        api_models::payments::NullObject,
        api_models::payments::ThirdPartySdkSessionResponse,
        api_models::payments::NoThirdPartySdkSessionResponse,
        api_models::payments::SecretInfoToInitiateSdk,
        api_models::payments::ApplePayPaymentRequest,
        api_models::payments::ApplePayBillingContactFields,
        api_models::payments::ApplePayShippingContactFields,
        api_models::payments::ApplePayRecurringPaymentRequest,
        api_models::payments::ApplePayRegularBillingRequest,
        api_models::payments::ApplePayPaymentTiming,
        api_models::payments::RecurringPaymentIntervalUnit,
        api_models::payments::ApplePayRecurringDetails,
        api_models::payments::ApplePayRegularBillingDetails,
        api_models::payments::ApplePayAddressParameters,
        api_models::payments::AmountInfo,
        api_models::payments::ClickToPaySessionResponse,
        api_models::enums::ProductType,
        api_models::enums::MerchantAccountType,
        api_models::enums::MerchantAccountRequestType,
        api_models::payments::GooglePayWalletData,
        api_models::payments::PayPalWalletData,
        api_models::payments::PaypalRedirection,
        api_models::payments::GpayMerchantInfo,
        api_models::payments::GpayAllowedPaymentMethods,
        api_models::payments::GpayAllowedMethodsParameters,
        api_models::payments::GpayTokenizationSpecification,
        api_models::payments::GpayTokenParameters,
        api_models::payments::GpayTransactionInfo,
        api_models::payments::GpaySessionTokenResponse,
        api_models::payments::GooglePayThirdPartySdkData,
        api_models::payments::KlarnaSessionTokenResponse,
        api_models::payments::PaypalSessionTokenResponse,
        api_models::payments::ApplepaySessionTokenResponse,
        api_models::payments::SdkNextAction,
        api_models::payments::NextActionCall,
        api_models::payments::SdkNextActionData,
        api_models::payments::SamsungPayWalletData,
        api_models::payments::WeChatPay,
        api_models::payments::GooglePayPaymentMethodInfo,
        api_models::payments::ApplePayWalletData,
        api_models::payments::SamsungPayWalletCredentials,
        api_models::payments::SamsungPayWebWalletData,
        api_models::payments::SamsungPayAppWalletData,
        api_models::payments::SamsungPayCardBrand,
        api_models::payments::SamsungPayTokenData,
        api_models::payments::ApplepayPaymentMethod,
        api_models::payments::PaymentsCancelRequest,
        api_models::payments::PaymentsCancelPostCaptureRequest,
        api_models::payments::PaymentListConstraints,
        api_models::payments::PaymentListResponse,
        api_models::payments::CashappQr,
        api_models::payments::BankTransferData,
        api_models::payments::BankTransferNextStepsData,
        api_models::payments::SepaAndBacsBillingDetails,
        api_models::payments::AchBillingDetails,
        api_models::payments::MultibancoBillingDetails,
        api_models::payments::DokuBillingDetails,
        api_models::payments::BankTransferInstructions,
        api_models::payments::MobilePaymentNextStepData,
        api_models::payments::MobilePaymentConsent,
        api_models::payments::IframeData,
        api_models::payments::ReceiverDetails,
        api_models::payments::AchTransfer,
        api_models::payments::MultibancoTransferInstructions,
        api_models::payments::DokuBankTransferInstructions,
        api_models::payments::AmazonPayRedirectData,
        api_models::payments::SkrillData,
        api_models::payments::PayseraData,
        api_models::payments::ApplePayRedirectData,
        api_models::payments::ApplePayThirdPartySdkData,
        api_models::payments::GooglePayRedirectData,
        api_models::payments::GooglePayThirdPartySdk,
        api_models::payments::GooglePaySessionResponse,
        api_models::payments::PazeSessionTokenResponse,
        api_models::payments::SamsungPaySessionTokenResponse,
        api_models::payments::SamsungPayMerchantPaymentInformation,
        api_models::payments::SamsungPayAmountDetails,
        api_models::payments::SamsungPayAmountFormat,
        api_models::payments::SamsungPayProtocolType,
        api_models::payments::GpayShippingAddressParameters,
        api_models::payments::GpayBillingAddressParameters,
        api_models::payments::GpayBillingAddressFormat,
        api_models::payments::SepaBankTransferInstructions,
        api_models::payments::BacsBankTransferInstructions,
        api_models::payments::RedirectResponse,
        api_models::payments::RequestSurchargeDetails,
        api_models::payments::PaymentAttemptResponse,
        api_models::payments::CaptureResponse,
        api_models::payments::PaymentsIncrementalAuthorizationRequest,
        api_models::payments::IncrementalAuthorizationResponse,
        api_models::payments::PaymentsCompleteAuthorizeRequest,
        api_models::payments::PaymentsExternalAuthenticationRequest,
        api_models::payments::PaymentsExternalAuthenticationResponse,
        api_models::payments::SdkInformation,
        api_models::payments::DeviceChannel,
        api_models::payments::ThreeDsCompletionIndicator,
        api_models::payments::MifinityData,
        api_models::enums::TransactionStatus,
        api_models::payments::BrowserInformation,
        api_models::payments::PaymentCreatePaymentLinkConfig,
        api_models::payments::ThreeDsData,
        api_models::payments::ThreeDsMethodData,
        api_models::payments::PollConfigResponse,
        api_models::payments::PollConfig,
        api_models::payments::ExternalAuthenticationDetailsResponse,
        api_models::payments::ExtendedCardInfo,
        api_models::payments::AmazonPaySessionTokenData,
        api_models::payments::AmazonPayMerchantCredentials,
        api_models::payments::AmazonPayWalletData,
        api_models::payments::AmazonPaySessionTokenResponse,
        api_models::payments::AmazonPayPaymentIntent,
        api_models::payments::AmazonPayDeliveryOptions,
        api_models::payments::AmazonPayDeliveryPrice,
        api_models::payments::AmazonPayShippingMethod,
        api_models::payment_methods::RequiredFieldInfo,
        api_models::payment_methods::DefaultPaymentMethod,
        api_models::payment_methods::MaskedBankDetails,
        api_models::payment_methods::SurchargeDetailsResponse,
        api_models::payment_methods::SurchargeResponse,
        api_models::payment_methods::SurchargePercentage,
        api_models::payment_methods::PaymentMethodCollectLinkRequest,
        api_models::payment_methods::PaymentMethodCollectLinkResponse,
        api_models::payment_methods::CardType,
        api_models::payment_methods::CardNetworkTokenizeRequest,
        api_models::payment_methods::CardNetworkTokenizeResponse,
        api_models::payment_methods::TokenizeDataRequest,
        api_models::payment_methods::TokenizeCardRequest,
        api_models::payment_methods::TokenizePaymentMethodRequest,
        api_models::refunds::RefundListRequest,
        api_models::refunds::RefundListResponse,
        api_models::relay::RelayRequest,
        api_models::relay::RelayResponse,
        api_models::enums::RelayType,
        api_models::relay::RelayData,
        api_models::relay::RelayRefundRequestData,
        api_models::enums::RelayStatus,
        api_models::relay::RelayError,
        api_models::payments::AmountFilter,
        api_models::mandates::MandateRevokedResponse,
        api_models::mandates::MandateResponse,
        api_models::mandates::MandateCardDetails,
        api_models::mandates::RecurringDetails,
        api_models::mandates::NetworkTransactionIdAndCardDetails,
        api_models::mandates::ProcessorPaymentToken,
        api_models::ephemeral_key::EphemeralKeyCreateResponse,
        api_models::payments::CustomerDetails,
        api_models::payments::GiftCardData,
        api_models::payments::GiftCardDetails,
        api_models::payments::BHNGiftCardDetails,
        api_models::payments::MobilePaymentData,
        api_models::payments::MobilePaymentResponse,
        api_models::payments::Address,
        api_models::payments::BankCodeResponse,
        api_models::payouts::CardPayout,
        api_models::payouts::Wallet,
        api_models::payouts::Paypal,
        api_models::payouts::Venmo,
        api_models::payouts::AchBankTransfer,
        api_models::payouts::BacsBankTransfer,
        api_models::payouts::SepaBankTransfer,
        api_models::payouts::PixBankTransfer,
        api_models::payouts::PayoutsCreateRequest,
        api_models::payouts::PayoutUpdateRequest,
        api_models::payouts::PayoutConfirmRequest,
        api_models::payouts::PayoutCancelRequest,
        api_models::payouts::PayoutFulfillRequest,
        api_models::payouts::PayoutRetrieveRequest,
        api_models::payouts::PayoutAttemptResponse,
        api_models::payouts::PayoutCreateResponse,
        api_models::payouts::PayoutListConstraints,
        api_models::payouts::PayoutListFilters,
        api_models::payouts::PayoutListFilterConstraints,
        api_models::payouts::PayoutListResponse,
        api_models::payouts::PayoutRetrieveBody,
        api_models::payouts::PayoutMethodData,
        api_models::payouts::PayoutMethodDataResponse,
        api_models::payouts::PayoutLinkResponse,
        api_models::payouts::Bank,
        api_models::payouts::PayoutCreatePayoutLinkConfig,
        api_models::enums::PayoutEntityType,
        api_models::enums::PayoutSendPriority,
        api_models::enums::PayoutStatus,
        api_models::enums::PayoutType,
        api_models::enums::TransactionType,
        api_models::payments::FrmMessage,
        api_models::webhooks::OutgoingWebhook,
        api_models::webhooks::OutgoingWebhookContent,
        api_models::enums::EventClass,
        api_models::enums::EventType,
        api_models::enums::DecoupledAuthenticationType,
        api_models::enums::AuthenticationStatus,
        api_models::admin::MerchantAccountResponse,
        api_models::admin::MerchantConnectorId,
        api_models::admin::MerchantDetails,
        api_models::admin::ToggleKVRequest,
        api_models::admin::ToggleKVResponse,
        api_models::admin::WebhookDetails,
        api_models::api_keys::ApiKeyExpiration,
        api_models::api_keys::CreateApiKeyRequest,
        api_models::api_keys::CreateApiKeyResponse,
        api_models::api_keys::RetrieveApiKeyResponse,
        api_models::api_keys::RevokeApiKeyResponse,
        api_models::api_keys::UpdateApiKeyRequest,
        api_models::payments::RetrievePaymentLinkRequest,
        api_models::payments::PaymentLinkResponse,
        api_models::payments::RetrievePaymentLinkResponse,
        api_models::payments::PaymentLinkInitiateRequest,
        api_models::payouts::PayoutLinkInitiateRequest,
        api_models::payments::ExtendedCardInfoResponse,
        api_models::payments::GooglePayAssuranceDetails,
        api_models::routing::RoutingConfigRequest,
        api_models::routing::RoutingDictionaryRecord,
        api_models::routing::RoutingKind,
        api_models::routing::RoutableConnectorChoice,
        api_models::routing::DynamicRoutingFeatures,
        api_models::routing::SuccessBasedRoutingConfig,
        api_models::routing::DynamicRoutingConfigParams,
        api_models::routing::CurrentBlockThreshold,
        api_models::routing::SuccessBasedRoutingConfigBody,
        api_models::routing::ContractBasedRoutingConfig,
        api_models::routing::ContractBasedRoutingConfigBody,
        api_models::routing::LabelInformation,
        api_models::routing::ContractBasedTimeScale,
        api_models::routing::LinkedRoutingConfigRetrieveResponse,
        api_models::routing::RoutingRetrieveResponse,
        api_models::routing::ProfileDefaultRoutingConfig,
        api_models::routing::MerchantRoutingAlgorithm,
        api_models::routing::RoutingAlgorithmKind,
        api_models::routing::RoutingDictionary,
        api_models::routing::RoutingAlgorithmWrapper,
        api_models::routing::EliminationRoutingConfig,
        api_models::open_router::DecisionEngineEliminationData,
        api_models::routing::EliminationAnalyserConfig,
        api_models::routing::DynamicRoutingAlgorithm,
        api_models::routing::StaticRoutingAlgorithm,
        api_models::routing::StraightThroughAlgorithm,
        api_models::routing::ConnectorVolumeSplit,
        api_models::routing::ConnectorSelection,
        api_models::routing::SuccessRateSpecificityLevel,
        api_models::routing::ToggleDynamicRoutingQuery,
        api_models::routing::ToggleDynamicRoutingPath,
        api_models::routing::ProgramThreeDsDecisionRule,
        api_models::routing::RuleThreeDsDecisionRule,
        api_models::routing::RoutingVolumeSplitResponse,
        api_models::routing::ast::RoutableChoiceKind,
        api_models::enums::RoutableConnectors,
        api_models::routing::ast::ProgramConnectorSelection,
        api_models::routing::ast::RuleConnectorSelection,
        api_models::routing::ast::IfStatement,
        api_models::routing::ast::Comparison,
        api_models::routing::ast::ComparisonType,
        api_models::routing::ast::ValueType,
        api_models::routing::ast::MetadataValue,
        api_models::routing::ast::NumberComparison,
        api_models::payment_methods::RequestPaymentMethodTypes,
        api_models::payments::PaymentLinkStatus,
        api_models::blocklist::BlocklistRequest,
        api_models::blocklist::BlocklistResponse,
        api_models::blocklist::ToggleBlocklistResponse,
        api_models::blocklist::ListBlocklistQuery,
        api_models::enums::BlocklistDataKind,
        api_models::enums::ErrorCategory,
        api_models::webhook_events::EventListConstraints,
        api_models::webhook_events::EventListItemResponse,
        api_models::webhook_events::EventRetrieveResponse,
        api_models::webhook_events::OutgoingWebhookRequestContent,
        api_models::webhook_events::OutgoingWebhookResponseContent,
        api_models::webhook_events::TotalEventsResponse,
        api_models::enums::WebhookDeliveryAttempt,
        api_models::enums::PaymentChargeType,
        api_models::enums::StripeChargeType,
        api_models::payments::CustomerDetailsResponse,
        api_models::payments::SdkType,
        api_models::payments::OpenBankingData,
        api_models::payments::OpenBankingSessionToken,
        api_models::payments::BankDebitResponse,
        api_models::payments::BankRedirectResponse,
        api_models::payments::BankTransferResponse,
        api_models::payments::CardRedirectResponse,
        api_models::payments::CardTokenResponse,
        api_models::payments::CryptoResponse,
        api_models::payments::GiftCardResponse,
        api_models::payments::OpenBankingResponse,
        api_models::payments::RealTimePaymentDataResponse,
        api_models::payments::UpiResponse,


pub async fn get_merchant_auth_events_filters(
        state: web::Data<AppState>,
        req: actix_web::HttpRequest,
        json_payload: web::Json<GetAuthEventFilterRequest>,
    ) -> impl Responder {
        let flow = AnalyticsFlow::GetAuthEventFilters;
        Box::pin(api::server_wrap(
            flow,
            state,
            &req,
            json_payload.into_inner(),
            |state, auth: AuthenticationData, req, _| async move {
                let org_id = auth.merchant_account.get_org_id();
                let merchant_id = auth.merchant_account.get_id();

                let auth: AuthInfo = AuthInfo::MerchantLevel {
                    org_id: org_id.clone(),
                    merchant_ids: vec![merchant_id.clone()],
                };
                analytics::auth_events::get_filters(&state.pool, req, &auth)
                    .await
                    .map(ApplicationResponse::Json)
            },
            &auth::JWTAuth {
                permission: Permission::MerchantAnalyticsRead,
            },
            api_locking::LockAction::NotApplicable,
        ))
        .await
    }


pub fn is_sso_auth_type(auth_type: UserAuthType) -> bool {
    match auth_type {
        UserAuthType::OpenIdConnect => true,
        UserAuthType::Password | UserAuthType::MagicLink => false,
    }
}


Documentation: crates/drainer/README.md
# Type: Doc File

# Drainer

Application that reads Redis streams and executes queries in database.


impl Stop for ServerHandle {
    async fn stop_server(&mut self) {
        let _ = self.stop(true).await;
    }
}


File: crates/router_env/src/vergen.rs
 Public functions: 2

/// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions.
///
/// This function should be typically called within build scripts to generate `cargo` build
/// instructions for the corresponding crate.
///
/// # Panics
///
/// Panics if `vergen` fails to generate `cargo` build instructions.
#[cfg(feature = "vergen")]
#[allow(clippy::expect_used)]
pub fn generate_cargo_instructions() {
    use std::io::Write;

    use vergen::EmitBuilder;

    EmitBuilder::builder()
        .cargo_debug()
        .cargo_opt_level()
        .cargo_target_triple()
        .git_commit_timestamp()
        .git_describe(true, true, None)
        .git_sha(true)
        .rustc_semver()
        .rustc_commit_hash()
        .emit()
        .expect("Failed to generate `cargo` build instructions");

    writeln!(
        &mut std::io::stdout(),
        "cargo:rustc-env=CARGO_PROFILE={}",
        std::env::var("PROFILE").expect("Failed to obtain `cargo` profile")
    )
    .expect("Failed to set `CARGO_PROFILE` environment variable");
}

#[cfg(not(feature = "vergen"))]
pub fn generate_cargo_instructions() {}


Web Documentation: Alternate Payment Method Widgets | Hyperswitch
# Type: Web Doc

We support modular, embeddable alternate payment methods (APMs) known as
Hyperwidgets
, which a merchant can use to augment their existing checkout in a low code manner.
Let us understand with an example-
In the below checkout screen the merchant only has Cards and Paypal offered by their current PSP.
But, if the merchant decides to enable more alternate payment methods (APMs), the problems can be multifold:
Availability
- Current PSP may not support the desired alternate payment method requiring the merchant to do a direct integration or use a different PSP.
Complex to integrate
- In case a PSP supports a desired payment method, integrating it into the existing checkout is tedious and often requires high engineering effort. Hyperwidets offers a low code solution for such a scenario where a merchant can not only choose to have their preferred payment method through a wide range of connectors, but also integrate it with minimal engineering effort.
Complex to enhance
- Traditional PSPs and Middle layers ((Subscription provider’s SDK or Token provider’s SDK or Orchestration provider’s SDK)) offer separate integration for every new APM, requiring ongoing engineering effort for enhancements.
Hyperwidets offers a way for merchants to extend APMs from just “Apple Pay” to “Apple Pay + Google Pay” to “Apple Pay + Google Pay + Amazon Pay + 10 more” with the same integration and no additional engineering effort.
Hyperwidgets also offers merchants the flexibility to surface the right set of APMs in the widget based on the order context - Value, Region and more.
Integration overhead to enable more APMs on the same PSP
: Some PSPs require the merchant to do some additional integration steps to enable an APM. This can be time consuming and require significant tech bandwidth from the merchant. Examples can be when certain APMs are only available on new API versions of the PSP, certification from Apple/ Google is required to go-live for some wallet flows, adding a frontend library/ javascript to add certain APMs, and so on.
in the image below you can find a checkout page with more alternate payment methods via Hyperwidgets.
Additional example:
How is Hyperwidget engineered:
Hyperwidgets are engineered to simplify and streamline the integration of alternate payment methods (APMs) for merchants, regardless of their existing payment setup. The design focuses on providing a modular, embeddable, and low-code solution, reducing the engineering effort traditionally required to add or enhance payment options.
Single SDK to manage all APMs
Hyperwidgets come packaged in a single SDK that merchants can integrate into their web app and route some of their APM traffic to. The widget is powered through a javascript which resides in the merchant's top level domain. Thus, it acts as an extension of the merchant checkout and powerful enough to offer a range of payment methods from Express Checkout payment options (like Applepay, Paypal, etc.), wallets ( like Wechatpay, Alipay, etc.), BNPLs (like Klarna, Affirm, etc.) to Bank Debits and Transfers (like ACH, BACS, SEPA, etc.)
Seamless integration for all tech stacks
The Hyperwidget provides seamless integration for merchants using different frameworks for their web app. This is done using multiple wrappers like React, HTML, Angular, etc. This ensures a low-code, low-effort integration for the merchants.
Configuring PSPs is independent from integration
The Hyperwidget integration is a one time effort. To manage the different payment methods across business lines, geographies, etc. the merchant bears no additional overhead. Adding/ removing PSPs and routing the transaction through different PSPs is a dashboard configuration.
Modular fit with other integrations
Merchants can work with multiple PSPs or middle layers, such as subscription providers or orchestration SDKs, without any conflicts from Hyperwidgets. The Hyperwidgets integration fits seamlessly in their existing checkout flow and business logic. They just need to invoke and handle callbacks at the right triggers in their checkout flow.
High customization
The Hyperwidgets UI is highly customizable and can completely blend in with the merchant app. Using a customization object, merchants can very easily control the UI parameters like background color, corner radius of the buttons,font size, etc. to match their branding. Some of the examples to highlight the customization options of the checkout are -
Unified Analytics and order management
All the transactions that are processed through Hyperwidgets can be seen on a unified dashboard. The merchant can analyse data at a granular level to understand conversion across different payment methods, filter by customer id, transaction type (3DS, no-3DS), get a summary of failure reasons for failed transactions and much more. The unification is done across the PSPs/ Acquirers for each payment method.
Future ready design
The engineering ensures support for emerging payment methods and new PSPs without requiring additional engineering work, ensuring a scalable one-time only integration for the merchants.
Supported merchant setups :
Setup A
- Merchant is directly integrated with 1 PSP and is looking to enable APMs via same or a different PSP
Setup B
- Merchant is indirectly integrated with 1 PSP via a middle layer (Subscription provider’s SDK or Token provider’s SDK or Orchestration provider’s SDK). The merchant is looking to enable APMs via the same or different PSP
via PSP or middle layer
via Hyperwidgets
Existing APMs
Apple Pay -
2-3 weeks of engineering effort
Klarna -
2-3 weeks of engineering effort
New innovations
Paze -
Not available via most players
Click2Pay -
Not available via most player

One time effort of
2-weeks
to enable all existing APMs and new innovations via the same integration
Hyperwidget Integration Guide
18 days ago
Was this helpful?


impl ConnectorSpecifications for Authorizedotnet {
    fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
        Some(&AUTHORIZEDOTNET_CONNECTOR_INFO)
    }

    fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
        Some(&*AUTHORIZEDOTNET_SUPPORTED_PAYMENT_METHODS)
    }

    fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
        Some(&AUTHORIZEDOTNET_SUPPORTED_WEBHOOK_FLOWS)
    }
}

impl ConnectorSpecifications for for Authorizedotnet


pub async fn get_event_handler(&self) -> StorageResult<EventsHandler> {
        Ok(match self {
            Self::Kafka { kafka } => EventsHandler::Kafka(
                KafkaProducer::create(kafka)
                    .await
                    .change_context(StorageError::InitializationError)?,
            ),
            Self::Logs => EventsHandler::Logs(event_logger::EventLogger::default()),
        })
    }


pub struct PaystackPaymentWebhookData {
    pub status: PaystackPSyncStatus,
    pub reference: String,
}


File: crates/router/src/utils/user/dashboard_metadata.rs
 Public functions: 13

use std::{net::IpAddr, ops::Not, str::FromStr};

use actix_web::http::header::HeaderMap;
use api_models::user::dashboard_metadata::{
    GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest,
};
use common_utils::id_type;
use diesel_models::{
    enums::DashboardMetadata as DBEnum,
    user::dashboard_metadata::{DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate},
};
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::logger;

use crate::{
    core::errors::{UserErrors, UserResult},
    headers, SessionState,
};

pub async fn insert_merchant_scoped_metadata_to_db(
    state: &SessionState,
    user_id: String,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_key: DBEnum,
    metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
    let now = common_utils::date_time::now();
    let data_value = serde_json::to_value(metadata_value)
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Error Converting Struct To Serde Value")?;
    state
        .store
        .insert_metadata(DashboardMetadataNew {
            user_id: None,
            merchant_id,
            org_id,
            data_key: metadata_key,
            data_value: Secret::from(data_value),
            created_by: user_id.clone(),
            created_at: now,
            last_modified_by: user_id,
            last_modified_at: now,
        })
        .await
        .map_err(|e| {
            if e.current_context().is_db_unique_violation() {
                return e.change_context(UserErrors::MetadataAlreadySet);
            }
            e.change_context(UserErrors::InternalServerError)
        })
}
pub async fn insert_user_scoped_metadata_to_db(
    state: &SessionState,
    user_id: String,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_key: DBEnum,
    metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
    let now = common_utils::date_time::now();
    let data_value = serde_json::to_value(metadata_value)
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Error Converting Struct To Serde Value")?;
    state
        .store
        .insert_metadata(DashboardMetadataNew {
            user_id: Some(user_id.clone()),
            merchant_id,
            org_id,
            data_key: metadata_key,
            data_value: Secret::from(data_value),
            created_by: user_id.clone(),
            created_at: now,
            last_modified_by: user_id,
            last_modified_at: now,
        })
        .await
        .map_err(|e| {
            if e.current_context().is_db_unique_violation() {
                return e.change_context(UserErrors::MetadataAlreadySet);
            }
            e.change_context(UserErrors::InternalServerError)
        })
}

pub async fn get_merchant_scoped_metadata_from_db(
    state: &SessionState,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
    state
        .store
        .find_merchant_scoped_dashboard_metadata(&merchant_id, &org_id, metadata_keys)
        .await
        .change_context(UserErrors::InternalServerError)
        .attach_printable("DB Error Fetching DashboardMetaData")
}
pub async fn get_user_scoped_metadata_from_db(
    state: &SessionState,
    user_id: String,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
    match state
        .store
        .find_user_scoped_dashboard_metadata(&user_id, &merchant_id, &org_id, metadata_keys)
        .await
    {
        Ok(data) => Ok(data),
        Err(e) => {
            if e.current_context().is_db_not_found() {
                return Ok(Vec::with_capacity(0));
            }
            Err(e
                .change_context(UserErrors::InternalServerError)
                .attach_printable("DB Error Fetching DashboardMetaData"))
        }
    }
}

pub async fn update_merchant_scoped_metadata(
    state: &SessionState,
    user_id: String,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_key: DBEnum,
    metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
    let data_value = serde_json::to_value(metadata_value)
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Error Converting Struct To Serde Value")?;

    state
        .store
        .update_metadata(
            None,
            merchant_id,
            org_id,
            metadata_key,
            DashboardMetadataUpdate::UpdateData {
                data_key: metadata_key,
                data_value: Secret::from(data_value),
                last_modified_by: user_id,
            },
        )
        .await
        .change_context(UserErrors::InternalServerError)
}
pub async fn update_user_scoped_metadata(
    state: &SessionState,
    user_id: String,
    merchant_id: id_type::MerchantId,
    org_id: id_type::OrganizationId,
    metadata_key: DBEnum,
    metadata_value: impl serde::Serialize,
) -> UserResult<DashboardMetadata> {
    let data_value = serde_json::to_value(metadata_value)
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Error Converting Struct To Serde Value")?;

    state
        .store
        .update_metadata(
            Some(user_id.clone()),
            merchant_id,
            org_id,
            metadata_key,
            DashboardMetadataUpdate::UpdateData {
                data_key: metadata_key,
                data_value: Secret::from(data_value),
                last_modified_by: user_id,
            },
        )
        .await
        .change_context(UserErrors::InternalServerError)
}

pub fn deserialize_to_response<T>(data: Option<&DashboardMetadata>) -> UserResult<Option<T>>
where
    T: serde::de::DeserializeOwned,
{
    data.map(|metadata| serde_json::from_value(metadata.data_value.clone().expose()))
        .transpose()
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Error Serializing Metadata from DB")
}

pub fn separate_metadata_type_based_on_scope(
    metadata_keys: Vec<DBEnum>,
) -> (Vec<DBEnum>, Vec<DBEnum>) {
    let (mut merchant_scoped, mut user_scoped) = (
        Vec::with_capacity(metadata_keys.len()),
        Vec::with_capacity(metadata_keys.len()),
    );
    for key in metadata_keys {
        match key {
            DBEnum::ProductionAgreement
            | DBEnum::SetupProcessor
            | DBEnum::ConfigureEndpoint
            | DBEnum::SetupComplete
            | DBEnum::FirstProcessorConnected
            | DBEnum::SecondProcessorConnected
            | DBEnum::ConfiguredRouting
            | DBEnum::TestPayment
            | DBEnum::IntegrationMethod
            | DBEnum::ConfigurationType
            | DBEnum::IntegrationCompleted
            | DBEnum::StripeConnected
            | DBEnum::PaypalConnected
            | DBEnum::SpRoutingConfigured
            | DBEnum::SpTestPayment
            | DBEnum::DownloadWoocom
            | DBEnum::ConfigureWoocom
            | DBEnum::SetupWoocomWebhook
            | DBEnum::OnboardingSurvey
            | DBEnum::IsMultipleConfiguration
            | DBEnum::ReconStatus
            | DBEnum::ProdIntent => merchant_scoped.push(key),
            DBEnum::Feedback | DBEnum::IsChangePasswordRequired => user_scoped.push(key),
        }
    }
    (merchant_scoped, user_scoped)
}

pub fn is_update_required(metadata: &UserResult<DashboardMetadata>) -> bool {
    match metadata {
        Ok(_) => false,
        Err(e) => matches!(e.current_context(), UserErrors::MetadataAlreadySet),
    }
}

pub fn is_backfill_required(metadata_key: DBEnum) -> bool {
    matches!(
        metadata_key,
        DBEnum::StripeConnected | DBEnum::PaypalConnected
    )
}

pub fn set_ip_address_if_required(
    request: &mut SetMetaDataRequest,
    headers: &HeaderMap,
) -> UserResult<()> {
    if let SetMetaDataRequest::ProductionAgreement(req) = request {
        let ip_address_from_request: Secret<String, common_utils::pii::IpAddress> = headers
            .get(headers::X_FORWARDED_FOR)
            .ok_or(report!(UserErrors::IpAddressParsingFailed))
            .attach_printable("X-Forwarded-For header not found")?
            .to_str()
            .change_context(UserErrors::IpAddressParsingFailed)
            .attach_printable("Error converting Header Value to Str")?
            .split(',')
            .next()
            .and_then(|ip| {
                let ip_addr: Result<IpAddr, _> = ip.parse();
                ip_addr.ok()
            })
            .ok_or(report!(UserErrors::IpAddressParsingFailed))
            .attach_printable("Error Parsing header value to ip")?
            .to_string()
            .into();
        req.ip_address = Some(ip_address_from_request)
    }
    Ok(())
}

pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPayload> {
    Ok(GetMultipleMetaDataPayload {
        results: query
            .split(',')
            .map(GetMetaDataRequest::from_str)
            .collect::<Result<Vec<GetMetaDataRequest>, _>>()
            .change_context(UserErrors::InvalidMetadataRequest)
            .attach_printable("Error Parsing to DashboardMetadata enums")?,
    })
}

fn not_contains_string(value: Option<&str>, value_to_be_checked: &str) -> bool {
    value.is_some_and(|mail| !mail.contains(value_to_be_checked))
}

pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {
    let poc_email_check = not_contains_string(
        data.poc_email.as_ref().map(|email| email.peek().as_str()),
        "juspay",
    );
    let business_website_check = not_contains_string(data.business_website.as_deref(), "juspay")
        && not_contains_string(data.business_website.as_deref(), "hyperswitch");
    let user_email_check = not_contains_string(Some(&user_email), "juspay");

    if (poc_email_check && business_website_check && user_email_check).not() {
        logger::info!(prod_intent_email = poc_email_check);
        logger::info!(prod_intent_email = business_website_check);
        logger::info!(prod_intent_email = user_email_check);
    }

    poc_email_check && business_website_check && user_email_check
}