impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
    for ClickhouseClient
{
}

impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
    for for ClickhouseClient


pub struct SquareCardData {
    cvv: Secret<String>,
    exp_month: Secret<u16>,
    exp_year: Secret<u16>,
    number: cards::CardNumber,
}


File: crates/hyperswitch_connectors/src/connectors/gocardless.rs
 Public functions: 1
 Public structs: 1

pub mod transformers;

use std::sync::LazyLock;

use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
    crypto,
    errors::CustomResult,
    ext_traits::{ByteSliceExt, BytesExt},
    request::{Method, Request, RequestBuilder, RequestContent},
    types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
    payment_method_data::PaymentMethodData,
    router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
    router_flow_types::{
        access_token_auth::AccessTokenAuth,
        payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
        refunds::{Execute, RSync},
        CreateConnectorCustomer, PreProcessing,
    },
    router_request_types::{
        AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
        PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
        PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
    },
    router_response_types::{
        ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
        SupportedPaymentMethods, SupportedPaymentMethodsExt,
    },
    types::{
        ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData,
        RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData,
    },
};
use hyperswitch_interfaces::{
    api::{
        self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
        ConnectorValidation,
    },
    configs::Connectors,
    errors,
    events::connector_api_logs::ConnectorEvent,
    types::{self, PaymentsSyncType, Response},
    webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as gocardless;

use crate::{
    constants::headers,
    types::ResponseRouterData,
    utils::{self, is_mandate_supported, PaymentMethodDataType},
};

#[derive(Clone)]
pub struct Gocardless {
    amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}

impl Gocardless {
    pub fn new() -> &'static Self {
        &Self {
            amount_converter: &MinorUnitForConnector,
        }
    }
}

impl api::Payment for Gocardless {}
impl api::PaymentSession for Gocardless {}
impl api::ConnectorAccessToken for Gocardless {}
impl api::MandateSetup for Gocardless {}
impl api::PaymentAuthorize for Gocardless {}
impl api::PaymentSync for Gocardless {}
impl api::PaymentCapture for Gocardless {}
impl api::PaymentVoid for Gocardless {}
impl api::Refund for Gocardless {}
impl api::RefundExecute for Gocardless {}
impl api::RefundSync for Gocardless {}
impl api::PaymentToken for Gocardless {}
impl api::ConnectorCustomer for Gocardless {}
impl api::PaymentsPreProcessing for Gocardless {}

const GOCARDLESS_VERSION: &str = "2015-07-06";
const GOCARDLESS_VERSION_HEADER: &str = "GoCardless-Version";

impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gocardless
where
    Self: ConnectorIntegration<Flow, Request, Response>,
{
    fn build_headers(
        &self,
        req: &RouterData<Flow, Request, Response>,
        _connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        let mut header = vec![
            (
                headers::CONTENT_TYPE.to_string(),
                self.get_content_type().to_string().into(),
            ),
            (
                GOCARDLESS_VERSION_HEADER.to_string(),
                GOCARDLESS_VERSION.to_string().into(),
            ),
        ];
        let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
        header.append(&mut api_key);
        Ok(header)
    }
}

impl ConnectorCommon for Gocardless {
    fn id(&self) -> &'static str {
        "gocardless"
    }

    fn get_currency_unit(&self) -> api::CurrencyUnit {
        api::CurrencyUnit::Minor
    }

    fn common_get_content_type(&self) -> &'static str {
        "application/json"
    }

    fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
        connectors.gocardless.base_url.as_ref()
    }

    fn get_auth_header(
        &self,
        auth_type: &ConnectorAuthType,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        let auth = gocardless::GocardlessAuthType::try_from(auth_type)
            .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
        Ok(vec![(
            headers::AUTHORIZATION.to_string(),
            format!("Bearer {}", auth.access_token.peek()).into_masked(),
        )])
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        let response: gocardless::GocardlessErrorResponse = res
            .response
            .parse_struct("GocardlessErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_error_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        let error_iter = response.error.errors.iter();
        let mut error_reason: Vec<String> = Vec::new();
        for error in error_iter {
            let reason = error.field.clone().map_or(error.message.clone(), |field| {
                format!("{} {}", field, error.message)
            });
            error_reason.push(reason)
        }
        Ok(ErrorResponse {
            status_code: res.status_code,
            code: response.error.code.to_string(),
            message: response.error.error_type,
            reason: Some(error_reason.join("; ")),
            attempt_status: None,
            connector_transaction_id: None,
            network_advice_code: None,
            network_decline_code: None,
            network_error_message: None,
            connector_metadata: None,
        })
    }
}

impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
    for Gocardless
{
    fn get_headers(
        &self,
        req: &ConnectorCustomerRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_url(
        &self,
        _req: &ConnectorCustomerRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/customers", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &ConnectorCustomerRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req = gocardless::GocardlessCustomerRequest::try_from(req)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &ConnectorCustomerRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::ConnectorCustomerType::get_url(
                    self, req, connectors,
                )?)
                .attach_default_headers()
                .headers(types::ConnectorCustomerType::get_headers(
                    self, req, connectors,
                )?)
                .set_body(types::ConnectorCustomerType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &ConnectorCustomerRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<
        RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
        errors::ConnectorError,
    >
    where
        CreateConnectorCustomer: Clone,
        ConnectorCustomerData: Clone,
        PaymentsResponseData: Clone,
    {
        let response: gocardless::GocardlessCustomerResponse = res
            .response
            .parse_struct("GocardlessCustomerResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
    for Gocardless
{
    fn get_headers(
        &self,
        req: &TokenizationRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_url(
        &self,
        _req: &TokenizationRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!(
            "{}/customer_bank_accounts",
            self.base_url(connectors),
        ))
    }

    fn get_request_body(
        &self,
        req: &TokenizationRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req = gocardless::GocardlessBankAccountRequest::try_from(req)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &TokenizationRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::TokenizationType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(types::TokenizationType::get_headers(self, req, connectors)?)
                .set_body(types::TokenizationType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &TokenizationRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
    where
        PaymentMethodToken: Clone,
        PaymentMethodTokenizationData: Clone,
        PaymentsResponseData: Clone,
    {
        let response: gocardless::GocardlessBankAccountResponse = res
            .response
            .parse_struct("GocardlessBankAccountResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
    for Gocardless
{
}

impl ConnectorValidation for Gocardless {
    fn validate_mandate_payment(
        &self,
        pm_type: Option<enums::PaymentMethodType>,
        pm_data: PaymentMethodData,
    ) -> CustomResult<(), errors::ConnectorError> {
        let mandate_supported_pmd = std::collections::HashSet::from([
            PaymentMethodDataType::SepaBankDebit,
            PaymentMethodDataType::AchBankDebit,
            PaymentMethodDataType::BecsBankDebit,
            PaymentMethodDataType::BacsBankDebit,
        ]);
        is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
    }
}

impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gocardless {
    //TODO: implement sessions flow
}

impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gocardless {}

impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
    for Gocardless
{
    fn get_headers(
        &self,
        req: &SetupMandateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_url(
        &self,
        _req: &SetupMandateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/mandates", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &SetupMandateRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let connector_req = gocardless::GocardlessMandateRequest::try_from(req)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &SetupMandateRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        // Preprocessing flow is to create mandate, which should to be called only in case of First mandate
        if req.request.setup_mandate_details.is_some() {
            Ok(Some(
                RequestBuilder::new()
                    .method(Method::Post)
                    .url(&types::SetupMandateType::get_url(self, req, connectors)?)
                    .attach_default_headers()
                    .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
                    .set_body(types::SetupMandateType::get_request_body(
                        self, req, connectors,
                    )?)
                    .build(),
            ))
        } else {
            Ok(None)
        }
    }

    fn handle_response(
        &self,
        data: &SetupMandateRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
        let response: gocardless::GocardlessMandateResponse = res
            .response
            .parse_struct("GocardlessMandateResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gocardless {
    fn get_headers(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        _req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/payments", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &PaymentsAuthorizeRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_amount,
            req.request.currency,
        )?;

        let connector_router_data = gocardless::GocardlessRouterData::from((amount, req));
        let connector_req =
            gocardless::GocardlessPaymentsRequest::try_from(&connector_router_data)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &PaymentsAuthorizeRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Post)
                .url(&types::PaymentsAuthorizeType::get_url(
                    self, req, connectors,
                )?)
                .attach_default_headers()
                .headers(types::PaymentsAuthorizeType::get_headers(
                    self, req, connectors,
                )?)
                .set_body(types::PaymentsAuthorizeType::get_request_body(
                    self, req, connectors,
                )?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsAuthorizeRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
        let response: gocardless::GocardlessPaymentsResponse = res
            .response
            .parse_struct("GocardlessPaymentsResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Gocardless {
    fn get_headers(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!(
            "{}/payments/{}",
            self.base_url(connectors),
            req.request
                .connector_transaction_id
                .get_connector_transaction_id()
                .change_context(errors::ConnectorError::MissingConnectorTransactionID)?
        ))
    }

    fn build_request(
        &self,
        req: &PaymentsSyncRouterData,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(Some(
            RequestBuilder::new()
                .method(Method::Get)
                .url(&PaymentsSyncType::get_url(self, req, connectors)?)
                .attach_default_headers()
                .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
                .build(),
        ))
    }

    fn handle_response(
        &self,
        data: &PaymentsSyncRouterData,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
        let response: gocardless::GocardlessPaymentsResponse = res
            .response
            .parse_struct("GocardlessPaymentsResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Gocardless {}

impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Gocardless {}

impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gocardless {
    fn get_headers(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
        self.build_headers(req, connectors)
    }

    fn get_content_type(&self) -> &'static str {
        self.common_get_content_type()
    }

    fn get_url(
        &self,
        _req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<String, errors::ConnectorError> {
        Ok(format!("{}/refunds", self.base_url(connectors)))
    }

    fn get_request_body(
        &self,
        req: &RefundsRouterData<Execute>,
        _connectors: &Connectors,
    ) -> CustomResult<RequestContent, errors::ConnectorError> {
        let refund_amount = utils::convert_amount(
            self.amount_converter,
            req.request.minor_refund_amount,
            req.request.currency,
        )?;

        let connector_router_data = gocardless::GocardlessRouterData::from((refund_amount, req));

        let connector_req = gocardless::GocardlessRefundRequest::try_from(&connector_router_data)?;
        Ok(RequestContent::Json(Box::new(connector_req)))
    }

    fn build_request(
        &self,
        req: &RefundsRouterData<Execute>,
        connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        let request = RequestBuilder::new()
            .method(Method::Post)
            .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
            .attach_default_headers()
            .headers(types::RefundExecuteType::get_headers(
                self, req, connectors,
            )?)
            .set_body(types::RefundExecuteType::get_request_body(
                self, req, connectors,
            )?)
            .build();
        Ok(Some(request))
    }

    fn handle_response(
        &self,
        data: &RefundsRouterData<Execute>,
        event_builder: Option<&mut ConnectorEvent>,
        res: Response,
    ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
        let response: gocardless::RefundResponse = res
            .response
            .parse_struct("gocardless RefundResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        RouterData::try_from(ResponseRouterData {
            response,
            data: data.clone(),
            http_code: res.status_code,
        })
    }

    fn get_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        self.build_error_response(res, event_builder)
    }
}

impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gocardless {
    fn build_request(
        &self,
        _req: &RefundSyncRouterData,
        _connectors: &Connectors,
    ) -> CustomResult<Option<Request>, errors::ConnectorError> {
        Ok(None)
    }
}

#[async_trait::async_trait]
impl IncomingWebhook for Gocardless {
    fn get_webhook_source_verification_algorithm(
        &self,
        _request: &IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
        Ok(Box::new(crypto::HmacSha256))
    }

    fn get_webhook_source_verification_signature(
        &self,
        request: &IncomingWebhookRequestDetails<'_>,
        _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        let signature = request
            .headers
            .get("Webhook-Signature")
            .map(|header_value| {
                header_value
                    .to_str()
                    .map(String::from)
                    .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
            })
            .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??;

        hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
    }

    fn get_webhook_source_verification_message(
        &self,
        request: &IncomingWebhookRequestDetails<'_>,
        _merchant_id: &common_utils::id_type::MerchantId,
        _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
    ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
        Ok(format!("{}", String::from_utf8_lossy(request.body))
            .as_bytes()
            .to_vec())
    }

    fn get_webhook_object_reference_id(
        &self,
        request: &IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
        let details: gocardless::GocardlessWebhookEvent = request
            .body
            .parse_struct("GocardlessWebhookEvent")
            .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
        let first_event = details
            .events
            .first()
            .ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
        let reference_id = match &first_event.links {
            transformers::WebhooksLink::PaymentWebhooksLink(link) => {
                let payment_id = api_models::payments::PaymentIdType::ConnectorTransactionId(
                    link.payment.to_owned(),
                );
                ObjectReferenceId::PaymentId(payment_id)
            }
            transformers::WebhooksLink::RefundWebhookLink(link) => {
                let refund_id =
                    api_models::webhooks::RefundIdType::ConnectorRefundId(link.refund.to_owned());
                ObjectReferenceId::RefundId(refund_id)
            }
            transformers::WebhooksLink::MandateWebhookLink(link) => {
                let mandate_id = api_models::webhooks::MandateIdType::ConnectorMandateId(
                    link.mandate.to_owned(),
                );
                ObjectReferenceId::MandateId(mandate_id)
            }
        };
        Ok(reference_id)
    }

    fn get_webhook_event_type(
        &self,
        request: &IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
        let details: gocardless::GocardlessWebhookEvent = request
            .body
            .parse_struct("GocardlessWebhookEvent")
            .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
        let first_event = details
            .events
            .first()
            .ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?;
        let event_type = match &first_event.action {
            transformers::WebhookAction::PaymentsAction(action) => match action {
                transformers::PaymentsAction::Created
                | transformers::PaymentsAction::Submitted
                | transformers::PaymentsAction::CustomerApprovalGranted => {
                    IncomingWebhookEvent::PaymentIntentProcessing
                }
                transformers::PaymentsAction::CustomerApprovalDenied
                | transformers::PaymentsAction::Failed
                | transformers::PaymentsAction::Cancelled
                | transformers::PaymentsAction::LateFailureSettled => {
                    IncomingWebhookEvent::PaymentIntentFailure
                }
                transformers::PaymentsAction::Confirmed | transformers::PaymentsAction::PaidOut => {
                    IncomingWebhookEvent::PaymentIntentSuccess
                }
                transformers::PaymentsAction::SurchargeFeeDebited
                | transformers::PaymentsAction::ResubmissionRequired => {
                    IncomingWebhookEvent::EventNotSupported
                }
            },
            transformers::WebhookAction::RefundsAction(action) => match action {
                transformers::RefundsAction::Failed => IncomingWebhookEvent::RefundFailure,
                transformers::RefundsAction::Paid => IncomingWebhookEvent::RefundSuccess,
                transformers::RefundsAction::RefundSettled
                | transformers::RefundsAction::FundsReturned
                | transformers::RefundsAction::Created => IncomingWebhookEvent::EventNotSupported,
            },
            transformers::WebhookAction::MandatesAction(action) => match action {
                transformers::MandatesAction::Active | transformers::MandatesAction::Reinstated => {
                    IncomingWebhookEvent::MandateActive
                }
                transformers::MandatesAction::Expired
                | transformers::MandatesAction::Cancelled
                | transformers::MandatesAction::Failed
                | transformers::MandatesAction::Consumed => IncomingWebhookEvent::MandateRevoked,
                transformers::MandatesAction::Created
                | transformers::MandatesAction::CustomerApprovalGranted
                | transformers::MandatesAction::CustomerApprovalSkipped
                | transformers::MandatesAction::Transferred
                | transformers::MandatesAction::Submitted
                | transformers::MandatesAction::ResubmissionRequested
                | transformers::MandatesAction::Replaced
                | transformers::MandatesAction::Blocked => IncomingWebhookEvent::EventNotSupported,
            },
        };
        Ok(event_type)
    }

    fn get_webhook_resource_object(
        &self,
        request: &IncomingWebhookRequestDetails<'_>,
    ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
        let details: gocardless::GocardlessWebhookEvent = request
            .body
            .parse_struct("GocardlessWebhookEvent")
            .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
        let first_event = details
            .events
            .first()
            .ok_or_else(|| errors::ConnectorError::WebhookReferenceIdNotFound)?
            .clone();
        match first_event.resource_type {
            transformers::WebhookResourceType::Payments => Ok(Box::new(
                gocardless::GocardlessPaymentsResponse::try_from(&first_event)?,
            )),
            transformers::WebhookResourceType::Refunds
            | transformers::WebhookResourceType::Mandates => Ok(Box::new(first_event)),
        }
    }
}

static GOCARDLESS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
    LazyLock::new(|| {
        let supported_capture_methods = vec![
            enums::CaptureMethod::Automatic,
            enums::CaptureMethod::SequentialAutomatic,
        ];

        let mut gocardless_supported_payment_methods = SupportedPaymentMethods::new();

        gocardless_supported_payment_methods.add(
            enums::PaymentMethod::BankDebit,
            enums::PaymentMethodType::Ach,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::Supported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods: supported_capture_methods.clone(),
                specific_features: None,
            },
        );

        gocardless_supported_payment_methods.add(
            enums::PaymentMethod::BankDebit,
            enums::PaymentMethodType::Becs,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::Supported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods: supported_capture_methods.clone(),
                specific_features: None,
            },
        );

        gocardless_supported_payment_methods.add(
            enums::PaymentMethod::BankDebit,
            enums::PaymentMethodType::Sepa,
            PaymentMethodDetails {
                mandates: common_enums::FeatureStatus::Supported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods: supported_capture_methods.clone(),
                specific_features: None,
            },
        );

        gocardless_supported_payment_methods
    });

static GOCARDLESS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
    display_name: "GoCardless",
    description: "GoCardless is a fintech company that specialises in bank payments including recurring payments.",
    connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
    integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};

static GOCARDLESS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
    enums::EventClass::Payments,
    enums::EventClass::Refunds,
    enums::EventClass::Mandates,
];

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

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

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


Documentation: api-reference/v2/api-key/api-key--retrieve.mdx
# Type: Doc File

---
openapi: get /v2/api-keys/{id}
---


pub struct NetworkTokenData {
    pub token_number: cards::CardNumber,
    pub token_exp_month: Secret<String>,
    pub token_exp_year: Secret<String>,
    pub token_cryptogram: Option<Secret<String>>,
    pub card_issuer: Option<String>,
    pub card_network: Option<common_enums::CardNetwork>,
    pub card_type: Option<String>,
    pub card_issuing_country: Option<String>,
    pub bank_code: Option<String>,
    pub nick_name: Option<Secret<String>>,
    pub eci: Option<String>,
}


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


impl super::payments::distribution::PaymentDistributionAnalytics for ClickhouseClient {}

impl super::payments::distribution::PaymentDistributionAnalytics for for ClickhouseClient


impl FileStorageConfig {
    /// Validates the file storage configuration.
    pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
        match self {
            #[cfg(feature = "aws_s3")]
            Self::AwsS3 { aws_s3 } => aws_s3.validate(),
            Self::FileSystem => Ok(()),
        }
    }

    /// Retrieves the appropriate file storage client based on the file storage configuration.
    pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> {
        match self {
            #[cfg(feature = "aws_s3")]
            Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),
            Self::FileSystem => Arc::new(file_system::FileSystem),
        }
    }
}


File: crates/api_models/src/events/gsm.rs

use common_utils::events::{ApiEventMetric, ApiEventsType};

use crate::gsm;

impl ApiEventMetric for gsm::GsmCreateRequest {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}

impl ApiEventMetric for gsm::GsmUpdateRequest {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}

impl ApiEventMetric for gsm::GsmRetrieveRequest {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}

impl ApiEventMetric for gsm::GsmDeleteRequest {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}

impl ApiEventMetric for gsm::GsmDeleteResponse {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}

impl ApiEventMetric for gsm::GsmResponse {
    fn get_api_event_type(&self) -> Option<ApiEventsType> {
        Some(ApiEventsType::Gsm)
    }
}


pub struct Link {
    href: Url,
    #[serde(rename = "type")]
    type_: String,
}


pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>(
    operation: &Op,
    payment_data: &D,
    debit_routing_config: &settings::DebitRoutingConfig,
) -> bool
where
    D: OperationSessionGetters<F> + Send + Sync + Clone,
{
    match format!("{operation:?}").as_str() {
        "PaymentConfirm" => {
            logger::info!("Checking if debit routing is required");

            request_validation(payment_data, debit_routing_config)
        }
        _ => false,
    }
}


pub async fn do_retry<F, ApiRequest, FData, D>(
    state: &routes::SessionState,
    req_state: ReqState,
    connector: &api::ConnectorData,
    operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,
    customer: &Option<domain::Customer>,
    merchant_context: &domain::MerchantContext,
    payment_data: &mut D,
    router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
    validate_result: &operations::ValidateResult,
    schedule_time: Option<time::PrimitiveDateTime>,
    is_step_up: bool,
    frm_suggestion: Option<storage_enums::FrmSuggestion>,
    business_profile: &domain::Profile,
    should_retry_with_pan: bool,
    routing_decision: Option<routing_helpers::RoutingDecisionData>,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
    F: Clone + Send + Sync,
    FData: Send + Sync + types::Capturable,
    payments::PaymentResponse: operations::Operation<F, FData>,
    D: payments::OperationSessionGetters<F>
        + payments::OperationSessionSetters<F>
        + Send
        + Sync
        + Clone,
    D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
    types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
    dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
    metrics::AUTO_RETRY_PAYMENT_COUNT.add(1, &[]);

    modify_trackers(
        state,
        connector.connector_name.to_string(),
        payment_data,
        merchant_context.get_merchant_key_store(),
        merchant_context.get_merchant_account().storage_scheme,
        router_data,
        is_step_up,
    )
    .await?;

    let (merchant_connector_account, router_data, tokenization_action) =
        payments::call_connector_service_prerequisites(
            state,
            merchant_context,
            connector.clone(),
            operation,
            payment_data,
            customer,
            validate_result,
            business_profile,
            should_retry_with_pan,
            routing_decision,
        )
        .await?;

    let (router_data, _mca) = payments::decide_unified_connector_service_call(
        state,
        req_state,
        merchant_context,
        connector.clone(),
        operation,
        payment_data,
        customer,
        payments::CallConnectorAction::Trigger,
        validate_result,
        schedule_time,
        hyperswitch_domain_models::payments::HeaderPayload::default(),
        frm_suggestion,
        business_profile,
        true,
        None,
        merchant_connector_account,
        router_data,
        tokenization_action,
    )
    .await?;

    Ok(router_data)
}


/// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
    pub async fn get_merchant_api_events_metrics(
        state: web::Data<AppState>,
        req: actix_web::HttpRequest,
        json_payload: web::Json<[GetApiEventMetricRequest; 1]>,
    ) -> impl Responder {
        // safety: This shouldn't panic owing to the data type
        #[allow(clippy::expect_used)]
        let payload = json_payload
            .into_inner()
            .to_vec()
            .pop()
            .expect("Couldn't get GetApiEventMetricRequest");
        let flow = AnalyticsFlow::GetApiEventMetrics;
        Box::pin(api::server_wrap(
            flow,
            state.clone(),
            &req,
            payload,
            |state, auth: AuthenticationData, req, _| async move {
                analytics::api_event::get_api_event_metrics(
                    &state.pool,
                    auth.merchant_account.get_id(),
                    req,
                )
                .await
                .map(ApplicationResponse::Json)
            },
            &auth::JWTAuth {
                permission: Permission::MerchantAnalyticsRead,
            },
            api_locking::LockAction::NotApplicable,
        ))
        .await
    }


pub struct NexixpayErrorBody {
    pub code: Option<String>,
    pub description: Option<String>,
}


pub struct PayloadCaptureRequest {
    pub status: responses::PayloadPaymentStatus,
}


            .service(web::resource("/filter").route(web::get().to(disputes::get_disputes_filters)))
            .service(
                web::resource("/profile/filter")
                    .route(web::get().to(disputes::get_disputes_filters_profile)),
            )
            .service(
                web::resource("/accept/{dispute_id}")
                    .route(web::post().to(disputes::accept_dispute)),
            )
            .service(
                web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)),
            )
            .service(
                web::resource("/profile/aggregate")
                    .route(web::get().to(disputes::get_disputes_aggregate_profile)),
            )
            .service(
                web::resource("/evidence")
                    .route(web::post().to(disputes::submit_dispute_evidence))
                    .route(web::put().to(disputes::attach_dispute_evidence))
                    .route(web::delete().to(disputes::delete_dispute_evidence)),
            )
            .service(
                web::resource("/evidence/{dispute_id}")
                    .route(web::get().to(disputes::retrieve_dispute_evidence)),
            )
            .service(
                web::resource("/{dispute_id}").route(web::get().to(disputes::retrieve_dispute)),
            )
            .service(
                web::resource("/{connector_id}/fetch")
                    .route(web::get().to(disputes::fetch_disputes)),
            )
    }
}

pub struct Cards;

#[cfg(all(feature = "oltp", feature = "v1"))]
impl Cards {
    pub fn server(state: AppState) -> Scope {
        web::scope("/cards")
            .app_data(web::Data::new(state))
            .service(web::resource("/create").route(web::post().to(create_cards_info)))
            .service(web::resource("/update").route(web::post().to(update_cards_info)))
            .service(web::resource("/update-batch").route(web::post().to(migrate_cards_info)))
            .service(web::resource("/{bin}").route(web::get().to(card_iin_info)))
    }
}

pub struct Files;

#[cfg(all(feature = "olap", feature = "v1"))]
impl Files {
    pub fn server(state: AppState) -> Scope {
        web::scope("/files")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::post().to(files::files_create)))
            .service(
                web::resource("/{file_id}")
                    .route(web::delete().to(files::files_delete))
                    .route(web::get().to(files::files_retrieve)),
            )
    }
}

pub struct Cache;

impl Cache {
    pub fn server(state: AppState) -> Scope {
        web::scope("/cache")
            .app_data(web::Data::new(state))
            .service(web::resource("/invalidate/{key}").route(web::post().to(invalidate)))
    }
}

pub struct PaymentLink;

#[cfg(all(feature = "olap", feature = "v1"))]
impl PaymentLink {
    pub fn server(state: AppState) -> Scope {
        web::scope("/payment_link")
            .app_data(web::Data::new(state))
            .service(web::resource("/list").route(web::post().to(payment_link::payments_link_list)))
            .service(
                web::resource("/{payment_link_id}")
                    .route(web::get().to(payment_link::payment_link_retrieve)),
            )
            .service(
                web::resource("{merchant_id}/{payment_id}")
                    .route(web::get().to(payment_link::initiate_payment_link)),
            )
            .service(
                web::resource("s/{merchant_id}/{payment_id}")
                    .route(web::get().to(payment_link::initiate_secure_payment_link)),
            )
            .service(
                web::resource("status/{merchant_id}/{payment_id}")
                    .route(web::get().to(payment_link::payment_link_status)),
            )
    }
}

#[cfg(feature = "payouts")]
pub struct PayoutLink;

#[cfg(all(feature = "payouts", feature = "v1"))]
impl PayoutLink {
    pub fn server(state: AppState) -> Scope {
        let mut route = web::scope("/payout_link").app_data(web::Data::new(state));
        route = route.service(
            web::resource("/{merchant_id}/{payout_id}").route(web::get().to(render_payout_link)),
        );
        route
    }
}
pub struct Profile;
#[cfg(all(feature = "olap", feature = "v2"))]
impl Profile {
    pub fn server(state: AppState) -> Scope {
        web::scope("/v2/profiles")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::post().to(profiles::profile_create)))
            .service(
                web::scope("/{profile_id}")
                    .service(
                        web::resource("")
                            .route(web::get().to(profiles::profile_retrieve))
                            .route(web::put().to(profiles::profile_update)),
                    )
                    .service(
                        web::resource("/connector-accounts")
                            .route(web::get().to(admin::connector_list)),
                    )
                    .service(
                        web::resource("/fallback-routing")
                            .route(web::get().to(routing::routing_retrieve_default_config))
                            .route(web::patch().to(routing::routing_update_default_config)),
                    )
                    .service(
                        web::resource("/activate-routing-algorithm").route(web::patch().to(
                            |state, req, path, payload| {
                                routing::routing_link_config(
                                    state,
                                    req,
                                    path,
                                    payload,
                                    &TransactionType::Payment,
                                )
                            },
                        )),
                    )
                    .service(
                        web::resource("/deactivate-routing-algorithm").route(web::patch().to(
                            |state, req, path| {
                                routing::routing_unlink_config(
                                    state,
                                    req,
                                    path,
                                    &TransactionType::Payment,
                                )
                            },
                        )),
                    )
                    .service(web::resource("/routing-algorithm").route(web::get().to(
                        |state, req, query_params, path| {
                            routing::routing_retrieve_linked_config(
                                state,
                                req,
                                query_params,
                                path,
                                &TransactionType::Payment,
                            )
                        },
                    )))
                    .service(
                        web::resource("/decision")
                            .route(web::put().to(routing::upsert_decision_manager_config))
                            .route(web::get().to(routing::retrieve_decision_manager_config)),
                    ),
            )
    }
}
#[cfg(all(feature = "olap", feature = "v1"))]
impl Profile {
    pub fn server(state: AppState) -> Scope {
        let mut route = web::scope("/account/{account_id}/business_profile")
            .app_data(web::Data::new(state))
            .service(
                web::resource("")
                    .route(web::post().to(profiles::profile_create))
                    .route(web::get().to(profiles::profiles_list)),
            );

        #[cfg(feature = "dynamic_routing")]
        {
            route = route.service(
                web::scope("/{profile_id}/dynamic_routing")
                    .service(
                        web::scope("/success_based")
                            .service(
                                web::resource("/toggle")
                                    .route(web::post().to(routing::toggle_success_based_routing)),
                            )
                            .service(
                                web::resource("/create")
                                    .route(web::post().to(routing::create_success_based_routing)),
                            )
                            .service(web::resource("/config/{algorithm_id}").route(
                                web::patch().to(|state, req, path, payload| {
                                    routing::success_based_routing_update_configs(
                                        state, req, path, payload,
                                    )
                                }),
                            )),
                    )
                    .service(
                        web::resource("/set_volume_split")
                            .route(web::post().to(routing::set_dynamic_routing_volume_split)),
                    )
                    .service(
                        web::resource("/get_volume_split")
                            .route(web::get().to(routing::get_dynamic_routing_volume_split)),
                    )
                    .service(
                        web::scope("/elimination")
                            .service(
                                web::resource("/toggle")
                                    .route(web::post().to(routing::toggle_elimination_routing)),
                            )
                            .service(
                                web::resource("/create")
                                    .route(web::post().to(routing::create_elimination_routing)),
                            )
                            .service(web::resource("config/{algorithm_id}").route(
                                web::patch().to(|state, req, path, payload| {
                                    routing::elimination_routing_update_configs(
                                        state, req, path, payload,
                                    )
                                }),
                            )),
                    )
                    .service(
                        web::scope("/contracts")
                            .service(web::resource("/toggle").route(
                                web::post().to(routing::contract_based_routing_setup_config),
                            ))
                            .service(web::resource("/config/{algorithm_id}").route(
                                web::patch().to(|state, req, path, payload| {
                                    routing::contract_based_routing_update_configs(
                                        state, req, path, payload,
                                    )
                                }),
                            )),
                    ),
            );
        }

        route = route.service(
            web::scope("/{profile_id}")
                .service(
                    web::resource("")
                        .route(web::get().to(profiles::profile_retrieve))
                        .route(web::post().to(profiles::profile_update))
                        .route(web::delete().to(profiles::profile_delete)),
                )
                .service(
                    web::resource("/toggle_extended_card_info")
                        .route(web::post().to(profiles::toggle_extended_card_info)),
                )
                .service(
                    web::resource("/toggle_connector_agnostic_mit")
                        .route(web::post().to(profiles::toggle_connector_agnostic_mit)),
                ),
        );

        route
    }
}

pub struct ProfileNew;

#[cfg(feature = "olap")]
impl ProfileNew {
    #[cfg(feature = "v1")]
    pub fn server(state: AppState) -> Scope {
        web::scope("/account/{account_id}/profile")
            .app_data(web::Data::new(state))
            .service(
                web::resource("").route(web::get().to(profiles::profiles_list_at_profile_level)),
            )
            .service(
                web::resource("/connectors").route(web::get().to(admin::connector_list_profile)),
            )
    }
    #[cfg(feature = "v2")]
    pub fn server(state: AppState) -> Scope {
        web::scope("/account/{account_id}/profile").app_data(web::Data::new(state))
    }
}

pub struct Gsm;

#[cfg(all(feature = "v1", feature = "olap"))]
impl Gsm {
    pub fn server(state: AppState) -> Scope {
        web::scope("/gsm")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::post().to(gsm::create_gsm_rule)))
            .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule)))
            .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule)))
            .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule)))
    }
}

#[cfg(all(feature = "v2", feature = "olap"))]
impl Gsm {
    pub fn server(state: AppState) -> Scope {
        web::scope("/v2/gsm")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::post().to(gsm::create_gsm_rule)))
            .service(web::resource("/get").route(web::post().to(gsm::get_gsm_rule)))
            .service(web::resource("/update").route(web::post().to(gsm::update_gsm_rule)))
            .service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule)))
    }
}
pub struct Chat;

#[cfg(feature = "olap")]
impl Chat {
    pub fn server(state: AppState) -> Scope {
        let mut route = web::scope("/chat").app_data(web::Data::new(state.clone()));
        if state.conf.chat.enabled {
            route = route.service(
                web::scope("/ai").service(
                    web::resource("/data")
                        .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)),
                ),
            );
        }
        route
    }
}
pub struct ThreeDsDecisionRule;

#[cfg(feature = "oltp")]
impl ThreeDsDecisionRule {
    pub fn server(state: AppState) -> Scope {
        web::scope("/three_ds_decision")
            .app_data(web::Data::new(state))
            .service(
                web::resource("/execute")
                    .route(web::post().to(three_ds_decision_rule::execute_decision_rule)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct Verify;
#[cfg(all(feature = "olap", feature = "v1"))]
impl Verify {
    pub fn server(state: AppState) -> Scope {
        web::scope("/verify")
            .app_data(web::Data::new(state))
            .service(
                web::resource("/apple_pay/{merchant_id}")
                    .route(web::post().to(apple_pay_merchant_registration)),
            )
            .service(
                web::resource("/applepay_verified_domains")
                    .route(web::get().to(retrieve_apple_pay_verified_domains)),
            )
    }
}

#[cfg(all(feature = "olap", feature = "v2"))]
impl Verify {
    pub fn server(state: AppState) -> Scope {
        web::scope("/v2/verify")
            .app_data(web::Data::new(state))
            .service(
                web::resource("/apple-pay/{merchant_id}")
                    .route(web::post().to(apple_pay_merchant_registration)),
            )
            .service(
                web::resource("/applepay-verified-domains")
                    .route(web::get().to(retrieve_apple_pay_verified_domains)),
            )
    }
}

pub struct UserDeprecated;

#[cfg(all(feature = "olap", feature = "v2"))]
impl UserDeprecated {
    pub fn server(state: AppState) -> Scope {
        // TODO: Deprecated. Remove this in favour of /v2/users
        let mut route = web::scope("/v2/user").app_data(web::Data::new(state));

        route = route.service(
            web::resource("/create_merchant")
                .route(web::post().to(user::user_merchant_account_create)),
        );
        route = route.service(
            web::scope("/list")
                .service(
                    web::resource("/merchant")
                        .route(web::get().to(user::list_merchants_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
                ),
        );

        route = route.service(
            web::scope("/switch")
                .service(
                    web::resource("/merchant")
                        .route(web::post().to(user::switch_merchant_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
                ),
        );

        route = route.service(
            web::resource("/data")
                .route(web::get().to(user::get_multiple_dashboard_metadata))
                .route(web::post().to(user::set_dashboard_metadata)),
        );

        route
    }
}

pub struct User;

#[cfg(all(feature = "olap", feature = "v2"))]
impl User {
    pub fn server(state: AppState) -> Scope {
        let mut route = web::scope("/v2/users").app_data(web::Data::new(state));

        route = route.service(
            web::resource("/create-merchant")
                .route(web::post().to(user::user_merchant_account_create)),
        );
        route = route.service(
            web::scope("/list")
                .service(
                    web::resource("/merchant")
                        .route(web::get().to(user::list_merchants_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
                ),
        );

        route = route.service(
            web::scope("/switch")
                .service(
                    web::resource("/merchant")
                        .route(web::post().to(user::switch_merchant_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
                ),
        );

        route = route.service(
            web::resource("/data")
                .route(web::get().to(user::get_multiple_dashboard_metadata))
                .route(web::post().to(user::set_dashboard_metadata)),
        );

        route
    }
}

#[cfg(all(feature = "olap", feature = "v1"))]
impl User {
    pub fn server(state: AppState) -> Scope {
        let mut route = web::scope("/user").app_data(web::Data::new(state.clone()));

        route = route
            .service(web::resource("").route(web::get().to(user::get_user_details)))
            .service(web::resource("/signin").route(web::post().to(user::user_signin)))
            .service(web::resource("/v2/signin").route(web::post().to(user::user_signin)))
            // signin/signup with sso using openidconnect
            .service(web::resource("/oidc").route(web::post().to(user::sso_sign)))
            .service(web::resource("/signout").route(web::post().to(user::signout)))
            .service(web::resource("/rotate_password").route(web::post().to(user::rotate_password)))
            .service(web::resource("/change_password").route(web::post().to(user::change_password)))
            .service(
                web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)),
            )
            .service(
                web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)),
            )
            .service(web::resource("/create_org").route(web::post().to(user::user_org_create)))
            .service(
                web::resource("/create_merchant")
                    .route(web::post().to(user::user_merchant_account_create)),
            )
            // TODO: To be deprecated
            .service(
                web::resource("/permission_info")
                    .route(web::get().to(user_role::get_authorization_info)),
            )
            // TODO: To be deprecated
            .service(
                web::resource("/module/list").route(web::get().to(user_role::get_role_information)),
            )
            .service(
                web::resource("/parent/list")
                    .route(web::get().to(user_role::get_parent_group_info)),
            )
            .service(
                web::resource("/update").route(web::post().to(user::update_user_account_details)),
            )
            .service(
                web::resource("/data")
                    .route(web::get().to(user::get_multiple_dashboard_metadata))
                    .route(web::post().to(user::set_dashboard_metadata)),
            );

        if state.conf.platform.enabled {
            route = route.service(
                web::resource("/create_platform").route(web::post().to(user::create_platform)),
            )
        }

        route = route
            .service(web::scope("/key").service(
                web::resource("/transfer").route(web::post().to(user::transfer_user_key)),
            ));

        route = route.service(
            web::scope("/list")
                .service(web::resource("/org").route(web::get().to(user::list_orgs_for_user)))
                .service(
                    web::resource("/merchant")
                        .route(web::get().to(user::list_merchants_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),
                )
                .service(
                    web::resource("/invitation")
                        .route(web::get().to(user_role::list_invitations_for_user)),
                ),
        );

        route = route.service(
            web::scope("/switch")
                .service(web::resource("/org").route(web::post().to(user::switch_org_for_user)))
                .service(
                    web::resource("/merchant")
                        .route(web::post().to(user::switch_merchant_for_user_in_org)),
                )
                .service(
                    web::resource("/profile")
                        .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),
                ),
        );

        // Two factor auth routes
        route = route.service(
            web::scope("/2fa")
                // TODO: to be deprecated
                .service(web::resource("").route(web::get().to(user::check_two_factor_auth_status)))
                .service(
                    web::resource("/v2")
                        .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),
                )
                .service(
                    web::scope("/totp")
                        .service(web::resource("/begin").route(web::get().to(user::totp_begin)))
                        .service(web::resource("/reset").route(web::get().to(user::totp_reset)))
                        .service(
                            web::resource("/verify")
                                .route(web::post().to(user::totp_verify))
                                .route(web::put().to(user::totp_update)),
                        ),
                )
                .service(
                    web::scope("/recovery_code")
                        .service(
                            web::resource("/verify")
                                .route(web::post().to(user::verify_recovery_code)),
                        )
                        .service(
                            web::resource("/generate")
                                .route(web::get().to(user::generate_recovery_codes)),
                        ),
                )
                .service(
                    web::resource("/terminate")
                        .route(web::get().to(user::terminate_two_factor_auth)),
                ),
        );

        route = route.service(
            web::scope("/auth")
                .service(
                    web::resource("")
                        .route(web::post().to(user::create_user_authentication_method))
                        .route(web::put().to(user::update_user_authentication_method)),
                )
                .service(
                    web::resource("/list")
                        .route(web::get().to(user::list_user_authentication_methods)),
                )
                .service(web::resource("/url").route(web::get().to(user::get_sso_auth_url)))
                .service(
                    web::resource("/select").route(web::post().to(user::terminate_auth_select)),
                ),
        );

        #[cfg(feature = "email")]
        {
            route = route
                .service(web::resource("/from_email").route(web::post().to(user::user_from_email)))
                .service(
                    web::resource("/connect_account")
                        .route(web::post().to(user::user_connect_account)),
                )
                .service(
                    web::resource("/forgot_password").route(web::post().to(user::forgot_password)),
                )
                .service(
                    web::resource("/reset_password").route(web::post().to(user::reset_password)),
                )
                .service(
                    web::resource("/signup_with_merchant_id")
                        .route(web::post().to(user::user_signup_with_merchant_id)),
                )
                .service(web::resource("/verify_email").route(web::post().to(user::verify_email)))
                .service(
                    web::resource("/v2/verify_email").route(web::post().to(user::verify_email)),
                )
                .service(
                    web::resource("/verify_email_request")
                        .route(web::post().to(user::verify_email_request)),
                )
                .service(
                    web::resource("/user/resend_invite").route(web::post().to(user::resend_invite)),
                )
                .service(
                    web::resource("/accept_invite_from_email")
                        .route(web::post().to(user::accept_invite_from_email)),
                );
        }
        #[cfg(not(feature = "email"))]
        {
            route = route.service(web::resource("/signup").route(web::post().to(user::user_signup)))
        }

        // User management
        route = route.service(
            web::scope("/user")
                .service(web::resource("").route(web::post().to(user::list_user_roles_details)))
                // TODO: To be deprecated
                .service(web::resource("/v2").route(web::post().to(user::list_user_roles_details)))
                .service(
                    web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)),
                )
                // TODO: To be deprecated
                .service(
                    web::resource("/v2/list")
                        .route(web::get().to(user_role::list_users_in_lineage)),
                )
                .service(
                    web::resource("/invite_multiple")
                        .route(web::post().to(user::invite_multiple_user)),
                )
                .service(
                    web::scope("/invite/accept")
                        .service(
                            web::resource("")
                                .route(web::post().to(user_role::accept_invitations_v2)),
                        )
                        .service(
                            web::resource("/pre_auth")
                                .route(web::post().to(user_role::accept_invitations_pre_auth)),
                        )
                        .service(
                            web::scope("/v2")
                                .service(
                                    web::resource("")
                                        .route(web::post().to(user_role::accept_invitations_v2)),
                                )
                                .service(
                                    web::resource("/pre_auth").route(
                                        web::post().to(user_role::accept_invitations_pre_auth),
                                    ),
                                ),
                        ),
                )
                .service(
                    web::resource("/update_role")
                        .route(web::post().to(user_role::update_user_role)),
                )
                .service(
                    web::resource("/delete").route(web::delete().to(user_role::delete_user_role)),
                ),
        );

        if state.conf().clone_connector_allowlist.is_some() {
            route = route.service(
                web::resource("/clone_connector").route(web::post().to(user::clone_connector)),
            );
        }

        // Role information
        route = route.service(
            web::scope("/role")
                .service(
                    web::resource("")
                        .route(web::get().to(user_role::get_role_from_token))
                        // TODO: To be deprecated
                        .route(web::post().to(user_role::create_role)),
                )
                .service(
                    web::resource("/v2")
                        .route(web::post().to(user_role::create_role_v2))
                        .route(
                            web::get().to(user_role::get_groups_and_resources_for_role_from_token),
                        ),
                )
                // TODO: To be deprecated
                .service(
                    web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)),
                )
                .service(
                    web::scope("/list")
                        .service(
                            web::resource("").route(web::get().to(user_role::list_roles_with_info)),
                        )
                        .service(
                            web::resource("/invite").route(
                                web::get().to(user_role::list_invitable_roles_at_entity_level),
                            ),
                        )
                        .service(
                            web::resource("/update").route(
                                web::get().to(user_role::list_updatable_roles_at_entity_level),
                            ),
                        ),
                )
                .service(
                    web::resource("/{role_id}")
                        .route(web::get().to(user_role::get_role))
                        .route(web::put().to(user_role::update_role)),
                )
                .service(
                    web::resource("/{role_id}/v2")
                        .route(web::get().to(user_role::get_parent_info_for_role)),
                ),
        );

        #[cfg(feature = "dummy_connector")]
        {
            route = route.service(
                web::resource("/sample_data")
                    .route(web::post().to(user::generate_sample_data))
                    .route(web::delete().to(user::delete_sample_data)),
            )
        }
        // Admin Theme
        // TODO: To be deprecated
        route = route.service(
            web::scope("/admin/theme")
                .service(
                    web::resource("")
                        .route(web::get().to(user::theme::get_theme_using_lineage))
                        .route(web::post().to(user::theme::create_theme)),
                )
                .service(
                    web::resource("/{theme_id}")
                        .route(web::get().to(user::theme::get_theme_using_theme_id))
                        .route(web::put().to(user::theme::update_theme))
                        .route(web::post().to(user::theme::upload_file_to_theme_storage))
                        .route(web::delete().to(user::theme::delete_theme)),
                ),
        );
        // User Theme
        route = route.service(
            web::scope("/theme")
                .service(
                    web::resource("")
                        .route(web::post().to(user::theme::create_user_theme))
                        .route(web::get().to(user::theme::get_user_theme_using_lineage)),
                )
                .service(
                    web::resource("/list")
                        .route(web::get().to(user::theme::list_all_themes_in_lineage)),
                )
                .service(
                    web::resource("/{theme_id}")
                        .route(web::get().to(user::theme::get_user_theme_using_theme_id))
                        .route(web::put().to(user::theme::update_user_theme))
                        .route(web::post().to(user::theme::upload_file_to_user_theme_storage))
                        .route(web::delete().to(user::theme::delete_user_theme)),
                ),
        );
        route
    }
}

pub struct ConnectorOnboarding;

#[cfg(all(feature = "olap", feature = "v1"))]
impl ConnectorOnboarding {
    pub fn server(state: AppState) -> Scope {
        web::scope("/connector_onboarding")
            .app_data(web::Data::new(state))
            .service(
                web::resource("/action_url")
                    .route(web::post().to(connector_onboarding::get_action_url)),
            )
            .service(
                web::resource("/sync")
                    .route(web::post().to(connector_onboarding::sync_onboarding_status)),
            )
            .service(
                web::resource("/reset_tracking_id")
                    .route(web::post().to(connector_onboarding::reset_tracking_id)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct WebhookEvents;

#[cfg(all(feature = "olap", feature = "v1"))]
impl WebhookEvents {
    pub fn server(config: AppState) -> Scope {
        web::scope("/events")
            .app_data(web::Data::new(config))
            .service(web::scope("/profile/list").service(web::resource("").route(
                web::post().to(webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth),
            )))
            .service(
                web::scope("/{merchant_id}")
                    .service(web::resource("").route(
                        web::post().to(webhook_events::list_initial_webhook_delivery_attempts),
                    ))
                    .service(
                        web::scope("/{event_id}")
                            .service(web::resource("attempts").route(
                                web::get().to(webhook_events::list_webhook_delivery_attempts),
                            ))
                            .service(web::resource("retry").route(
                                web::post().to(webhook_events::retry_webhook_delivery_attempt),
                            )),
                    ),
            )
    }
}

#[cfg(feature = "olap")]
pub struct FeatureMatrix;

#[cfg(all(feature = "olap", feature = "v1"))]
impl FeatureMatrix {
    pub fn server(state: AppState) -> Scope {
        web::scope("/feature_matrix")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::get().to(feature_matrix::fetch_feature_matrix)))
    }
}

#[cfg(feature = "olap")]
pub struct ProcessTrackerDeprecated;

#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTrackerDeprecated {
    pub fn server(state: AppState) -> Scope {
        use super::process_tracker::revenue_recovery;
        // TODO: Deprecated. Remove this in favour of /v2/process-trackers
        web::scope("/v2/process_tracker/revenue_recovery_workflow")
            .app_data(web::Data::new(state.clone()))
            .service(
                web::resource("/{revenue_recovery_id}")
                    .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct ProcessTracker;

#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTracker {
    pub fn server(state: AppState) -> Scope {
        use super::process_tracker::revenue_recovery;
        web::scope("/v2/process-trackers/revenue-recovery-workflow")
            .app_data(web::Data::new(state.clone()))
            .service(
                web::resource("/{revenue_recovery_id}")
                    .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)),
            )
    }
}

pub struct Authentication;

#[cfg(feature = "v1")]
impl Authentication {
    pub fn server(state: AppState) -> Scope {
        web::scope("/authentication")
            .app_data(web::Data::new(state))
            .service(web::resource("").route(web::post().to(authentication::authentication_create)))
            .service(
                web::resource("/{authentication_id}/eligibility")
                    .route(web::post().to(authentication::authentication_eligibility)),
            )
            .service(
                web::resource("/{authentication_id}/authenticate")
                    .route(web::post().to(authentication::authentication_authenticate)),
            )
            .service(
                web::resource("{merchant_id}/{authentication_id}/sync")
                    .route(web::post().to(authentication::authentication_sync))
                    .route(web::get().to(authentication::authentication_sync_post_update)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct ProfileAcquirer;

#[cfg(all(feature = "olap", feature = "v1"))]
impl ProfileAcquirer {
    pub fn server(state: AppState) -> Scope {
        web::scope("/profile_acquirer")
            .app_data(web::Data::new(state))
            .service(
                web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)),
            )
            .service(
                web::resource("/{profile_id}/{profile_acquirer_id}")
                    .route(web::post().to(profile_acquirer::profile_acquirer_update)),
            )
    }
}


pub fn update_router_data_with_payment_method_token_result<F: Clone, T>(
    payment_method_token_result: types::PaymentMethodTokenResult,
    router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>,
    is_retry_payment: bool,
    should_continue_further: bool,
) -> bool {
    if payment_method_token_result.is_payment_method_tokenization_performed {
        match payment_method_token_result.payment_method_token_result {
            Ok(pm_token_result) => {
                router_data.payment_method_token = pm_token_result.map(|pm_token| {
                    hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new(
                        pm_token,
                    ))
                });
                if router_data.connector_response.is_none() {
                    router_data.connector_response =
                        payment_method_token_result.connector_response.clone();
                }
                true
            }
            Err(err) => {
                if is_retry_payment {
                    router_data.response = Err(err);
                    false
                } else {
                    logger::debug!(payment_method_tokenization_error=?err);
                    true
                }
            }
        }
    } else {
        should_continue_further
    }
}


impl ConnectorCommon for Cashtocode {
    fn id(&self) -> &'static str {
        "cashtocode"
    }

    fn common_get_content_type(&self) -> &'static str {
        "application/json"
    }

    fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
        connectors.cashtocode.base_url.as_ref()
    }

    fn build_error_response(
        &self,
        res: Response,
        event_builder: Option<&mut ConnectorEvent>,
    ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
        let response: cashtocode::CashtocodeErrorResponse = res
            .response
            .parse_struct("CashtocodeErrorResponse")
            .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;

        event_builder.map(|i| i.set_error_response_body(&response));
        router_env::logger::info!(connector_response=?response);

        Ok(ErrorResponse {
            status_code: res.status_code,
            code: response.error.to_string(),
            message: response.error_description.clone(),
            reason: Some(response.error_description),
            attempt_status: None,
            connector_transaction_id: None,
            network_advice_code: None,
            network_decline_code: None,
            network_error_message: None,
            connector_metadata: None,
        })
    }
}


pub struct Processor {
    reference_number: Option<String>,
    authorization_code: Option<String>,
    response_code: Option<String>,
    response_message: Option<String>,
    avs_response: Option<AvsResponse>,
    security_code_response: Option<String>,
}


impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}

impl super::refunds::metrics::RefundMetricAnalytics for for SqlxClient


pub struct OnboardSubAccountResponse {
    pub account_id: Secret<String>,
    pub id: String,
    pub client_sub_account_id: Secret<String>,
    pub profile: Profile,
    pub virtual_accounts: Vec<VirtualAccountsType>,
    pub status: String,
    pub created_on: String,
    pub last_updated: String,
}


pub struct NexinetsPaymentResponse {
    pub transaction_id: String,
    pub status: NexinetsPaymentStatus,
    pub order: NexinetsOrder,
    #[serde(rename = "type")]
    pub transaction_type: NexinetsTransactionType,
}


impl<'a> NetworkTokenizationBuilder<'a, CardTokenized> {
    pub fn set_stored_card_response(
        self,
        store_card_response: &'a StoreLockerResponse,
    ) -> NetworkTokenizationBuilder<'a, CardStored> {
        NetworkTokenizationBuilder {
            state: std::marker::PhantomData,
            stored_card: Some(&store_card_response.store_card_resp),
            customer: self.customer,
            card: self.card,
            card_cvc: self.card_cvc,
            network_token: self.network_token,
            stored_token: self.stored_token,
            payment_method_response: self.payment_method_response,
            card_tokenized: self.card_tokenized,
            error_code: self.error_code,
            error_message: self.error_message,
        }
    }
}


File: crates/router/src/services/kafka/payout.rs
 Public functions: 1
 Public structs: 1

use common_utils::{id_type, pii, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts};
use time::OffsetDateTime;

#[derive(serde::Serialize, Debug)]
pub struct KafkaPayout<'a> {
    pub payout_id: &'a id_type::PayoutId,
    pub payout_attempt_id: &'a String,
    pub merchant_id: &'a id_type::MerchantId,
    pub customer_id: Option<&'a id_type::CustomerId>,
    pub address_id: Option<&'a String>,
    pub profile_id: &'a id_type::ProfileId,
    pub payout_method_id: Option<&'a String>,
    pub payout_type: Option<storage_enums::PayoutType>,
    pub amount: MinorUnit,
    pub destination_currency: storage_enums::Currency,
    pub source_currency: storage_enums::Currency,
    pub description: Option<&'a String>,
    pub recurring: bool,
    pub auto_fulfill: bool,
    pub return_url: Option<&'a String>,
    pub entity_type: storage_enums::PayoutEntityType,
    pub metadata: Option<pii::SecretSerdeValue>,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp")]
    pub last_modified_at: OffsetDateTime,
    pub attempt_count: i16,
    pub status: storage_enums::PayoutStatus,
    pub priority: Option<storage_enums::PayoutSendPriority>,

    pub connector: Option<&'a String>,
    pub connector_payout_id: Option<&'a String>,
    pub is_eligible: Option<bool>,
    pub error_message: Option<&'a String>,
    pub error_code: Option<&'a String>,
    pub business_country: Option<storage_enums::CountryAlpha2>,
    pub business_label: Option<&'a String>,
    pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
}

impl<'a> KafkaPayout<'a> {
    pub fn from_storage(payouts: &'a Payouts, payout_attempt: &'a PayoutAttempt) -> Self {
        Self {
            payout_id: &payouts.payout_id,
            payout_attempt_id: &payout_attempt.payout_attempt_id,
            merchant_id: &payouts.merchant_id,
            customer_id: payouts.customer_id.as_ref(),
            address_id: payouts.address_id.as_ref(),
            profile_id: &payouts.profile_id,
            payout_method_id: payouts.payout_method_id.as_ref(),
            payout_type: payouts.payout_type,
            amount: payouts.amount,
            destination_currency: payouts.destination_currency,
            source_currency: payouts.source_currency,
            description: payouts.description.as_ref(),
            recurring: payouts.recurring,
            auto_fulfill: payouts.auto_fulfill,
            return_url: payouts.return_url.as_ref(),
            entity_type: payouts.entity_type,
            metadata: payouts.metadata.clone(),
            created_at: payouts.created_at.assume_utc(),
            last_modified_at: payouts.last_modified_at.assume_utc(),
            attempt_count: payouts.attempt_count,
            status: payouts.status,
            priority: payouts.priority,
            connector: payout_attempt.connector.as_ref(),
            connector_payout_id: payout_attempt.connector_payout_id.as_ref(),
            is_eligible: payout_attempt.is_eligible,
            error_message: payout_attempt.error_message.as_ref(),
            error_code: payout_attempt.error_code.as_ref(),
            business_country: payout_attempt.business_country,
            business_label: payout_attempt.business_label.as_ref(),
            merchant_connector_id: payout_attempt.merchant_connector_id.as_ref(),
        }
    }
}

impl super::KafkaMessage for KafkaPayout<'_> {
    fn key(&self) -> String {
        format!(
            "{}_{}",
            self.merchant_id.get_string_repr(),
            self.payout_attempt_id
        )
    }

    fn event_type(&self) -> crate::events::EventType {
        crate::events::EventType::Payout
    }
}


pub struct RsyncApplicationInformation {
    status: Option<BarclaycardRefundStatus>,
}


pub struct ThreedsecureioPostAuthenticationRequest {
    pub three_ds_server_trans_id: String,
}