        //Note: we might have to call retrieve_setup_intent to get the network_transaction_id in case its not sent in PaymentIntentResponse
        // Or we identify the mandate txns before hand and always call SetupIntent in case of mandate payment call
        let network_txn_id = match item.response.latest_charge.as_ref() {
            Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
                .payment_method_details
                .as_ref()
                .and_then(|payment_method_details| match payment_method_details {
                    StripePaymentMethodDetailsResponse::Card { card } => {
                        card.network_transaction_id.clone()
                    }
                    _ => None,
                }),
            _ => None,
        };

        let connector_metadata =
            get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;

        let status = AttemptStatus::from(item.response.status);

        let response = if is_payment_failure(status) {
            *get_stripe_payments_response_data(
                &item.response.last_payment_error,
                item.http_code,
                item.response.id.clone(),
            )
        } else {
            let charges = item
                .response
                .latest_charge
                .as_ref()
                .map(|charge| match charge {
                    StripeChargeEnum::ChargeId(charges) => charges.clone(),
                    StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
                })
                .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request));

            Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
                redirection_data: Box::new(redirection_data),
                mandate_reference: Box::new(mandate_reference),
                connector_metadata,
                network_txn_id,
                connector_response_reference_id: Some(item.response.id),
                incremental_authorization_allowed: item
                    .data
                    .request
                    .get_request_incremental_authorization(),
                charges,
            })
        };

        let connector_response_data = item
            .response
            .latest_charge
            .as_ref()
            .and_then(extract_payment_method_connector_response_from_latest_charge);

        Ok(Self {
            status,
            /* Commented out fields:
            client_secret: Some(item.response.client_secret.clone().as_str()),
            description: item.response.description.map(|x| x.as_str()),
            statement_descriptor_suffix: item.response.statement_descriptor_suffix.map(|x| x.as_str()),
            three_ds_form,
            */
            response,
            amount_captured: item
                .response
                .amount_received
                .map(|amount| amount.get_amount_as_i64()),
            minor_amount_captured: item.response.amount_received,
            connector_response: connector_response_data,
            ..item.data
        })
    }
}

impl From<StripePaymentStatus> for common_enums::AuthorizationStatus {
    fn from(item: StripePaymentStatus) -> Self {
        match item {
            StripePaymentStatus::Succeeded
            | StripePaymentStatus::RequiresCapture
            | StripePaymentStatus::Chargeable
            | StripePaymentStatus::RequiresCustomerAction
            | StripePaymentStatus::RequiresConfirmation
            | StripePaymentStatus::Consumed => Self::Success,
            StripePaymentStatus::Processing | StripePaymentStatus::Pending => Self::Processing,
            StripePaymentStatus::Failed
            | StripePaymentStatus::Canceled
            | StripePaymentStatus::RequiresPaymentMethod => Self::Failure,
        }
    }
}

impl<F>
    TryFrom<
        ResponseRouterData<
            F,
            PaymentIntentResponse,
            PaymentsIncrementalAuthorizationData,
            PaymentsResponseData,
        >,
    > for RouterData<F, PaymentsIncrementalAuthorizationData, PaymentsResponseData>
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<
            F,
            PaymentIntentResponse,
            PaymentsIncrementalAuthorizationData,
            PaymentsResponseData,
        >,
    ) -> Result<Self, Self::Error> {
        let status = common_enums::AuthorizationStatus::from(item.response.status);
        Ok(Self {
            response: Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
                status,
                error_code: None,
                error_message: None,
                connector_authorization_id: Some(item.response.id),
            }),
            ..item.data
        })
    }
}

pub fn get_connector_metadata(
    next_action: Option<&StripeNextActionResponse>,
    amount: MinorUnit,
) -> CustomResult<Option<Value>, ConnectorError> {
    let next_action_response = next_action
        .and_then(|next_action_response| match next_action_response {
            StripeNextActionResponse::DisplayBankTransferInstructions(response) => {
                match response.financial_addresses.clone() {
                    FinancialInformation::StripeFinancialInformation(financial_addresses) => {
                        let bank_instructions = financial_addresses.first();
                        let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions
                            .map_or((None, None), |financial_address| {
                                (
                                    financial_address.iban.to_owned().map(
                                        |sepa_financial_details| SepaFinancialDetails {
                                            account_holder_name: sepa_financial_details
                                                .account_holder_name,
                                            bic: sepa_financial_details.bic,
                                            country: sepa_financial_details.country,
                                            iban: sepa_financial_details.iban,
                                            reference: response.reference.to_owned(),
                                        },
                                    ),
                                    financial_address.sort_code.to_owned(),
                                )
                            });
                        let bank_transfer_instructions = SepaAndBacsBankTransferInstructions {
                            sepa_bank_instructions,
                            bacs_bank_instructions,
                            receiver: SepaAndBacsReceiver {
                                amount_received: amount - response.amount_remaining,
                                amount_remaining: response.amount_remaining,
                            },
                        };

                        Some(bank_transfer_instructions.encode_to_value())
                    }
                    FinancialInformation::AchFinancialInformation(financial_addresses) => {
                        let mut ach_financial_information = HashMap::new();
                        for address in financial_addresses {
                            match address.financial_details {
                                AchFinancialDetails::Aba(aba_details) => {
                                    ach_financial_information
                                        .insert("account_number", aba_details.account_number);
                                    ach_financial_information
                                        .insert("bank_name", aba_details.bank_name);
                                    ach_financial_information
                                        .insert("routing_number", aba_details.routing_number);
                                }
                                AchFinancialDetails::Swift(swift_details) => {
                                    ach_financial_information
                                        .insert("swift_code", swift_details.swift_code);
                                }
                            }
                        }

                        let ach_financial_information_value =
                            serde_json::to_value(ach_financial_information).ok()?;

                        let ach_transfer_instruction =
                            serde_json::from_value::<payments::AchTransfer>(
                                ach_financial_information_value,
                            )
                            .ok()?;

                        let bank_transfer_instructions = payments::BankTransferNextStepsData {
                            bank_transfer_instructions:
                                payments::BankTransferInstructions::AchCreditTransfer(Box::new(
                                    ach_transfer_instruction,
                                )),
                            receiver: None,
                        };

                        Some(bank_transfer_instructions.encode_to_value())
                    }
                }
            }
            StripeNextActionResponse::WechatPayDisplayQrCode(response) => {
                let wechat_pay_instructions = QrCodeNextInstructions {
                    image_data_url: response.image_data_url.to_owned(),
                    display_to_timestamp: None,
                };

                Some(wechat_pay_instructions.encode_to_value())
            }
            StripeNextActionResponse::CashappHandleRedirectOrDisplayQrCode(response) => {
                let cashapp_qr_instructions: QrCodeNextInstructions = QrCodeNextInstructions {
                    image_data_url: response.qr_code.image_url_png.to_owned(),
                    display_to_timestamp: response.qr_code.expires_at.to_owned(),
                };
                Some(cashapp_qr_instructions.encode_to_value())
            }
            StripeNextActionResponse::MultibancoDisplayDetails(response) => {
                let multibanco_bank_transfer_instructions = payments::BankTransferNextStepsData {
                    bank_transfer_instructions: payments::BankTransferInstructions::Multibanco(
                        Box::new(payments::MultibancoTransferInstructions {
                            reference: response.clone().reference,
                            entity: response.clone().entity.expose(),
                        }),
                    ),
                    receiver: None,
                };
                Some(multibanco_bank_transfer_instructions.encode_to_value())
            }
            _ => None,
        })
        .transpose()
        .change_context(ConnectorError::ResponseHandlingFailed)?;
    Ok(next_action_response)
}

pub fn get_payment_method_id(
    latest_charge: Option<StripeChargeEnum>,
    payment_method_id_from_intent_root: Secret<String>,
) -> String {
    match latest_charge {
        Some(StripeChargeEnum::ChargeObject(charge)) => match charge.payment_method_details {
            Some(StripePaymentMethodDetailsResponse::Bancontact { bancontact }) => bancontact
                .attached_payment_method
                .map(|attached_payment_method| attached_payment_method.expose())
                .unwrap_or(payment_method_id_from_intent_root.expose()),
            Some(StripePaymentMethodDetailsResponse::Ideal { ideal }) => ideal
                .attached_payment_method
                .map(|attached_payment_method| attached_payment_method.expose())
                .unwrap_or(payment_method_id_from_intent_root.expose()),
            Some(StripePaymentMethodDetailsResponse::Blik)
            | Some(StripePaymentMethodDetailsResponse::Eps)
            | Some(StripePaymentMethodDetailsResponse::Fpx)
            | Some(StripePaymentMethodDetailsResponse::Giropay)
            | Some(StripePaymentMethodDetailsResponse::Przelewy24)
            | Some(StripePaymentMethodDetailsResponse::Card { .. })
            | Some(StripePaymentMethodDetailsResponse::Klarna)
            | Some(StripePaymentMethodDetailsResponse::Affirm)
            | Some(StripePaymentMethodDetailsResponse::AfterpayClearpay)
            | Some(StripePaymentMethodDetailsResponse::AmazonPay)
            | Some(StripePaymentMethodDetailsResponse::ApplePay)
            | Some(StripePaymentMethodDetailsResponse::Ach)
            | Some(StripePaymentMethodDetailsResponse::Sepa)
            | Some(StripePaymentMethodDetailsResponse::Becs)
            | Some(StripePaymentMethodDetailsResponse::Bacs)
            | Some(StripePaymentMethodDetailsResponse::Wechatpay)
            | Some(StripePaymentMethodDetailsResponse::Alipay)
            | Some(StripePaymentMethodDetailsResponse::CustomerBalance)
            | Some(StripePaymentMethodDetailsResponse::Cashapp { .. })
            | Some(StripePaymentMethodDetailsResponse::RevolutPay)
            | None => payment_method_id_from_intent_root.expose(),
        },
        Some(StripeChargeEnum::ChargeId(_)) | None => payment_method_id_from_intent_root.expose(),
    }
}

impl<F, T> TryFrom<ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>>
    for RouterData<F, T, PaymentsResponseData>
where
    T: SplitPaymentData,
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, PaymentIntentSyncResponse, T, PaymentsResponseData>,
    ) -> Result<Self, Self::Error> {
        let redirect_data = item.response.next_action.clone();
        let redirection_data = redirect_data
            .and_then(|redirection_data| redirection_data.get_url())
            .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));

        let mandate_reference = item
            .response
            .payment_method
            .clone()
            .map(|payment_method_id| {
                // Implemented Save and re-use payment information for recurring charges
                // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
                // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
                let payment_method_id =
                    get_payment_method_id(item.response.latest_charge.clone(), payment_method_id);

                MandateReference {
                    connector_mandate_id: Some(payment_method_id.clone()),
                    payment_method_id: Some(payment_method_id),
                    mandate_metadata: None,
                    connector_mandate_request_reference_id: None,
                }
            });

        let connector_metadata =
            get_connector_metadata(item.response.next_action.as_ref(), item.response.amount)?;

        let status = AttemptStatus::from(item.response.status.to_owned());

        let connector_response_data = item
            .response
            .latest_charge
            .as_ref()
            .and_then(extract_payment_method_connector_response_from_latest_charge);

        let response = if is_payment_failure(status) {
            *get_stripe_payments_response_data(
                &item.response.payment_intent_fields.last_payment_error,
                item.http_code,
                item.response.id.clone(),
            )
        } else {
            let network_transaction_id = match item.response.latest_charge.clone() {
                Some(StripeChargeEnum::ChargeObject(charge_object)) => charge_object
                    .payment_method_details
                    .and_then(|payment_method_details| match payment_method_details {
                        StripePaymentMethodDetailsResponse::Card { card } => {
                            card.network_transaction_id
                        }
                        _ => None,
                    }),
                _ => None,
            };
            let charges = item
                .response
                .latest_charge
                .as_ref()
                .map(|charge| match charge {
                    StripeChargeEnum::ChargeId(charges) => charges.clone(),
                    StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
                })
                .and_then(|charge_id| construct_charge_response(charge_id, &item.data.request));

            Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
                redirection_data: Box::new(redirection_data),
                mandate_reference: Box::new(mandate_reference),
                connector_metadata,
                network_txn_id: network_transaction_id,
                connector_response_reference_id: Some(item.response.id.clone()),
                incremental_authorization_allowed: None,
                charges,
            })
        };

        Ok(Self {
            status: AttemptStatus::from(item.response.status.to_owned()),
            response,
            amount_captured: item
                .response
                .amount_received
                .map(|amount| amount.get_amount_as_i64()),
            minor_amount_captured: item.response.amount_received,
            connector_response: connector_response_data,
            ..item.data
        })
    }
}

impl<F, T> TryFrom<ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>>
    for RouterData<F, T, PaymentsResponseData>
{
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, SetupIntentResponse, T, PaymentsResponseData>,
    ) -> Result<Self, Self::Error> {
        let redirect_data = item.response.next_action.clone();
        let redirection_data = redirect_data
            .and_then(|redirection_data| redirection_data.get_url())
            .map(|redirection_url| RedirectForm::from((redirection_url, Method::Get)));

        let mandate_reference = item.response.payment_method.map(|payment_method_id| {
            // Implemented Save and re-use payment information for recurring charges
            // For more info: https://docs.stripe.com/recurring-payments#accept-recurring-payments
            // For backward compatibility payment_method_id & connector_mandate_id is being populated with the same value
            let connector_mandate_id = Some(payment_method_id.clone());
            let payment_method_id = Some(payment_method_id);
            MandateReference {
                connector_mandate_id,
                payment_method_id,
                mandate_metadata: None,
                connector_mandate_request_reference_id: None,
            }
        });
        let status = AttemptStatus::from(item.response.status);
        let connector_response_data = item
            .response
            .latest_attempt
            .as_ref()
            .and_then(extract_payment_method_connector_response_from_latest_attempt);

        let response = if is_payment_failure(status) {
            *get_stripe_payments_response_data(
                &item.response.last_setup_error,
                item.http_code,
                item.response.id.clone(),
            )
        } else {
            let network_transaction_id = match item.response.latest_attempt {
                Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
                    .payment_method_details
                    .and_then(|payment_method_details| match payment_method_details {
                        StripePaymentMethodDetailsResponse::Card { card } => {
                            card.network_transaction_id
                        }
                        _ => None,
                    }),
                _ => None,
            };

            Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
                redirection_data: Box::new(redirection_data),
                mandate_reference: Box::new(mandate_reference),
                connector_metadata: None,
                network_txn_id: network_transaction_id,
                connector_response_reference_id: Some(item.response.id),
                incremental_authorization_allowed: None,
                charges: None,
            })
        };

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

pub fn stripe_opt_latest_attempt_to_opt_string(
    latest_attempt: Option<LatestAttempt>,
) -> Option<String> {
    match latest_attempt {
        Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
            .payment_method_options
            .and_then(|payment_method_options| match payment_method_options {
                StripePaymentMethodOptions::Card {
                    network_transaction_id,
                    ..
                } => network_transaction_id.map(|network_id| network_id.expose()),
                _ => None,
            }),
        _ => None,
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", remote = "Self")]
pub enum StripeNextActionResponse {
    CashappHandleRedirectOrDisplayQrCode(StripeCashappQrResponse),
    RedirectToUrl(StripeRedirectToUrlResponse),
    AlipayHandleRedirect(StripeRedirectToUrlResponse),
    VerifyWithMicrodeposits(StripeVerifyWithMicroDepositsResponse),
    WechatPayDisplayQrCode(WechatPayRedirectToQr),
    DisplayBankTransferInstructions(StripeBankTransferDetails),
    MultibancoDisplayDetails(MultibancoCreditTansferResponse),
    NoNextActionBody,
}

impl StripeNextActionResponse {
    fn get_url(&self) -> Option<Url> {
        match self {
            Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => {
                Some(redirect_to_url.url.to_owned())
            }
            Self::WechatPayDisplayQrCode(_) => None,
            Self::VerifyWithMicrodeposits(verify_with_microdeposits) => {
                Some(verify_with_microdeposits.hosted_verification_url.to_owned())
            }
            Self::CashappHandleRedirectOrDisplayQrCode(_) => None,
            Self::DisplayBankTransferInstructions(_) => None,
            Self::MultibancoDisplayDetails(_) => None,
            Self::NoNextActionBody => None,
        }
    }
}

// This impl is required because Stripe's response is of the below format, which is externally
// tagged, but also with an extra 'type' field specifying the enum variant name:
// "next_action": {
//   "redirect_to_url": { "return_url": "...", "url": "..." },
//   "type": "redirect_to_url"
// },
// Reference: https://github.com/serde-rs/serde/issues/1343#issuecomment-409698470
impl<'de> Deserialize<'de> for StripeNextActionResponse {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(rename = "type")]
            _ignore: String,
            #[serde(flatten, with = "StripeNextActionResponse")]
            inner: StripeNextActionResponse,
        }

        // There is some exception in the stripe next action, it usually sends :
        // "next_action": {
        //   "redirect_to_url": { "return_url": "...", "url": "..." },
        //   "type": "redirect_to_url"
        // },
        // But there is a case where it only sends the type and not other field named as it's type
        let stripe_next_action_response =
            Wrapper::deserialize(deserializer).map_or(Self::NoNextActionBody, |w| w.inner);

        Ok(stripe_next_action_response)
    }
}

impl Serialize for StripeNextActionResponse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match *self {
            Self::CashappHandleRedirectOrDisplayQrCode(ref i) => {
                Serialize::serialize(i, serializer)
            }
            Self::RedirectToUrl(ref i) => Serialize::serialize(i, serializer),
            Self::AlipayHandleRedirect(ref i) => Serialize::serialize(i, serializer),
            Self::VerifyWithMicrodeposits(ref i) => Serialize::serialize(i, serializer),
            Self::WechatPayDisplayQrCode(ref i) => Serialize::serialize(i, serializer),
            Self::DisplayBankTransferInstructions(ref i) => Serialize::serialize(i, serializer),
            Self::MultibancoDisplayDetails(ref i) => Serialize::serialize(i, serializer),
            Self::NoNextActionBody => Serialize::serialize("NoNextActionBody", serializer),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeRedirectToUrlResponse {
    return_url: String,
    url: Url,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct WechatPayRedirectToQr {
    // This data contains url, it should be converted to QR code.
    // Note: The url in this data is not redirection url
    data: Url,
    // This is the image source, this image_data_url can directly be used by sdk to show the QR code
    image_data_url: Url,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeVerifyWithMicroDepositsResponse {
    hosted_verification_url: Url,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum FinancialInformation {
    AchFinancialInformation(Vec<AchFinancialInformation>),
    StripeFinancialInformation(Vec<StripeFinancialInformation>),
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeBankTransferDetails {
    pub amount_remaining: MinorUnit,
    pub currency: String,
    pub financial_addresses: FinancialInformation,
    pub hosted_instructions_url: Option<String>,
    pub reference: Option<String>,
    #[serde(rename = "type")]
    pub bank_transfer_type: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeCashappQrResponse {
    pub mobile_auth_url: Url,
    pub qr_code: QrCodeResponse,
    pub hosted_instructions_url: Url,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct QrCodeResponse {
    pub expires_at: Option<i64>,
    pub image_url_png: Url,
    pub image_url_svg: Url,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AbaDetails {
    pub account_number: Secret<String>,
    pub bank_name: Secret<String>,
    pub routing_number: Secret<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SwiftDetails {
    pub account_number: Secret<String>,
    pub bank_name: Secret<String>,
    pub swift_code: Secret<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AchFinancialDetails {
    Aba(AbaDetails),
    Swift(SwiftDetails),
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct StripeFinancialInformation {
    pub iban: Option<SepaFinancialDetails>,
    pub sort_code: Option<BacsFinancialDetails>,
    pub supported_networks: Vec<String>,
    #[serde(rename = "type")]
    pub financial_info_type: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct AchFinancialInformation {
    #[serde(flatten)]
    pub financial_details: AchFinancialDetails,
    pub supported_networks: Vec<String>,
    #[serde(rename = "type")]
    pub financial_info_type: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SepaFinancialDetails {
    pub account_holder_name: Secret<String>,
    pub bic: Secret<String>,
    pub country: Secret<String>,
    pub iban: Secret<String>,
    pub reference: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct BacsFinancialDetails {
    pub account_holder_name: Secret<String>,
    pub account_number: Secret<String>,
    pub sort_code: Secret<String>,
}

// REFUND :
// Type definition for Stripe RefundRequest

#[derive(Debug, Serialize)]
pub struct RefundRequest {
    pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer
    pub payment_intent: String,
    #[serde(flatten)]
    pub meta_data: StripeMetadata,
}

impl<F> TryFrom<(&RefundsRouterData<F>, MinorUnit)> for RefundRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        (item, refund_amount): (&RefundsRouterData<F>, MinorUnit),
    ) -> Result<Self, Self::Error> {
        let payment_intent = item.request.connector_transaction_id.clone();
        Ok(Self {
            amount: Some(refund_amount),
            payment_intent,
            meta_data: StripeMetadata {
                order_id: Some(item.request.refund_id.clone()),
                is_refund_id_as_reference: Some("true".to_string()),
            },
        })
    }
}

#[derive(Debug, Serialize)]
pub struct ChargeRefundRequest {
    pub charge: String,
    pub refund_application_fee: Option<bool>,
    pub reverse_transfer: Option<bool>,
    pub amount: Option<MinorUnit>, //amount in cents, hence passed as integer
    #[serde(flatten)]
    pub meta_data: StripeMetadata,
}

impl<F> TryFrom<&RefundsRouterData<F>> for ChargeRefundRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
        let amount = item.request.minor_refund_amount;
        match item.request.split_refunds.as_ref() {
            None => Err(ConnectorError::MissingRequiredField {
                field_name: "split_refunds",
            }
            .into()),

            Some(split_refunds) => match split_refunds {
                SplitRefundsRequest::StripeSplitRefund(stripe_refund) => {
                    let (refund_application_fee, reverse_transfer) = match &stripe_refund.options {
                        ChargeRefundsOptions::Direct(DirectChargeRefund {
                            revert_platform_fee,
                        }) => (Some(*revert_platform_fee), None),
                        ChargeRefundsOptions::Destination(DestinationChargeRefund {
                            revert_platform_fee,
                            revert_transfer,
                        }) => (Some(*revert_platform_fee), Some(*revert_transfer)),
                    };

                    Ok(Self {
                        charge: stripe_refund.charge_id.clone(),
                        refund_application_fee,
                        reverse_transfer,
                        amount: Some(amount),
                        meta_data: StripeMetadata {
                            order_id: Some(item.request.refund_id.clone()),
                            is_refund_id_as_reference: Some("true".to_string()),
                        },
                    })
                }
                _ => Err(ConnectorError::MissingRequiredField {
                    field_name: "stripe_split_refund",
                })?,
            },
        }
    }
}

// Type definition for Stripe Refund Response

#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum RefundStatus {
    Succeeded,
    Failed,
    #[default]
    Pending,
    RequiresAction,
}

impl From<RefundStatus> for enums::RefundStatus {
    fn from(item: RefundStatus) -> Self {
        match item {
            RefundStatus::Succeeded => Self::Success,
            RefundStatus::Failed => Self::Failure,
            RefundStatus::Pending => Self::Pending,
            RefundStatus::RequiresAction => Self::ManualReview,
        }
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
    pub id: String,
    pub object: String,
    pub amount: MinorUnit,
    pub currency: String,
    pub metadata: StripeMetadata,
    pub payment_intent: String,
    pub status: RefundStatus,
    pub failure_reason: Option<String>,
}

impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: RefundsResponseRouterData<Execute, RefundResponse>,
    ) -> Result<Self, Self::Error> {
        let refund_status = enums::RefundStatus::from(item.response.status);
        let response = if is_refund_failure(refund_status) {
            Err(hyperswitch_domain_models::router_data::ErrorResponse {
                code: consts::NO_ERROR_CODE.to_string(),
                message: item
                    .response
                    .failure_reason
                    .clone()
                    .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
                reason: item.response.failure_reason,
                status_code: item.http_code,
                attempt_status: None,
                connector_transaction_id: Some(item.response.id),
                network_advice_code: None,
                network_decline_code: None,
                network_error_message: None,
                connector_metadata: None,
            })
        } else {
            Ok(RefundsResponseData {
                connector_refund_id: item.response.id,
                refund_status,
            })
        };

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

impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(
        item: RefundsResponseRouterData<RSync, RefundResponse>,
    ) -> Result<Self, Self::Error> {
        let refund_status = enums::RefundStatus::from(item.response.status);
        let response = if is_refund_failure(refund_status) {
            Err(hyperswitch_domain_models::router_data::ErrorResponse {
                code: consts::NO_ERROR_CODE.to_string(),
                message: item
                    .response
                    .failure_reason
                    .clone()
                    .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
                reason: item.response.failure_reason,
                status_code: item.http_code,
                attempt_status: None,
                connector_transaction_id: Some(item.response.id),
                network_advice_code: None,
                network_decline_code: None,
                network_error_message: None,
                connector_metadata: None,
            })
        } else {
            Ok(RefundsResponseData {
                connector_refund_id: item.response.id,
                refund_status,
            })
        };

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

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ErrorDetails {
    pub code: Option<String>,
    #[serde(rename = "type")]
    pub error_type: Option<String>,
    pub message: Option<String>,
    pub param: Option<String>,
    pub decline_code: Option<String>,
    pub payment_intent: Option<PaymentIntentErrorResponse>,
    pub network_advice_code: Option<String>,
    pub network_decline_code: Option<String>,
    pub advice_code: Option<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentIntentErrorResponse {
    pub id: String,
}

#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct ErrorResponse {
    pub error: ErrorDetails,
}

#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct StripeShippingAddress {
    #[serde(rename = "shipping[address][city]")]
    pub city: Option<String>,
    #[serde(rename = "shipping[address][country]")]
    pub country: Option<api_enums::CountryAlpha2>,
    #[serde(rename = "shipping[address][line1]")]
    pub line1: Option<Secret<String>>,
    #[serde(rename = "shipping[address][line2]")]
    pub line2: Option<Secret<String>>,
    #[serde(rename = "shipping[address][postal_code]")]
    pub zip: Option<Secret<String>>,
    #[serde(rename = "shipping[address][state]")]
    pub state: Option<Secret<String>>,
    #[serde(rename = "shipping[name]")]
    pub name: Option<Secret<String>>,
    #[serde(rename = "shipping[phone]")]
    pub phone: Option<Secret<String>>,
}

#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize)]
pub struct StripeBillingAddress {
    #[serde(rename = "payment_method_data[billing_details][email]")]
    pub email: Option<Email>,
    #[serde(rename = "payment_method_data[billing_details][address][country]")]
    pub country: Option<api_enums::CountryAlpha2>,
    #[serde(rename = "payment_method_data[billing_details][name]")]
    pub name: Option<Secret<String>>,
    #[serde(rename = "payment_method_data[billing_details][address][city]")]
    pub city: Option<String>,
    #[serde(rename = "payment_method_data[billing_details][address][line1]")]
    pub address_line1: Option<Secret<String>>,
    #[serde(rename = "payment_method_data[billing_details][address][line2]")]
    pub address_line2: Option<Secret<String>>,
    #[serde(rename = "payment_method_data[billing_details][address][postal_code]")]
    pub zip_code: Option<Secret<String>>,
    #[serde(rename = "payment_method_data[billing_details][address][state]")]
    pub state: Option<Secret<String>>,
    #[serde(rename = "payment_method_data[billing_details][phone]")]
    pub phone: Option<Secret<String>>,
}

#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct StripeRedirectResponse {
    pub payment_intent: Option<String>,
    pub payment_intent_client_secret: Option<Secret<String>>,
    pub source_redirect_slug: Option<String>,
    pub redirect_status: Option<StripePaymentStatus>,
    pub source_type: Option<Secret<String>>,
}

#[derive(Debug, Serialize)]
pub struct CancelRequest {
    cancellation_reason: Option<String>,
}

impl TryFrom<&PaymentsCancelRouterData> for CancelRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
        Ok(Self {
            cancellation_reason: item.request.cancellation_reason.clone(),
        })
    }
}

#[derive(Debug, Serialize)]
pub struct UpdateMetadataRequest {
    #[serde(flatten)]
    pub metadata: HashMap<String, String>,
}

impl TryFrom<&PaymentsUpdateMetadataRouterData> for UpdateMetadataRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(item: &PaymentsUpdateMetadataRouterData) -> Result<Self, Self::Error> {
        let metadata = format_metadata_for_request(item.request.metadata.clone());
        Ok(Self { metadata })
    }
}

fn format_metadata_for_request(merchant_metadata: Secret<Value>) -> HashMap<String, String> {
    let mut formatted_metadata = HashMap::new();
    if let Value::Object(metadata_map) = merchant_metadata.expose() {
        for (key, value) in metadata_map {
            formatted_metadata.insert(format!("metadata[{key}]"), value.to_string());
        }
    }
    formatted_metadata
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
pub enum StripePaymentMethodOptions {
    Card {
        mandate_options: Option<StripeMandateOptions>,
        #[serde(rename = "payment_method_options[card][network_transaction_id]")]
        network_transaction_id: Option<Secret<String>>,
        #[serde(flatten)]
        mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns
    },
    Klarna {},
    Affirm {},
    AfterpayClearpay {},
    AmazonPay {},
    Eps {},
    Giropay {},
    Ideal {},
    Sofort {},
    #[serde(rename = "us_bank_account")]
    Ach {},
    #[serde(rename = "sepa_debit")]
    Sepa {},
    #[serde(rename = "au_becs_debit")]
    Becs {},
    #[serde(rename = "bacs_debit")]
    Bacs {},
    Bancontact {},
    WechatPay {},
    Alipay {},
    #[serde(rename = "p24")]
    Przelewy24 {},
    CustomerBalance {},
    Multibanco {},
    Blik {},
    Cashapp {},
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct MitExemption {
    #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")]
    pub network_transaction_id: Secret<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum LatestAttempt {
    PaymentIntentAttempt(Box<LatestPaymentAttempt>),
    SetupAttempt(String),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct LatestPaymentAttempt {
    pub payment_method_options: Option<StripePaymentMethodOptions>,
    pub payment_method_details: Option<StripePaymentMethodDetailsResponse>,
}

// #[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
// pub struct Card
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
pub struct StripeMandateOptions {
    reference: Secret<String>, // Extendable, But only important field to be captured
}
/// Represents the capture request body for stripe connector.
#[derive(Debug, Serialize, Clone, Copy)]
pub struct CaptureRequest {
    /// If amount_to_capture is None stripe captures the amount in the payment intent.
    amount_to_capture: Option<MinorUnit>,
}

impl TryFrom<MinorUnit> for CaptureRequest {
    type Error = error_stack::Report<ConnectorError>;
    fn try_from(capture_amount: MinorUnit) -> Result<Self, Self::Error> {
        Ok(Self {
            amount_to_capture: Some(capture_amount),
        })
    }
}


Documentation: docs/CONTRIBUTING.md
# Type: Doc File

# Contributing to hyperswitch

:tada: First off, thanks for taking the time to contribute!
We are so happy to have you! :tada:

There are opportunities to contribute to hyperswitch at any level.
It doesn't matter if you are just getting started with Rust or are the most
weathered expert, we can use your help.

**No contribution is too small and all contributions are valued.**

This guide will help you get started.
**Do not let this guide intimidate you.**
It should be considered a map to help you navigate the process.

You can also get help with contributing on our [Discord server][discord],
[Slack workspace][slack], or [Discussions][discussions] space.
Please join us!

[discord]: https://discord.gg/wJZ7DVW8mm
[slack]: https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2awm23agh-p_G5xNpziv6yAiedTkkqLg
[discussions]: https://github.com/juspay/hyperswitch/discussions

## Table of Contents

- [Code of Conduct](#code-of-conduct)
- [What's Included?](#whats-included)
  - [Repositories](#repositories)
  - [Files Tree Layout](#files-tree-layout)
- [Contributing in Issues](#contributing-in-issues)
  - [Asking for General Help](#asking-for-general-help)
  - [Submitting a Bug Report](#submitting-a-bug-report)
  - [Triaging a Bug Report](#triaging-a-bug-report)
  - [Resolving a Bug Report](#resolving-a-bug-report)
- [Pull Requests](#pull-requests)
  - [Cargo Commands](#cargo-commands)
  - [Code Coverage](#code-coverage)
  - [Commits](#commits)
  - [Opening the Pull Request](#opening-the-pull-request)
  - [Discuss and update](#discuss-and-update)
  - [Commit Squashing](#commit-squashing)
- [Reviewing Pull Requests](#reviewing-pull-requests)
  - [Review a bit at a time](#review-a-bit-at-a-time)
  - [Be aware of the person behind the code](#be-aware-of-the-person-behind-the-code)
  - [Abandoned or Stalled Pull Requests](#abandoned-or-stalled-pull-requests)
- [Keeping track of issues and PRs](#keeping-track-of-issues-and-prs)
  - [Area](#area)
  - [Category](#category)
  - [Calls for participation](#calls-for-participation)
  - [Metadata](#metadata)
  - [Priority](#priority)
  - [RFCs](#rfcs)
  - [Status](#status)

## Code of Conduct

The hyperswitch project adheres to the [Rust Code of Conduct][coc].
This describes the _minimum_ behavior expected from all contributors.

[coc]: https://www.rust-lang.org/policies/code-of-conduct

## What's Included❓

### Repositories
The current setup contains three different repositories, corresponding to the different Hyperswitch components.

- [App Server][app-server] - The core payments engine responsible for managing payment flows, payment unification and smart routing. App server is maintained in this repo itself.

- [Web Client (SDK)][web-client] - An inclusive, consistent and blended payment experience optimized for the best payment conversions.

- [Control center][control-center] - A dashboard for payment analytics and operations, managing payment processors or payment methods and configuring payment routing rules.

[app-server]: https://github.com/juspay/hyperswitch
[web-client]: https://github.com/juspay/hyperswitch-web
[control-center]: https://github.com/juspay/hyperswitch-control-center

### Files Tree Layout

Within the repositories, you'll find the following directories and files,
logically grouping common assets and providing both compiled and minified
variations.

<!-- FIXME: this table should either be generated by a script or smoke test
should be introduced, checking it agrees with the actual structure -->

```text
.
├── config                             : Initial startup config files for the router
├── connector-template                 : boilerplate code for connectors
├── crates                             : sub-crates
│   ├── api_models                     : Request/response models for the `router` crate
│   ├── cards                          : Types to handle card masking and validation
│   ├── common_enums                   : Enums shared across the request/response types and database types
│   ├── common_utils                   : Utilities shared across `router` and other crates
│   ├── data_models                    : Represents the data/domain models used by the business/domain layer
│   ├── diesel_models                  : Database models shared across `router` and other crates
│   ├── drainer                        : Application that reads Redis streams and executes queries in database
│   ├── external_services              : Interactions with external systems like emails, AWS KMS, etc.
│   ├── masking                        : Personal Identifiable Information protection
│   ├── redis_interface                : A user-friendly interface to Redis
│   ├── router                         : Main crate of the project
│   ├── router_derive                  : Utility macros for the `router` crate
│   ├── router_env                     : Environment of payment router: logger, basic config, its environment awareness
│   ├── scheduler                      : Scheduling and executing deferred tasks like mail scheduling
│   ├── storage_impl                   : Storage backend implementations for data structures & objects
│   └── test_utils                     : Utilities to run Postman and connector UI tests
├── docs                               : hand-written documentation
├── loadtest                           : performance benchmarking setup
├── migrations                         : diesel DB setup
├── monitoring                         : Grafana & Loki monitoring related configuration files
├── openapi                            : automatically generated OpenAPI spec
├── postman                            : postman scenarios API
└── scripts                            : automation, testing, and other utility scripts
```

## Contributing in Issues

For any issue, there are fundamentally three ways an individual can contribute:

1. By opening the issue for discussion: For instance, if you believe that you
   have discovered a bug in hyperswitch, creating a new issue in [the
   juspay/hyperswitch issue tracker][issue] is the way to report it.

2. By helping to triage the issue: This can be done by providing supporting
   details (a test case that demonstrates a bug), providing suggestions on how
   to address the issue, or ensuring that the issue is tagged correctly.

3. By helping to resolve the issue: Typically this is done either in the form of
   demonstrating that the issue reported is not a problem after all, or more
   often, by opening a Pull Request that changes some bit of something in
   hyperswitch in a concrete and reviewable manner.

[issue]: https://github.com/juspay/hyperswitch/issues

**Anybody can participate in any stage of contribution**.
We urge you to participate in the discussion around bugs and participate in
reviewing PRs.

### Asking for General Help

If you have reviewed existing documentation and still have questions or are
having problems, you can [open a discussion] asking for help.

In exchange for receiving help, we ask that you contribute back a documentation
PR that helps others avoid the problems that you encountered.

[open a discussion]: https://github.com/juspay/hyperswitch/discussions/new/choose

### Submitting a Bug Report

When opening a new issue in the hyperswitch issue tracker, you will be presented
with a basic template that should be filled in.
If you believe that you have uncovered a bug, please fill out this form,
following the template to the best of your ability.
Do not worry if you cannot answer every detail, just fill in what you can.

The two most important pieces of information we need in order to properly
evaluate the report is a description of the behavior you are seeing and a simple
test case we can use to recreate the problem on our own.
If we cannot recreate the issue, it becomes impossible for us to fix.

See [How to create a Minimal, Complete, and Verifiable example][mcve].

[mcve]: https://stackoverflow.com/help/mcve

### Triaging a Bug Report

Once an issue has been opened, it is not uncommon for there to be discussion
around it.
Some contributors may have differing opinions about the issue, including whether
the behavior being seen is a bug or a feature.
This discussion is part of the process and should be kept focused, helpful, and
professional.

Short, clipped responses — that provide neither additional context nor
supporting detail — are not helpful or professional.
To many, such responses are simply annoying and unfriendly.

Contributors are encouraged to help one another make forward progress as much as
possible, empowering one another to solve issues collaboratively.
If you choose to comment on an issue that you feel either is not a problem that
needs to be fixed, or if you encounter information in an issue that you feel is
incorrect, explain why you feel that way with additional supporting context, and
be willing to be convinced that you may be wrong.
By doing so, we can often reach the correct outcome much faster.

### Resolving a Bug Report

In the majority of cases, issues are resolved by opening a Pull Request.
The process for opening and reviewing a Pull Request is similar to that of
opening and triaging issues, but carries with it a necessary review and approval
workflow that ensures that the proposed changes meet the minimal quality and
functional guidelines of the hyperswitch project.

## Pull Requests

Pull Requests are the way concrete changes are made to the code, documentation,
and dependencies in the hyperswitch repository.

Even tiny pull requests (e.g., one character pull request fixing a typo in API
documentation) are greatly appreciated.
Before making a large change, it is usually a good idea to first open an issue
describing the change to solicit feedback and guidance.
This will increase the likelihood of the PR getting merged.

### Cargo Commands

Due to the extensive use of features in hyperswitch, you will often need to add
extra arguments to many common cargo commands.
This section lists some commonly needed commands.

Some commands just need the `--all-features` argument:

```shell
cargo check --all-features
cargo clippy --all-features
cargo test --all-features
```

The `cargo fmt` command requires the nightly toolchain, as we use a few of the
unstable features:

```shell
cargo +nightly fmt
```

### Code Coverage

We appreciate well-tested code, so feel free to add tests when you can.

To generate code coverage using the cypress tests, follow these steps:

0. Make sure `grcov` and `llvm-tools-preview` are installed

   ```shell
   rustup component add llvm-tools-preview
   cargo install grcov
   ```

1. Build the project with the `-Cinstrument-coverage` flag:

   ```shell
   RUSTFLAGS="-Cinstrument-coverage" cargo build --bin=router --package=router
   ```

   Several `.profraw` files will be generated. (Due to the execution of build scripts)

2. Execute the binary:

   ```shell
   LLVM_PROFILE_FILE="coverage.profraw" target/debug/router
   ```

3. Open a separate terminal tab and run the cypress tests, following the [README][cypress-v2-readme]

4. After the tests have finished running, stop the `router` process using `Ctrl+C`

   The generated `coverage.profraw` file will contain the code coverage data for `router`

5. Generate an html report from the data:

   ```shell
   grcov . --source-dir . --output-type html --binary-path ./target/debug
   ```

6. A folder named `html` will be generated, containing the report. You can view it using:

   ```shell
   cd html && python3 -m http.server 8000
   ```

7. You can delete the generated `.profraw` files:

   ```shell
   rm **/*.profraw
   ```

Note:
- It is necessary to stop the `router` process to generate the coverage file
- Branch coverage generation requires nightly and currently `grcov` crashes while trying to include branch coverage. (Checked using `--log-level` parameter in `grcov`)

#### Integration with VSCode
You can also visualize code coverage in VSCode using the [coverage-gutters](https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters) extension.

You need to generate an `lcov.info` file in the directory root. After following till step 4 above:

```shell
grcov . -s . -t lcov --output-path lcov.info --binary-path ./target/debug --keep-only "crates/*"
```

This will generate an `lcov.info` file that can be read by the extension.

[cypress-v2-readme]: /cypress-tests-v2/README.md

### Commits

It is a recommended best practice to keep your changes as logically grouped as
possible within individual commits.
There is no limit to the number of commits any single Pull Request may have, and
many contributors find it easier to review changes that are split across
multiple commits.

Please adhere to the general guideline that you should never force push to a
publicly shared branch.
Once you have opened your pull request, you should consider your branch publicly shared.
Instead of force pushing you can just add incremental commits;
this is generally easier on your reviewers.
If you need to pick up changes from main, you can merge main into your branch.

A reviewer might ask you to rebase a long-running pull request
in which case force pushing is okay for that request.

Note that squashing at the end of the review process should also not be done,
that can be done when the pull request is integrated via GitHub.

#### Commit message guidelines

Each commit message consists of a header, an optional body, and an optional
footer.

```text
<header>
<BLANK LINE>
<optional body>
<BLANK LINE>
<optional footer>
```

The `header` is mandatory and must conform to the
[commit message header](#commit-message-header) format.

The `body` is optional.
When the body is present it must be at least 20 characters long and must conform
to the [commit message body](#commit-message-body) format.

The `footer` is optional.
The [commit message footer](#commit-message-footer) format describes what the
footer is used for and the structure it must have.

##### Commit message header

```text
<type>(<scope>): <short summary>
│         │             │
│         │             └── Summary in present tense.
|         |                 Not capitalized.
|         |                 No period at the end.
│         │
│         └── Commit Scope: crate name | changelog | config | migrations
|                           | openapi | postman
│
└── Commit Type: build | chore | ci | docs | feat | fix | perf | refactor | test
```

The `<type>` and `<summary>` fields are mandatory, the (`<scope>`) field is
optional.

`<type>` must be one of the following:

- `build`: Changes that affect the build system or external dependencies
  (example scopes: `deps`, `dev-deps`, `metadata`)
- `chore`: Changes such as fixing formatting or addressing warnings or lints, or
  other maintenance changes
- `ci`: Changes to our CI configuration files and scripts (examples: `workflows`,
  `dependabot`, `renovate`)
- `docs`: Documentation only changes
- `feat`: A new feature
- `fix`: A bug fix
- `perf`: A code change that improves performance
- `refactor`: A code change that neither fixes a bug nor adds a feature
- `test`: Adding missing tests or correcting existing tests

`<scope>` should be the name of the crate affected (as perceived by the person
reading the changelog generated from commit messages).
The scope can be more specific if the changes are targeted towards the main
crate in the repository (`router`).

The following is the list of supported scopes:

- `masking`
- `router`
- `router_derive`
- `router_env`

There are currently a few exceptions to the "use crate name" rule:

- `changelog`: Used for updating the release notes in the `CHANGELOG.md` file.
  Commonly used with the `docs` commit type
  (e.g. `docs(changelog): generate release notes for v0.4.0 release`).
- `config`: Used for changes which affect the configuration files of any of the
  services.
- `migrations`: Used for changes to the database migration scripts.
- `openapi`: Used for changes to the OpenAPI specification file.
- `postman`: Used for changes to the Postman collection file.
- none/empty string: Useful for test and refactor changes that are done across
  all crates (e.g. `test: add missing unit tests`) and for docs changes that are
  not related to a specific crate (e.g. `docs: fix typo in tutorial`).

Use the `<summary>` field to provide a succinct description of the change:

- Use the imperative, present tense: "change" not "changed" nor "changes".
- Don't capitalize the first letter.
- No period (.) at the end.

##### Commit message body

Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor
"fixes".

Explain the motivation for the change in the commit message body.
This commit message should explain why you are making the change.
You can include a comparison of the previous behavior with the new behavior in
order to illustrate the impact of the change.

##### Commit message footer

The footer can contain information about breaking changes and deprecations and
is also the place to reference GitHub issues, Jira tickets, and other PRs that
this commit closes or is related to.
For example:

```text
BREAKING CHANGE: <breaking change summary>
<BLANK LINE>
<breaking change description + migration instructions>
<BLANK LINE>
<BLANK LINE>
Fixes #<issue number>
```

or

```text
DEPRECATED: <what is deprecated>
<BLANK LINE>
<deprecation description + recommended update path>
<BLANK LINE>
<BLANK LINE>
Closes #<PR number>
```

Breaking Change section should start with the phrase "BREAKING CHANGE: "
followed by a summary of the breaking change, a blank line, and a detailed
description of the breaking change that also includes migration instructions.

Similarly, a Deprecation section should start with "DEPRECATED: " followed by a
short description of what is deprecated, a blank line, and a detailed
description of the deprecation that also mentions the recommended update path.

If the commit reverts a previous commit, it should begin with `revert:`,
followed by the header of the reverted commit.
The content of the commit message body should contain:

- Information about the SHA of the commit being reverted in the following
  format: `This reverts commit <SHA>`.
- A clear description of the reason for reverting the commit message.

Sample commit messages:

1. ```text
   feat(router): add 3ds support to payments core flow

   Implement Redirection flow support. This can be used by any flow that
   requires redirection.

   Fixes #123
   ```

2. ```text
   chore: run formatter
   ```

3. ```text
   fix(config): fix binary name displayed in help message
   ```

_Adapted from the [Angular Commit Message convention][angular commit message]._

[angular commit message]: https://github.com/angular/angular/blob/d684148f93837cf0e4e37146a8df17dc70403558/CONTRIBUTING.md#-commit-message-format

### Opening the Pull Request

From within GitHub, opening a new Pull Request will present you with a
[template] that should be filled out. Please try to do your best at filling out
the details, but feel free to skip parts if you're not sure what to put.

[template]: /.github/PULL_REQUEST_TEMPLATE.md

### Discuss and update

You will probably get feedback or requests for changes to your Pull Request.
This is a big part of the submission process so don't be discouraged!
Some contributors may sign off on the Pull Request right away, others may have
more detailed comments or feedback.
This is a necessary part of the process in order to evaluate whether the changes
are correct and necessary.

**Any community member can review a PR and you might get conflicting feedback**.
Keep an eye out for comments from code owners to provide guidance on conflicting
feedback.

**Once the PR is open, do not rebase the commits**.
See [Commit Squashing](#commit-squashing) for more details.

### Commit Squashing

In most cases, **do not squash commits that you add to your Pull Request during
the review process**.
When the commits in your Pull Request land, they may be squashed into one commit
per logical change.
Metadata will be added to the commit message (including links to the Pull
Request, links to relevant issues, and the names of the reviewers).
The commit history of your Pull Request, however, will stay intact on the Pull
Request page.

## Reviewing Pull Requests

**Any hyperswitch community member is welcome to review any pull request**.

All hyperswitch contributors who choose to review and provide feedback on Pull
Requests have a responsibility to both the project and the individual making the
contribution.
Reviews and feedback must be helpful, insightful, and geared towards improving
the contribution as opposed to simply blocking it.
If there are reasons why you feel the PR should not land, explain what those are.
Do not expect to be able to block a Pull Request from advancing simply because
you say "No" without giving an explanation.
Be open to having your mind changed.
Be open to working with the contributor to make the Pull Request better.

Reviews that are dismissive or disrespectful of the contributor or any other
reviewers are strictly counter to the Code of Conduct.

When reviewing a Pull Request, the primary goals are for the codebase to improve
and for the person submitting the request to succeed.
**Even if a Pull Request does not land, the submitters should come away from the
experience feeling like their effort was not wasted or unappreciated**.
Every Pull Request from a new contributor is an opportunity to grow the
community.

### Review a bit at a time

Do not overwhelm new contributors.

It is tempting to micro-optimize and make everything about relative performance,
perfect grammar, or exact style matches.
Do not succumb to that temptation.

Focus first on the most significant aspects of the change:

1. Does this change make sense for hyperswitch?
2. Does this change make hyperswitch better, even if only incrementally?
3. Are there clear bugs or larger scale issues that need attending to?
4. Is the commit message readable and correct?
   If it contains a breaking change is it clear enough?

Note that only **incremental** improvement is needed to land a PR.
This means that the PR does not need to be perfect, only better than the status
quo.
Follow up PRs may be opened to continue iterating.

When changes are necessary, _request_ them, do not _demand_ them, and **do not
assume that the submitter already knows how to add a test or run a benchmark**.

Specific performance optimization techniques, coding styles and conventions
change over time.
The first impression you give to a new contributor never does.

Nits (requests for small changes that are not essential) are fine, but try to
avoid stalling the Pull Request.
Most nits can typically be fixed by the hyperswitch collaborator landing the
Pull Request but they can also be an opportunity for the contributor to learn a
bit more about the project.

It is always good to clearly indicate nits when you comment: e.g.
`Nit: change foo() to bar(). But this is not blocking.`

If your comments were addressed but were not folded automatically after new
commits or if they proved to be mistaken, please, [hide them][hiding-a-comment]
with the appropriate reason to keep the conversation flow concise and relevant.

### Be aware of the person behind the code

Be aware that _how_ you communicate requests and reviews in your feedback can
have a significant impact on the success of the Pull Request.
Yes, we may land a particular change that makes hyperswitch better, but the
individual might just not want to have anything to do with hyperswitch ever
again.
The goal is not just having good code.

### Abandoned or Stalled Pull Requests

If a Pull Request appears to be abandoned or stalled, it is polite to first
check with the contributor to see if they intend to continue the work before
checking if they would mind if you took it over (especially if it just has nits
left).
When doing so, it is courteous to give the original contributor credit for the
work they started (either by preserving their name and email address in the
commit log, or by using an `Author:` meta-data tag in the commit.

_Adapted from the [Node.js contributing guide][node]_.

[node]: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md
[hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment

## Keeping track of issues and PRs

The hyperswitch GitHub repository has a lot of issues and PRs to keep track of.
This section explains the meaning of various labels, as well as our [GitHub
project][project].
The section is primarily targeted at maintainers.
Most contributors aren't able to set these labels.

### Area

The area label describes the area relevant to this issue or PR.

- **A-CI-CD**: This issue/PR concerns our CI/CD setup.
- **A-connector-compatibility**: This issue/PR concerns connector compatibility
  code.
- **A-connector-integration**: This issue/PR concerns connector integrations.
- **A-core**: This issue/PR concerns the core flows.
- **A-dependencies**: The issue/PR concerns one or more of our dependencies.
- **A-drainer**: The issue/PR concerns the drainer code.
- **A-errors**: The issue/PR concerns error messages, error structure or error
  logging.
- **A-framework**: The issue/PR concerns code to interact with other systems or
  services such as database, Redis, connector APIs, etc.
- **A-infra**: This issue/PR concerns deployments, Dockerfiles, Docker Compose
  files, etc.
- **A-macros**: This issue/PR concerns the `router_derive` crate.
- **A-payment-methods**: This issue/PR concerns the integration of new or
  existing payment methods.
- **A-process-tracker**: This issue/PR concerns the process tracker code.

### Category

- **C-bug**: This issue is a bug report or this PR is a bug fix.
- **C-doc**: This issue/PR concerns changes to the documentation.
- **C-feature**: This issue is a feature request or this PR adds new features.
- **C-refactor**: This issue/PR concerns a refactor of existing behavior.
- **C-tracking-issue**: This is a tracking issue for a proposal or for a
  category of bugs.

### Calls for participation

- **E-easy**: This is easy, ranging from quick documentation fixes to stuff you
  can do after getting a basic idea about our product.
- **E-medium**: This is not `E-easy` or `E-hard`.
- **E-hard**: This either involves very tricky code, is something we don't know
  how to solve, or is difficult for some other reason.

### Metadata

The metadata label describes additional metadata that are important for sandbox
or production deployments of our application.

- **M-api-contract-changes**: This PR involves API contract changes.
- **M-configuration-changes**: This PR involves configuration changes.
- **M-database-changes**: This PR involves database schema changes.

### Priority

- **P-low**: This is a low priority issue.
- **P-medium**: This is not `P-low` or `P-high`.
- **P-high**: This is a high priority issue and must be addressed quickly.

### RFCs

- **RFC-in-progress**: This RFC involves active discussion regarding substantial
  design changes.
- **RFC-resolved**: This RFC has been resolved.

### Status

The status label provides information about the status of the issue or PR.

- **S-awaiting-triage**: This issue or PR is relatively new and has not been
  addressed yet.
- **S-blocked**: This issue or PR is blocked on something else, or other
  implementation work.
- **S-design**: This issue or PR involves a problem without an obvious solution;
  or the proposed solution raises other questions.
- **S-in-progress**: The implementation relevant to this issue/PR is underway.
- **S-invalid**: This is an invalid issue.
- **S-needs-conflict-resolution**: This PR requires merge conflicts to be
  resolved by the author.
- **S-needs-reproduction-steps**: This behavior hasn't been reproduced by the
  team.
- **S-unactionable**: There is not enough information to act on this problem.
- **S-unassigned**: This issue has no one assigned to address it.
- **S-waiting-on-author**: This PR is incomplete or the author needs to address
  review comments.
- **S-waiting-on-reporter**: Awaiting response from the issue author.
- **S-waiting-on-review**: This PR has been implemented and needs to be reviewed.
- **S-wont-fix**: The proposal in this issue was rejected and will not be
  implemented.

Any label not listed here is not in active use.

[project]: https://github.com/orgs/juspay/projects/3


pub struct KakaoPayRedirection {}


pub fn get_resources_set(&self) -> HashSet<Resource> {
        self.get_permission_groups()
            .iter()
            .flat_map(|group| group.resources())
            .collect()
    }


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

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


pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo {
        MerchantConnectorInfo {
            connector_label: connector_label.to_string(),
            merchant_connector_id: self.id.clone(),
        }
    }


pub struct DwollaAuthType {
    pub(super) client_id: Secret<String>,
    pub(super) client_secret: Secret<String>,
}


File: crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs

use std::collections::HashSet;

use api_models::analytics::{
    refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
    Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;

use super::RefundMetricRow;
use crate::{
    enums::AuthInfo,
    query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
    types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct RefundSuccessRate {}

#[async_trait::async_trait]
impl<T> super::RefundMetric<T> for RefundSuccessRate
where
    T: AnalyticsDataSource + super::RefundMetricAnalytics,
    PrimitiveDateTime: ToSql<T>,
    AnalyticsCollection: ToSql<T>,
    Granularity: GroupByClause<T>,
    Aggregate<&'static str>: ToSql<T>,
    Window<&'static str>: ToSql<T>,
{
    async fn load_metrics(
        &self,
        dimensions: &[RefundDimensions],
        auth: &AuthInfo,
        filters: &RefundFilters,
        granularity: Option<Granularity>,
        time_range: &TimeRange,
        pool: &T,
    ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
    where
        T: AnalyticsDataSource + super::RefundMetricAnalytics,
    {
        let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized);
        let mut dimensions = dimensions.to_vec();

        dimensions.push(RefundDimensions::RefundStatus);

        for dim in dimensions.iter() {
            query_builder.add_select_column(dim).switch()?;
        }

        query_builder
            .add_select_column(Aggregate::Count {
                field: None,
                alias: Some("count"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Min {
                field: "created_at",
                alias: Some("start_bucket"),
            })
            .switch()?;
        query_builder
            .add_select_column(Aggregate::Max {
                field: "created_at",
                alias: Some("end_bucket"),
            })
            .switch()?;

        filters.set_filter_clause(&mut query_builder).switch()?;

        auth.set_filter_clause(&mut query_builder).switch()?;

        time_range.set_filter_clause(&mut query_builder).switch()?;

        for dim in dimensions.iter() {
            query_builder.add_group_by_clause(dim).switch()?;
        }

        if let Some(granularity) = granularity {
            granularity
                .set_group_by_clause(&mut query_builder)
                .switch()?;
        }

        query_builder
            .execute_query::<RefundMetricRow, _>(pool)
            .await
            .change_context(MetricsError::QueryBuildingError)?
            .change_context(MetricsError::QueryExecutionFailure)?
            .into_iter()
            .map(|i| {
                Ok((
                    RefundMetricsBucketIdentifier::new(
                        i.currency.as_ref().map(|i| i.0),
                        None,
                        i.connector.clone(),
                        i.refund_type.as_ref().map(|i| i.0.to_string()),
                        i.profile_id.clone(),
                        i.refund_reason.clone(),
                        i.refund_error_message.clone(),
                        TimeRange {
                            start_time: match (granularity, i.start_bucket) {
                                (Some(g), Some(st)) => g.clip_to_start(st)?,
                                _ => time_range.start_time,
                            },
                            end_time: granularity.as_ref().map_or_else(
                                || Ok(time_range.end_time),
                                |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
                            )?,
                        },
                    ),
                    i,
                ))
            })
            .collect::<error_stack::Result<
                HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
                crate::query::PostProcessingError,
            >>()
            .change_context(MetricsError::PostProcessingFailure)
    }
}


File: crates/masking/src/maskable.rs
 Public functions: 5

//! This module contains Masking objects and traits

use crate::{ExposeInterface, Secret};

/// An Enum that allows us to optionally mask data, based on which enum variant that data is stored
/// in.
#[derive(Clone, Eq, PartialEq)]
pub enum Maskable<T: Eq + PartialEq + Clone> {
    /// Variant which masks the data by wrapping in a Secret
    Masked(Secret<T>),
    /// Varant which doesn't mask the data
    Normal(T),
}

impl<T: std::fmt::Debug + Clone + Eq + PartialEq> std::fmt::Debug for Maskable<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Masked(secret_value) => std::fmt::Debug::fmt(secret_value, f),
            Self::Normal(value) => std::fmt::Debug::fmt(value, f),
        }
    }
}

impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Self::Masked(value) => crate::PeekInterface::peek(value).hash(state),
            Self::Normal(value) => value.hash(state),
        }
    }
}

impl<T: Eq + PartialEq + Clone> Maskable<T> {
    /// Get the inner data while consuming self
    pub fn into_inner(self) -> T {
        match self {
            Self::Masked(inner_secret) => inner_secret.expose(),
            Self::Normal(inner) => inner,
        }
    }

    /// Create a new Masked data
    pub fn new_masked(item: Secret<T>) -> Self {
        Self::Masked(item)
    }

    /// Create a new non-masked data
    pub fn new_normal(item: T) -> Self {
        Self::Normal(item)
    }

    /// Checks whether the data is masked.
    /// Returns `true` if the data is wrapped in the `Masked` variant,
    /// returns `false` otherwise.
    pub fn is_masked(&self) -> bool {
        matches!(self, Self::Masked(_))
    }

    /// Checks whether the data is normal (not masked).
    /// Returns `true` if the data is wrapped in the `Normal` variant,
    /// returns `false` otherwise.
    pub fn is_normal(&self) -> bool {
        matches!(self, Self::Normal(_))
    }
}

/// Trait for providing a method on custom types for constructing `Maskable`
pub trait Mask {
    /// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone`
    type Output: Eq + Clone + PartialEq;

    /// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self`
    fn into_masked(self) -> Maskable<Self::Output>;
}

impl Mask for String {
    type Output = Self;
    fn into_masked(self) -> Maskable<Self::Output> {
        Maskable::new_masked(self.into())
    }
}

impl Mask for Secret<String> {
    type Output = String;
    fn into_masked(self) -> Maskable<Self::Output> {
        Maskable::new_masked(self)
    }
}

impl<T: Eq + PartialEq + Clone> From<T> for Maskable<T> {
    fn from(value: T) -> Self {
        Self::new_normal(value)
    }
}

impl From<&str> for Maskable<String> {
    fn from(value: &str) -> Self {
        Self::new_normal(value.to_string())
    }
}


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


pub async fn connect_account(
    state: SessionState,
    request: user_api::ConnectAccountRequest,
    auth_id: Option<String>,
    theme_id: Option<String>,
) -> UserResponse<user_api::ConnectAccountResponse> {
    let user_email = domain::UserEmail::from_pii_email(request.email.clone())?;

    utils::user::validate_email_domain_auth_type_using_db(
        &state,
        &user_email,
        UserAuthType::MagicLink,
    )
    .await?;

    let find_user = state.global_store.find_user_by_email(&user_email).await;

    if let Ok(found_user) = find_user {
        let user_from_db: domain::UserFromStorage = found_user.into();

        let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;

        let email_contents = email_types::MagicLink {
            recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
            settings: state.conf.clone(),
            user_name: domain::UserName::new(user_from_db.get_name())?,
            auth_id,
            theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
            theme_config: theme
                .map(|theme| theme.email_config())
                .unwrap_or(state.conf.theme.email_config.clone()),
        };

        let send_email_result = state
            .email_client
            .compose_and_send_email(
                user_utils::get_base_url(&state),
                Box::new(email_contents),
                state.conf.proxy.https_url.as_ref(),
            )
            .await;
        logger::info!(?send_email_result);

        Ok(ApplicationResponse::Json(
            user_api::ConnectAccountResponse {
                is_email_sent: send_email_result.is_ok(),
                user_id: user_from_db.get_user_id().to_string(),
            },
        ))
    } else if find_user
        .as_ref()
        .map_err(|e| e.current_context().is_db_not_found())
        .err()
        .unwrap_or(false)
    {
        if matches!(env::which(), env::Env::Production) {
            return Err(report!(UserErrors::InvalidCredentials));
        }

        let new_user = domain::NewUser::try_from(request)?;
        let _ = new_user
            .get_new_merchant()
            .get_new_organization()
            .insert_org_in_db(state.clone())
            .await?;
        let user_from_db = new_user
            .insert_user_and_merchant_in_db(state.clone())
            .await?;
        let _user_role = new_user
            .insert_org_level_user_role_in_db(
                state.clone(),
                common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
                UserStatus::Active,
            )
            .await?;

        let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;

        let magic_link_email = email_types::VerifyEmail {
            recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
            settings: state.conf.clone(),
            auth_id,
            theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
            theme_config: theme
                .map(|theme| theme.email_config())
                .unwrap_or(state.conf.theme.email_config.clone()),
        };

        let magic_link_result = state
            .email_client
            .compose_and_send_email(
                user_utils::get_base_url(&state),
                Box::new(magic_link_email),
                state.conf.proxy.https_url.as_ref(),
            )
            .await;

        logger::info!(?magic_link_result);

        if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT {
            let welcome_to_community_email = email_types::WelcomeToCommunity {
                recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
            };

            let welcome_email_result = state
                .email_client
                .compose_and_send_email(
                    user_utils::get_base_url(&state),
                    Box::new(welcome_to_community_email),
                    state.conf.proxy.https_url.as_ref(),
                )
                .await;

            logger::info!(?welcome_email_result);
        }

        Ok(ApplicationResponse::Json(
            user_api::ConnectAccountResponse {
                is_email_sent: magic_link_result.is_ok(),
                user_id: user_from_db.get_user_id().to_string(),
            },
        ))
    } else {
        Err(find_user
            .err()
            .map(|e| e.change_context(UserErrors::InternalServerError))
            .unwrap_or(UserErrors::InternalServerError.into()))
    }
}


pub struct NexinetsErrorResponse {
    pub status: u16,
    pub code: u16,
    pub message: String,
    pub errors: Vec<OrderErrorDetails>,
}


pub struct OrderLines {
    name: String,
    quantity: u16,
    unit_price: MinorUnit,
    total_amount: MinorUnit,
    total_tax_amount: Option<MinorUnit>,
    tax_rate: Option<f64>,
}


pub async fn proxy_confirm_intent(
    state: web::Data<app::AppState>,
    req: actix_web::HttpRequest,
    json_payload: web::Json<api_models::payments::ProxyPaymentsRequest>,
    path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> impl Responder {
    use hyperswitch_domain_models::payments::PaymentConfirmData;

    let flow = Flow::ProxyConfirmIntent;

    // Extract the payment ID from the path
    let global_payment_id = path.into_inner();
    tracing::Span::current().record("payment_id", global_payment_id.get_string_repr());

    // Parse and validate headers
    let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
        Ok(headers) => headers,
        Err(err) => {
            return api::log_and_return_error_response(err);
        }
    };

    // Prepare the internal payload
    let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
        global_payment_id,
        payload: json_payload.into_inner(),
    };

    // Determine the locking action, if required
    let locking_action = internal_payload.get_locking_input(flow.clone());

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        internal_payload,
        |state, auth: auth::AuthenticationData, req, req_state| {
            let payment_id = req.global_payment_id;
            let request = req.payload;

            // Define the operation for proxy payments intent
            let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;

            let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
                domain::Context(auth.merchant_account, auth.key_store),
            ));
            // Call the core proxy logic
            Box::pin(payments::proxy_for_payments_core::<
                api_types::Authorize,
                api_models::payments::PaymentsResponse,
                _,
                _,
                _,
                PaymentConfirmData<api_types::Authorize>,
            >(
                state,
                req_state,
                merchant_context,
                auth.profile,
                operation,
                request,
                payment_id,
                payments::CallConnectorAction::Trigger,
                header_payload.clone(),
                None,
            ))
        },
        &auth::V2ApiKeyAuth {
            is_connected_allowed: false,
            is_platform_allowed: false,
        },
        locking_action,
    ))
    .await
}


pub async fn log_refund(
        &self,
        refund: &Refund,
        old_refund: Option<Refund>,
        tenant_id: TenantID,
    ) -> MQResult<()> {
        if let Some(negative_event) = old_refund {
            self.log_event(&KafkaEvent::old(
                &KafkaRefund::from_storage(&negative_event),
                tenant_id.clone(),
                self.ckh_database_name.clone(),
            ))
            .attach_printable_lazy(|| {
                format!("Failed to add negative refund event {negative_event:?}")
            })?;
        };

        self.log_event(&KafkaEvent::new(
            &KafkaRefund::from_storage(refund),
            tenant_id.clone(),
            self.ckh_database_name.clone(),
        ))
        .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?;

        self.log_event(&KafkaConsolidatedEvent::new(
            &KafkaRefundEvent::from_storage(refund),
            tenant_id.clone(),
        ))
        .attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}"))
    }


File: crates/router/src/types/storage/role.rs

pub use diesel_models::role::*;


pub struct FrmBlockRate;