File: crates/hyperswitch_connectors/src/connectors/placetopay/transformers.rs
 Public structs: 18

use common_enums::{enums, Currency};
use common_utils::{consts::BASE64_ENGINE, date_time, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
    payment_method_data::PaymentMethodData,
    router_data::{ConnectorAuthType, RouterData},
    router_flow_types::refunds::{Execute, RSync},
    router_request_types::ResponseId,
    router_response_types::{PaymentsResponseData, RefundsResponseData},
    types,
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};

use crate::{
    types::{RefundsResponseRouterData, ResponseRouterData},
    utils::{
        self, generate_random_bytes, BrowserInformationData, CardData as _,
        PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData as _,
    },
};

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

impl<T> From<(MinorUnit, T)> for PlacetopayRouterData<T> {
    fn from((amount, item): (MinorUnit, T)) -> Self {
        Self {
            amount,
            router_data: item,
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsRequest {
    auth: PlacetopayAuth,
    payment: PlacetopayPayment,
    instrument: PlacetopayInstrument,
    ip_address: Secret<String, common_utils::pii::IpAddress>,
    user_agent: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayAuthorizeAction {
    Checkin,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuthType {
    login: Secret<String>,
    tran_key: Secret<String>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuth {
    login: Secret<String>,
    tran_key: Secret<String>,
    nonce: Secret<String>,
    seed: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPayment {
    reference: String,
    description: String,
    amount: PlacetopayAmount,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAmount {
    currency: Currency,
    total: MinorUnit,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayInstrument {
    card: PlacetopayCard,
}

#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayCard {
    number: cards::CardNumber,
    expiration: Secret<String>,
    cvv: Secret<String>,
}

impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>>
    for PlacetopayPaymentsRequest
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: &PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>,
    ) -> Result<Self, Self::Error> {
        let browser_info = item.router_data.request.get_browser_info()?;
        let ip_address = browser_info.get_ip_address()?;
        let user_agent = browser_info.get_user_agent()?;
        let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
        let payment = PlacetopayPayment {
            reference: item.router_data.connector_request_reference_id.clone(),
            description: item.router_data.get_description()?,
            amount: PlacetopayAmount {
                currency: item.router_data.request.currency,
                total: item.amount,
            },
        };
        match item.router_data.request.payment_method_data.clone() {
            PaymentMethodData::Card(req_card) => {
                let card = PlacetopayCard {
                    number: req_card.card_number.clone(),
                    expiration: req_card
                        .clone()
                        .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
                    cvv: req_card.card_cvc.clone(),
                };
                Ok(Self {
                    ip_address,
                    user_agent,
                    auth,
                    payment,
                    instrument: PlacetopayInstrument {
                        card: card.to_owned(),
                    },
                })
            }
            PaymentMethodData::Wallet(_)
            | PaymentMethodData::CardRedirect(_)
            | PaymentMethodData::PayLater(_)
            | PaymentMethodData::BankRedirect(_)
            | PaymentMethodData::BankDebit(_)
            | PaymentMethodData::BankTransfer(_)
            | PaymentMethodData::Crypto(_)
            | PaymentMethodData::MandatePayment
            | PaymentMethodData::Reward
            | PaymentMethodData::RealTimePayment(_)
            | PaymentMethodData::MobilePayment(_)
            | PaymentMethodData::Upi(_)
            | PaymentMethodData::Voucher(_)
            | PaymentMethodData::GiftCard(_)
            | PaymentMethodData::OpenBanking(_)
            | PaymentMethodData::CardToken(_)
            | PaymentMethodData::NetworkToken(_)
            | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
                Err(errors::ConnectorError::NotImplemented(
                    utils::get_unimplemented_payment_method_error_message("Placetopay"),
                )
                .into())
            }
        }
    }
}

impl TryFrom<&ConnectorAuthType> for PlacetopayAuth {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
        let placetopay_auth = PlacetopayAuthType::try_from(auth_type)?;
        let nonce_bytes = generate_random_bytes(16);
        let now = date_time::date_as_yyyymmddthhmmssmmmz()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;
        let seed = format!("{}+00:00", now.split_at(now.len() - 5).0);
        let mut context = digest::Context::new(&digest::SHA256);
        context.update(&nonce_bytes);
        context.update(seed.as_bytes());
        context.update(placetopay_auth.tran_key.peek().as_bytes());
        let encoded_digest = base64::Engine::encode(&BASE64_ENGINE, context.finish());
        let nonce = Secret::new(base64::Engine::encode(&BASE64_ENGINE, &nonce_bytes));
        Ok(Self {
            login: placetopay_auth.login,
            tran_key: encoded_digest.into(),
            nonce,
            seed,
        })
    }
}

impl TryFrom<&ConnectorAuthType> for PlacetopayAuthType {
    type Error = error_stack::Report<errors::ConnectorError>;

    fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
        if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
            Ok(Self {
                login: api_key.to_owned(),
                tran_key: key1.to_owned(),
            })
        } else {
            Err(errors::ConnectorError::FailedToObtainAuthType)?
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayTransactionStatus {
    Ok,
    Failed,
    Approved,
    // ApprovedPartial,
    // PartialExpired,
    Rejected,
    Pending,
    PendingValidation,
    PendingProcess,
    // Refunded,
    // Reversed,
    Error,
    // Unknown,
    // Manual,
    // Dispute,
    //The statuses that are commented out are awaiting clarification on the connector.
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
    status: PlacetopayTransactionStatus,
}

impl From<PlacetopayTransactionStatus> for enums::AttemptStatus {
    fn from(item: PlacetopayTransactionStatus) -> Self {
        match item {
            PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => {
                Self::Charged
            }
            PlacetopayTransactionStatus::Failed
            | PlacetopayTransactionStatus::Rejected
            | PlacetopayTransactionStatus::Error => Self::Failure,
            PlacetopayTransactionStatus::Pending
            | PlacetopayTransactionStatus::PendingValidation
            | PlacetopayTransactionStatus::PendingProcess => Self::Pending,
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsResponse {
    status: PlacetopayStatusResponse,
    internal_reference: u64,
    authorization: Option<String>,
}

impl<F, T> TryFrom<ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>>
    for RouterData<F, T, PaymentsResponseData>
{
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(
        item: ResponseRouterData<F, PlacetopayPaymentsResponse, T, PaymentsResponseData>,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            status: enums::AttemptStatus::from(item.response.status.status),
            response: Ok(PaymentsResponseData::TransactionResponse {
                resource_id: ResponseId::ConnectorTransactionId(
                    item.response.internal_reference.to_string(),
                ),
                redirection_data: Box::new(None),
                mandate_reference: Box::new(None),
                connector_metadata: item
                    .response
                    .authorization
                    .clone()
                    .map(|authorization| serde_json::json!(authorization)),
                network_txn_id: None,
                connector_response_reference_id: None,
                incremental_authorization_allowed: None,
                charges: None,
            }),
            ..item.data
        })
    }
}

// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundRequest {
    auth: PlacetopayAuth,
    internal_reference: u64,
    action: PlacetopayNextAction,
    authorization: Option<String>,
}

impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
        if item.request.minor_refund_amount == item.request.minor_payment_amount {
            let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;

            let internal_reference = item
                .request
                .connector_transaction_id
                .parse::<u64>()
                .change_context(errors::ConnectorError::RequestEncodingFailed)?;
            let action = PlacetopayNextAction::Reverse;
            let authorization = match item.request.connector_metadata.clone() {
                Some(metadata) => metadata.as_str().map(|auth| auth.to_string()),
                None => None,
            };
            Ok(Self {
                auth,
                internal_reference,
                action,
                authorization,
            })
        } else {
            Err(errors::ConnectorError::NotSupported {
                message: "Partial Refund".to_string(),
                connector: "placetopay",
            }
            .into())
        }
    }
}

impl From<PlacetopayRefundStatus> for enums::RefundStatus {
    fn from(item: PlacetopayRefundStatus) -> Self {
        match item {
            PlacetopayRefundStatus::Ok
            | PlacetopayRefundStatus::Approved
            | PlacetopayRefundStatus::Refunded => Self::Success,
            PlacetopayRefundStatus::Failed
            | PlacetopayRefundStatus::Rejected
            | PlacetopayRefundStatus::Error => Self::Failure,
            PlacetopayRefundStatus::Pending
            | PlacetopayRefundStatus::PendingProcess
            | PlacetopayRefundStatus::PendingValidation => Self::Pending,
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
    Ok,
    Failed,
    Approved,
    // ApprovedPartial,
    // PartialExpired,
    Rejected,
    Pending,
    PendingValidation,
    PendingProcess,
    Refunded,
    // Reversed,
    Error,
    // Unknown,
    // Manual,
    // Dispute,
    //The statuses that are commented out are awaiting clarification on the connector.
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundStatusResponse {
    status: PlacetopayRefundStatus,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundResponse {
    status: PlacetopayRefundStatusResponse,
    internal_reference: u64,
}

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

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRsyncRequest {
    auth: PlacetopayAuth,
    internal_reference: u64,
}

impl TryFrom<&types::RefundsRouterData<RSync>> for PlacetopayRsyncRequest {
    type Error = error_stack::Report<errors::ConnectorError>;
    fn try_from(item: &types::RefundsRouterData<RSync>) -> Result<Self, Self::Error> {
        let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
        let internal_reference = item
            .request
            .connector_transaction_id
            .parse::<u64>()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;
        Ok(Self {
            auth,
            internal_reference,
        })
    }
}

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

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayErrorResponse {
    pub status: PlacetopayError,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayError {
    pub status: PlacetopayErrorStatus,
    pub message: String,
    pub reason: String,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayErrorStatus {
    Failed,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPsyncRequest {
    auth: PlacetopayAuth,
    internal_reference: u64,
}

impl TryFrom<&types::PaymentsSyncRouterData> for PlacetopayPsyncRequest {
    type Error = error_stack::Report<errors::ConnectorError>;

    fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
        let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
        let internal_reference = item
            .request
            .get_connector_transaction_id()?
            .parse::<u64>()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;
        Ok(Self {
            auth,
            internal_reference,
        })
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayNextActionRequest {
    auth: PlacetopayAuth,
    internal_reference: u64,
    action: PlacetopayNextAction,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayNextAction {
    Refund,
    Reverse,
    Void,
    Process,
    Checkout,
}

impl TryFrom<&types::PaymentsCaptureRouterData> for PlacetopayNextActionRequest {
    type Error = error_stack::Report<errors::ConnectorError>;

    fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
        let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
        let internal_reference = item
            .request
            .connector_transaction_id
            .parse::<u64>()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;
        let action = PlacetopayNextAction::Checkout;
        Ok(Self {
            auth,
            internal_reference,
            action,
        })
    }
}

impl TryFrom<&types::PaymentsCancelRouterData> for PlacetopayNextActionRequest {
    type Error = error_stack::Report<errors::ConnectorError>;

    fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
        let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
        let internal_reference = item
            .request
            .connector_transaction_id
            .parse::<u64>()
            .change_context(errors::ConnectorError::RequestEncodingFailed)?;
        let action = PlacetopayNextAction::Void;
        Ok(Self {
            auth,
            internal_reference,
            action,
        })
    }
}


OpenAPI Block Path: components.schemas.OrganizationResponse
{
  "type": "object",
  "required": [
    "organization_id",
    "modified_at",
    "created_at"
  ],
  "properties": {
    "organization_id": {
      "type": "string",
      "description": "The unique identifier for the Organization",
      "example": "org_q98uSGAYbjEwqs0mJwnz",
      "maxLength": 64,
      "minLength": 1
    },
    "organization_name": {
      "type": "string",
      "description": "Name of the Organization",
      "nullable": true
    },
    "organization_details": {
      "type": "object",
      "description": "Details about the organization",
      "nullable": true
    },
    "metadata": {
      "type": "object",
      "description": "Metadata is useful for storing additional, unstructured information on an object.",
      "nullable": true
    },
    "modified_at": {
      "type": "string",
      "format": "date-time"
    },
    "created_at": {
      "type": "string",
      "format": "date-time"
    },
    "organization_type": {
      "allOf": [
        {
          "$ref": "#/components/schemas/OrganizationType"
        }
      ],
      "nullable": true
    }
  }
}


pub async fn validate_file_upload(
    state: &SessionState,
    merchant_context: domain::MerchantContext,
    create_file_request: api::CreateFileRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
    //File Validation based on the purpose of file upload
    match create_file_request.purpose {
        api::FilePurpose::DisputeEvidence => {
            let dispute_id = &create_file_request
                .dispute_id
                .ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
            let dispute = state
                .store
                .find_dispute_by_merchant_id_dispute_id(
                    merchant_context.get_merchant_account().get_id(),
                    dispute_id,
                )
                .await
                .to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
                    dispute_id: dispute_id.to_string(),
                })?;
            // Connector is not called for validating the file, connector_id can be passed as None safely
            let connector_data = api::ConnectorData::get_connector_by_name(
                &state.conf.connectors,
                &dispute.connector,
                api::GetToken::Connector,
                None,
            )?;

            let validation = connector_data.connector.validate_file_upload(
                create_file_request.purpose,
                create_file_request.file_size,
                create_file_request.file_type.clone(),
            );
            match validation {
                Ok(()) => Ok(()),
                Err(err) => match err.current_context() {
                    errors::ConnectorError::FileValidationFailed { reason } => {
                        Err(errors::ApiErrorResponse::FileValidationFailed {
                            reason: reason.to_string(),
                        }
                        .into())
                    }
                    //We are using parent error and ignoring this
                    _error => Err(err
                        .change_context(errors::ApiErrorResponse::InternalServerError)
                        .attach_printable("File validation failed"))?,
                },
            }
        }
    }
}


impl ConnectorValidation for Tsys {}


impl api::ConnectorAccessToken for Bamboraapac {}

impl api::ConnectorAccessToken for for Bamboraapac


pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = syn::parse_macro_input!(input as syn::DeriveInput);

    macros::derive_to_encryption(input)
        .unwrap_or_else(|err| err.into_compile_error())
        .into()
}


impl api::RefundSync for Trustpayments {}

impl api::RefundSync for for Trustpayments


pub fn get_payment_body(
    req: &BamboraapacRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Vec<u8>, Error> {
    let transaction_data = get_transaction_body(req)?;
    let body = format!(
        r#"
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
                <soapenv:Body>
                    <dts:SubmitSinglePayment>
                        <dts:trnXML>
                            <![CDATA[
                                {transaction_data}
                            ]]>
                        </dts:trnXML>
                    </dts:SubmitSinglePayment>
                </soapenv:Body>
            </soapenv:Envelope>
        "#,
    );

    Ok(body.as_bytes().to_vec())
}


impl SuccessBasedRoutingConfig {
    pub fn update(&mut self, new: Self) {
        if let Some(params) = new.params {
            self.params = Some(params)
        }
        if let Some(new_config) = new.config {
            self.config.as_mut().map(|config| config.update(new_config));
        }
        if let Some(new_config) = new.decision_engine_configs {
            self.decision_engine_configs
                .as_mut()
                .map(|config| config.update(new_config));
        }
    }

    pub fn open_router_config_default() -> Self {
        Self {
            params: None,
            config: None,
            decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData {
                default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD),
                default_bucket_size: Some(DEFAULT_BUCKET_SIZE),
                default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
                default_lower_reset_factor: None,
                default_upper_reset_factor: None,
                default_gateway_extra_score: None,
                sub_level_input_config: Some(vec![
                    open_router::DecisionEngineSRSubLevelInputConfig {
                        payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()),
                        payment_method: None,
                        latency_threshold: None,
                        bucket_size: Some(DEFAULT_BUCKET_SIZE),
                        hedging_percent: Some(DEFAULT_HEDGING_PERCENT),
                        lower_reset_factor: None,
                        upper_reset_factor: None,
                        gateway_extra_score: None,
                    },
                ]),
            }),
        }
    }

    pub fn get_decision_engine_configs(
        &self,
    ) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>>
    {
        self.decision_engine_configs
            .clone()
            .ok_or(error_stack::Report::new(
                ValidationError::MissingRequiredField {
                    field_name: "decision_engine_configs".to_string(),
                },
            ))
    }
}


File: crates/analytics/src/auth_events/types.rs

use api_models::analytics::auth_events::{AuthEventDimensions, AuthEventFilters};
use error_stack::ResultExt;

use crate::{
    query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
    types::{AnalyticsCollection, AnalyticsDataSource},
};

impl<T> QueryFilter<T> for AuthEventFilters
where
    T: AnalyticsDataSource,
    AnalyticsCollection: ToSql<T>,
{
    fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
        if !self.authentication_status.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::AuthenticationStatus,
                    &self.authentication_status,
                )
                .attach_printable("Error adding authentication status filter")?;
        }

        if !self.trans_status.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::TransactionStatus,
                    &self.trans_status,
                )
                .attach_printable("Error adding transaction status filter")?;
        }

        if !self.error_message.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::ErrorMessage, &self.error_message)
                .attach_printable("Error adding error message filter")?;
        }

        if !self.authentication_connector.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::AuthenticationConnector,
                    &self.authentication_connector,
                )
                .attach_printable("Error adding authentication connector filter")?;
        }

        if !self.message_version.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::MessageVersion,
                    &self.message_version,
                )
                .attach_printable("Error adding message version filter")?;
        }

        if !self.platform.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::Platform, &self.platform)
                .attach_printable("Error adding platform filter")?;
        }

        if !self.acs_reference_number.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::AcsReferenceNumber,
                    &self.acs_reference_number,
                )
                .attach_printable("Error adding acs reference number filter")?;
        }

        if !self.mcc.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::Mcc, &self.mcc)
                .attach_printable("Failed to add MCC filter")?;
        }
        if !self.currency.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::Currency, &self.currency)
                .attach_printable("Failed to add currency filter")?;
        }
        if !self.merchant_country.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::MerchantCountry,
                    &self.merchant_country,
                )
                .attach_printable("Failed to add merchant country filter")?;
        }
        if !self.billing_country.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::BillingCountry,
                    &self.billing_country,
                )
                .attach_printable("Failed to add billing country filter")?;
        }
        if !self.shipping_country.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::ShippingCountry,
                    &self.shipping_country,
                )
                .attach_printable("Failed to add shipping country filter")?;
        }
        if !self.issuer_country.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::IssuerCountry,
                    &self.issuer_country,
                )
                .attach_printable("Failed to add issuer country filter")?;
        }
        if !self.earliest_supported_version.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::EarliestSupportedVersion,
                    &self.earliest_supported_version,
                )
                .attach_printable("Failed to add earliest supported version filter")?;
        }
        if !self.latest_supported_version.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::LatestSupportedVersion,
                    &self.latest_supported_version,
                )
                .attach_printable("Failed to add latest supported version filter")?;
        }
        if !self.whitelist_decision.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::WhitelistDecision,
                    &self.whitelist_decision,
                )
                .attach_printable("Failed to add whitelist decision filter")?;
        }
        if !self.device_manufacturer.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::DeviceManufacturer,
                    &self.device_manufacturer,
                )
                .attach_printable("Failed to add device manufacturer filter")?;
        }
        if !self.device_type.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::DeviceType, &self.device_type)
                .attach_printable("Failed to add device type filter")?;
        }
        if !self.device_brand.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::DeviceBrand, &self.device_brand)
                .attach_printable("Failed to add device brand filter")?;
        }
        if !self.device_os.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::DeviceOs, &self.device_os)
                .attach_printable("Failed to add device OS filter")?;
        }
        if !self.device_display.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::DeviceDisplay,
                    &self.device_display,
                )
                .attach_printable("Failed to add device display filter")?;
        }
        if !self.browser_name.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::BrowserName, &self.browser_name)
                .attach_printable("Failed to add browser name filter")?;
        }
        if !self.browser_version.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::BrowserVersion,
                    &self.browser_version,
                )
                .attach_printable("Failed to add browser version filter")?;
        }
        if !self.issuer_id.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::IssuerId, &self.issuer_id)
                .attach_printable("Failed to add issuer ID filter")?;
        }
        if !self.scheme_name.is_empty() {
            builder
                .add_filter_in_range_clause(AuthEventDimensions::SchemeName, &self.scheme_name)
                .attach_printable("Failed to add scheme name filter")?;
        }
        if !self.exemption_requested.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::ExemptionRequested,
                    &self.exemption_requested,
                )
                .attach_printable("Failed to add exemption requested filter")?;
        }
        if !self.exemption_accepted.is_empty() {
            builder
                .add_filter_in_range_clause(
                    AuthEventDimensions::ExemptionAccepted,
                    &self.exemption_accepted,
                )
                .attach_printable("Failed to add exemption accepted filter")?;
        }

        Ok(())
    }
}


pub async fn execute_payment_task_response_handler(
        &self,
        state: &SessionState,
        payment_intent: &PaymentIntent,
        execute_task_process: &storage::ProcessTracker,
        revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
        revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
    ) -> Result<(), errors::ProcessTrackerError> {
        logger::info!("Entering execute_payment_task_response_handler");

        let db = &*state.store;
        match self {
            Self::SyncPayment(payment_attempt) => {
                revenue_recovery_core::insert_psync_pcr_task_to_pt(
                    revenue_recovery_payment_data.billing_mca.get_id().clone(),
                    db,
                    revenue_recovery_payment_data
                        .merchant_account
                        .get_id()
                        .to_owned(),
                    payment_intent.id.clone(),
                    revenue_recovery_payment_data.profile.get_id().to_owned(),
                    payment_attempt.id.clone(),
                    storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
                    revenue_recovery_payment_data.retry_algorithm,
                )
                .await
                .change_context(errors::RecoveryError::ProcessTrackerFailure)
                .attach_printable("Failed to create a psync workflow in the process tracker")?;

                db.as_scheduler()
                    .finish_process_with_business_status(
                        execute_task_process.clone(),
                        business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
                    )
                    .await
                    .change_context(errors::RecoveryError::ProcessTrackerFailure)
                    .attach_printable("Failed to update the process tracker")?;
                Ok(())
            }

            Self::RetryPayment(schedule_time) => {
                db.as_scheduler()
                    .retry_process(execute_task_process.clone(), *schedule_time)
                    .await?;

                // update the connector payment transmission field to Unsuccessful and unset active attempt id
                revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
                    enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
                );

                let payment_update_req =
                PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
                    payment_intent
                        .feature_metadata
                        .clone()
                        .unwrap_or_default()
                        .convert_back()
                        .set_payment_revenue_recovery_metadata_using_api(
                            revenue_recovery_metadata.clone(),
                        ),
                    api_enums::UpdateActiveAttempt::Unset,
                );
                logger::info!(
                    "Call made to payments update intent api , with the request body {:?}",
                    payment_update_req
                );
                revenue_recovery_core::api::update_payment_intent_api(
                    state,
                    payment_intent.id.clone(),
                    revenue_recovery_payment_data,
                    payment_update_req,
                )
                .await
                .change_context(errors::RecoveryError::PaymentCallFailed)?;
                Ok(())
            }
            Self::TerminalFailure(payment_attempt) => {
                // update the connector payment transmission field to Unsuccessful and unset active attempt id
                revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
                    enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
                );

                let payment_update_req =
                PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
                    payment_intent
                        .feature_metadata
                        .clone()
                        .unwrap_or_default()
                        .convert_back()
                        .set_payment_revenue_recovery_metadata_using_api(
                            revenue_recovery_metadata.clone(),
                        ),
                    api_enums::UpdateActiveAttempt::Unset,
                );
                logger::info!(
                    "Call made to payments update intent api , with the request body {:?}",
                    payment_update_req
                );
                revenue_recovery_core::api::update_payment_intent_api(
                    state,
                    payment_intent.id.clone(),
                    revenue_recovery_payment_data,
                    payment_update_req,
                )
                .await
                .change_context(errors::RecoveryError::PaymentCallFailed)?;

                db.as_scheduler()
                    .finish_process_with_business_status(
                        execute_task_process.clone(),
                        business_status::EXECUTE_WORKFLOW_FAILURE,
                    )
                    .await
                    .change_context(errors::RecoveryError::ProcessTrackerFailure)
                    .attach_printable("Failed to update the process tracker")?;
                // TODO: Add support for retrying failed outgoing recordback webhooks
                Ok(())
            }
            Self::SuccessfulPayment(payment_attempt) => {
                db.as_scheduler()
                    .finish_process_with_business_status(
                        execute_task_process.clone(),
                        business_status::EXECUTE_WORKFLOW_COMPLETE,
                    )
                    .await
                    .change_context(errors::RecoveryError::ProcessTrackerFailure)
                    .attach_printable("Failed to update the process tracker")?;
                // Record back to billing connector for terminal status
                // TODO: Add support for retrying failed outgoing recordback webhooks
                record_back_to_billing_connector(
                    state,
                    payment_attempt,
                    payment_intent,
                    &revenue_recovery_payment_data.billing_mca,
                )
                .await
                .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
                .attach_printable("Failed to update the process tracker")?;
                Ok(())
            }
            Self::ReviewPayment => {
                // requeue the process tracker in case of error response
                let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
                    status: enums::ProcessTrackerStatus::Pending,
                    business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
                };
                db.as_scheduler()
                    .update_process(execute_task_process.clone(), pt_update)
                    .await?;
                Ok(())
            }
            Self::ManualReviewAction => {
                logger::debug!("Invalid Payment Status For PCR Payment");
                let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
                    status: enums::ProcessTrackerStatus::Review,
                    business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
                };
                // update the process tracker status as Review
                db.as_scheduler()
                    .update_process(execute_task_process.clone(), pt_update)
                    .await?;
                Ok(())
            }
        }
    }


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

use serde;
use utoipa::ToSchema;

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


impl api::Payment for Jpmorgan {}


pub fn get_redis_connection_for_global_tenant(
    state: &SessionState,
) -> UserResult<Arc<RedisConnectionPool>> {
    state
        .global_store
        .get_redis_conn()
        .change_context(UserErrors::InternalServerError)
        .attach_printable("Failed to get redis connection")
}


pub struct TokenizationData {
    cnp_token: Secret<String>,
    exp_date: Secret<String>,
}


pub struct PlaidExchangeTokenRequest {
    public_token: String,
}


pub struct NoonCard {
    name_on_card: Option<Secret<String>>,
    number_plain: cards::CardNumber,
    expiry_month: Secret<String>,
    expiry_year: Secret<String>,
    cvv: Secret<String>,
}


pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> {
        match self.routing_algorithm {
            Some(ref routing_algorithm) => {
                let _: routing::StaticRoutingAlgorithm = routing_algorithm
                    .clone()
                    .parse_value("StaticRoutingAlgorithm")?;
                Ok(())
            }
            None => Ok(()),
        }
    }


/// Get a merchant id from String
    pub fn wrap(merchant_id: String) -> CustomResult<Self, ValidationError> {
        Self::try_from(std::borrow::Cow::from(merchant_id))
    }


impl AccountsStorageInterface for MockDb {}

impl AccountsStorageInterface for for MockDb


pub struct NovalnetTransaction {
    tid: String,
    amount: Option<StringMinorUnit>,
    capture: Capture,
}


impl api::ConnectorValidation for Adyenplatform {}

impl api::ConnectorValidation for for Adyenplatform


impl api::PaymentsCompleteAuthorize for Shift4 {}

impl api::PaymentsCompleteAuthorize for for Shift4


impl api::Payment for Forte {}


impl api::RefundExecute for Fiservemea {}

impl api::RefundExecute for for Fiservemea


pub struct DummyConnectorUpiFlow {
    pub status: DummyConnectorStatus,
    pub error: Option<DummyConnectorErrors>,
    pub is_next_action_required: bool,
}


OpenAPI Block Path: components.schemas.BankTransferData
{
  "oneOf": [
    {
      "type": "object",
      "required": [
        "ach_bank_transfer"
      ],
      "properties": {
        "ach_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/AchBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "sepa_bank_transfer"
      ],
      "properties": {
        "sepa_bank_transfer": {
          "type": "object",
          "required": [
            "country"
          ],
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/SepaAndBacsBillingDetails"
                }
              ],
              "nullable": true
            },
            "country": {
              "$ref": "#/components/schemas/CountryAlpha2"
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "bacs_bank_transfer"
      ],
      "properties": {
        "bacs_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/SepaAndBacsBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "multibanco_bank_transfer"
      ],
      "properties": {
        "multibanco_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/MultibancoBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "permata_bank_transfer"
      ],
      "properties": {
        "permata_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "bca_bank_transfer"
      ],
      "properties": {
        "bca_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "bni_va_bank_transfer"
      ],
      "properties": {
        "bni_va_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "bri_va_bank_transfer"
      ],
      "properties": {
        "bri_va_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "cimb_va_bank_transfer"
      ],
      "properties": {
        "cimb_va_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "danamon_va_bank_transfer"
      ],
      "properties": {
        "danamon_va_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "mandiri_va_bank_transfer"
      ],
      "properties": {
        "mandiri_va_bank_transfer": {
          "type": "object",
          "properties": {
            "billing_details": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/DokuBillingDetails"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "pix"
      ],
      "properties": {
        "pix": {
          "type": "object",
          "properties": {
            "pix_key": {
              "type": "string",
              "description": "Unique key for pix transfer",
              "example": "a1f4102e-a446-4a57-bcce-6fa48899c1d1",
              "nullable": true
            },
            "cpf": {
              "type": "string",
              "description": "CPF is a Brazilian tax identification number",
              "example": "10599054689",
              "nullable": true
            },
            "cnpj": {
              "type": "string",
              "description": "CNPJ is a Brazilian company tax identification number",
              "example": "74469027417312",
              "nullable": true
            },
            "source_bank_account_id": {
              "type": "string",
              "description": "Source bank account number",
              "example": "8b******-****-****-****-*******08bc5",
              "nullable": true
            },
            "destination_bank_account_id": {
              "type": "string",
              "description": "Partially masked destination bank account number _Deprecated: Will be removed in next stable release._",
              "deprecated": true,
              "example": "********-****-460b-****-f23b4e71c97b",
              "nullable": true
            },
            "expiry_date": {
              "type": "string",
              "description": "The expiration date and time for the Pix QR code in ISO 8601 format",
              "example": "2025-09-10T10:11:12Z",
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "pse"
      ],
      "properties": {
        "pse": {
          "type": "object"
        }
      }
    },
    {
      "type": "object",
      "required": [
        "local_bank_transfer"
      ],
      "properties": {
        "local_bank_transfer": {
          "type": "object",
          "properties": {
            "bank_code": {
              "type": "string",
              "nullable": true
            }
          }
        }
      }
    },
    {
      "type": "object",
      "required": [
        "instant_bank_transfer"
      ],
      "properties": {
        "instant_bank_transfer": {
          "type": "object"
        }
      }
    },
    {
      "type": "object",
      "required": [
        "instant_bank_transfer_finland"
      ],
      "properties": {
        "instant_bank_transfer_finland": {
          "type": "object"
        }
      }
    },
    {
      "type": "object",
      "required": [
        "instant_bank_transfer_poland"
      ],
      "properties": {
        "instant_bank_transfer_poland": {
          "type": "object"
        }
      }
    },
    {
      "type": "object",
      "required": [
        "indonesian_bank_transfer"
      ],
      "properties": {
        "indonesian_bank_transfer": {
          "type": "object",
          "properties": {
            "bank_name": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/BankNames"
                }
              ],
              "nullable": true
            }
          }
        }
      }
    }
  ]
}


pub fn from_storage(dispute: &'a Dispute) -> Self {
        let currency = dispute.dispute_currency.unwrap_or(
            dispute
                .currency
                .to_uppercase()
                .parse_enum("Currency")
                .unwrap_or_default(),
        );
        Self {
            dispute_id: &dispute.dispute_id,
            dispute_amount: StringMinorUnitForConnector::convert_back(
                &StringMinorUnitForConnector,
                dispute.amount.clone(),
                currency,
            )
            .unwrap_or_else(|e| {
                router_env::logger::error!("Failed to convert dispute amount: {e:?}");
                MinorUnit::new(0)
            }),
            currency,
            dispute_stage: &dispute.dispute_stage,
            dispute_status: &dispute.dispute_status,
            payment_id: &dispute.payment_id,
            attempt_id: &dispute.attempt_id,
            merchant_id: &dispute.merchant_id,
            connector_status: &dispute.connector_status,
            connector_dispute_id: &dispute.connector_dispute_id,
            connector_reason: dispute.connector_reason.as_ref(),
            connector_reason_code: dispute.connector_reason_code.as_ref(),
            challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
            connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
            connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
            created_at: dispute.created_at.assume_utc(),
            modified_at: dispute.modified_at.assume_utc(),
            connector: &dispute.connector,
            evidence: &dispute.evidence,
            profile_id: dispute.profile_id.as_ref(),
            merchant_connector_id: dispute.merchant_connector_id.as_ref(),
            organization_id: &dispute.organization_id,
        }
    }


OpenAPI Block Path: components.schemas.CardNetworkTokenizeResponse
{
  "type": "object",
  "required": [
    "customer",
    "card_tokenized"
  ],
  "properties": {
    "payment_method_response": {
      "allOf": [
        {
          "$ref": "#/components/schemas/PaymentMethodResponse"
        }
      ],
      "nullable": true
    },
    "customer": {
      "$ref": "#/components/schemas/CustomerDetails"
    },
    "card_tokenized": {
      "type": "boolean",
      "description": "Card network tokenization status"
    },
    "error_code": {
      "type": "string",
      "description": "Error code",
      "nullable": true
    },
    "error_message": {
      "type": "string",
      "description": "Error message",
      "nullable": true
    },
    "tokenization_data": {
      "allOf": [
        {
          "$ref": "#/components/schemas/TokenizeDataRequest"
        }
      ],
      "nullable": true
    }
  }
}


impl GetPaymentMethodDetails for DummyConnectorPayLater {
    fn get_name(&self) -> &'static str {
        match self {
            Self::Klarna => "Klarna",
            Self::Affirm => "Affirm",
            Self::AfterPayClearPay => "Afterpay Clearpay",
        }
    }
    fn get_image_link(&self, base_url: &str) -> String {
        let image_name = match self {
            Self::Klarna => "KLARNA.svg",
            Self::Affirm => "AFFIRM.svg",
            Self::AfterPayClearPay => "AFTERPAY.svg",
        };
        format!("{base_url}{image_name}")
    }
}

impl GetPaymentMethodDetails for for DummyConnectorPayLater


impl api::ConnectorAccessToken for Custombilling {}

impl api::ConnectorAccessToken for for Custombilling


pub struct CheckoutWebhookObjectResource {
    pub data: serde_json::Value,
}


File: crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs

//! Revenue Recovery Interface V2

use hyperswitch_domain_models::{
    router_data_v2::flow_common_types::{
        BillingConnectorInvoiceSyncFlowData, BillingConnectorPaymentsSyncFlowData,
        RevenueRecoveryRecordBackData,
    },
    router_flow_types::{
        BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, RecoveryRecordBack,
    },
    router_request_types::revenue_recovery::{
        BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,
        RevenueRecoveryRecordBackRequest,
    },
    router_response_types::revenue_recovery::{
        BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
        RevenueRecoveryRecordBackResponse,
    },
};

use crate::connector_integration_v2::ConnectorIntegrationV2;

#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
/// trait RevenueRecoveryV2
pub trait RevenueRecoveryV2:
    BillingConnectorPaymentsSyncIntegrationV2
    + RevenueRecoveryRecordBackV2
    + BillingConnectorInvoiceSyncIntegrationV2
{
}

#[cfg(not(all(feature = "v2", feature = "revenue_recovery")))]
/// trait RevenueRecoveryV2
pub trait RevenueRecoveryV2 {}

/// trait BillingConnectorPaymentsSyncIntegrationV2
pub trait BillingConnectorPaymentsSyncIntegrationV2:
    ConnectorIntegrationV2<
    BillingConnectorPaymentsSync,
    BillingConnectorPaymentsSyncFlowData,
    BillingConnectorPaymentsSyncRequest,
    BillingConnectorPaymentsSyncResponse,
>
{
}

/// trait RevenueRecoveryRecordBackV2
pub trait RevenueRecoveryRecordBackV2:
    ConnectorIntegrationV2<
    RecoveryRecordBack,
    RevenueRecoveryRecordBackData,
    RevenueRecoveryRecordBackRequest,
    RevenueRecoveryRecordBackResponse,
>
{
}

/// trait BillingConnectorInvoiceSyncIntegrationV2
pub trait BillingConnectorInvoiceSyncIntegrationV2:
    ConnectorIntegrationV2<
    BillingConnectorInvoiceSync,
    BillingConnectorInvoiceSyncFlowData,
    BillingConnectorInvoiceSyncRequest,
    BillingConnectorInvoiceSyncResponse,
>
{
}


pub struct PayLaterInfo {
    pub email: Option<Email>,
}


File: crates/diesel_models/src/user/sample_data.rs
 Public structs: 2

#[cfg(feature = "v1")]
use common_enums::{
    AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod,
    PaymentMethodType,
};
#[cfg(feature = "v1")]
use common_types::primitive_wrappers::{
    ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool,
};
#[cfg(feature = "v1")]
use common_utils::types::{ConnectorTransactionId, MinorUnit};
#[cfg(feature = "v1")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "v1")]
use time::PrimitiveDateTime;

#[cfg(feature = "v1")]
use crate::{
    enums::{MandateDataType, MandateDetails},
    schema::payment_attempt,
    ConnectorMandateReferenceId, PaymentAttemptNew,
};

// #[cfg(feature = "v2")]
// #[derive(
//     Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
// )]
// #[diesel(table_name = payment_attempt)]
// pub struct PaymentAttemptBatchNew {
//     pub payment_id: common_utils::id_type::PaymentId,
//     pub merchant_id: common_utils::id_type::MerchantId,
//     pub status: AttemptStatus,
//     pub error_message: Option<String>,
//     pub surcharge_amount: Option<i64>,
//     pub tax_on_surcharge: Option<i64>,
//     pub payment_method_id: Option<String>,
//     pub authentication_type: Option<AuthenticationType>,
//     #[serde(with = "common_utils::custom_serde::iso8601")]
//     pub created_at: PrimitiveDateTime,
//     #[serde(with = "common_utils::custom_serde::iso8601")]
//     pub modified_at: PrimitiveDateTime,
//     #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
//     pub last_synced: Option<PrimitiveDateTime>,
//     pub cancellation_reason: Option<String>,
//     pub browser_info: Option<serde_json::Value>,
//     pub payment_token: Option<String>,
//     pub error_code: Option<String>,
//     pub connector_metadata: Option<serde_json::Value>,
//     pub payment_experience: Option<PaymentExperience>,
//     pub payment_method_data: Option<serde_json::Value>,
//     pub preprocessing_step_id: Option<String>,
//     pub error_reason: Option<String>,
//     pub connector_response_reference_id: Option<String>,
//     pub multiple_capture_count: Option<i16>,
//     pub amount_capturable: i64,
//     pub updated_by: String,
//     pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
//     pub authentication_data: Option<serde_json::Value>,
//     pub encoded_data: Option<String>,
//     pub unified_code: Option<String>,
//     pub unified_message: Option<String>,
//     pub net_amount: Option<i64>,
//     pub external_three_ds_authentication_attempted: Option<bool>,
//     pub authentication_connector: Option<String>,
//     pub authentication_id: Option<String>,
//     pub fingerprint_id: Option<String>,
//     pub charge_id: Option<String>,
//     pub client_source: Option<String>,
//     pub client_version: Option<String>,
//     pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
//     pub profile_id: common_utils::id_type::ProfileId,
//     pub organization_id: common_utils::id_type::OrganizationId,
// }

// #[cfg(feature = "v2")]
// #[allow(dead_code)]
// impl PaymentAttemptBatchNew {
//     // Used to verify compatibility with PaymentAttemptTable
//     fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew {
//         // PaymentAttemptNew {
//         //     payment_id: self.payment_id,
//         //     merchant_id: self.merchant_id,
//         //     status: self.status,
//         //     error_message: self.error_message,
//         //     surcharge_amount: self.surcharge_amount,
//         //     tax_amount: self.tax_amount,
//         //     payment_method_id: self.payment_method_id,
//         //     confirm: self.confirm,
//         //     authentication_type: self.authentication_type,
//         //     created_at: self.created_at,
//         //     modified_at: self.modified_at,
//         //     last_synced: self.last_synced,
//         //     cancellation_reason: self.cancellation_reason,
//         //     browser_info: self.browser_info,
//         //     payment_token: self.payment_token,
//         //     error_code: self.error_code,
//         //     connector_metadata: self.connector_metadata,
//         //     payment_experience: self.payment_experience,
//         //     card_network: self
//         //         .payment_method_data
//         //         .as_ref()
//         //         .and_then(|data| data.as_object())
//         //         .and_then(|card| card.get("card"))
//         //         .and_then(|v| v.as_object())
//         //         .and_then(|v| v.get("card_network"))
//         //         .and_then(|network| network.as_str())
//         //         .map(|network| network.to_string()),
//         //     payment_method_data: self.payment_method_data,
//         //     straight_through_algorithm: self.straight_through_algorithm,
//         //     preprocessing_step_id: self.preprocessing_step_id,
//         //     error_reason: self.error_reason,
//         //     multiple_capture_count: self.multiple_capture_count,
//         //     connector_response_reference_id: self.connector_response_reference_id,
//         //     amount_capturable: self.amount_capturable,
//         //     updated_by: self.updated_by,
//         //     merchant_connector_id: self.merchant_connector_id,
//         //     authentication_data: self.authentication_data,
//         //     encoded_data: self.encoded_data,
//         //     unified_code: self.unified_code,
//         //     unified_message: self.unified_message,
//         //     net_amount: self.net_amount,
//         //     external_three_ds_authentication_attempted: self
//         //         .external_three_ds_authentication_attempted,
//         //     authentication_connector: self.authentication_connector,
//         //     authentication_id: self.authentication_id,
//         //     payment_method_billing_address_id: self.payment_method_billing_address_id,
//         //     fingerprint_id: self.fingerprint_id,
//         //     charge_id: self.charge_id,
//         //     client_source: self.client_source,
//         //     client_version: self.client_version,
//         //     customer_acceptance: self.customer_acceptance,
//         //     profile_id: self.profile_id,
//         //     organization_id: self.organization_id,
//         // }
//         todo!()
//     }
// }

#[cfg(feature = "v1")]
#[derive(
    Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptBatchNew {
    pub payment_id: common_utils::id_type::PaymentId,
    pub merchant_id: common_utils::id_type::MerchantId,
    pub attempt_id: String,
    pub status: AttemptStatus,
    pub amount: MinorUnit,
    pub currency: Option<Currency>,
    pub save_to_locker: Option<bool>,
    pub connector: Option<String>,
    pub error_message: Option<String>,
    pub offer_amount: Option<MinorUnit>,
    pub surcharge_amount: Option<MinorUnit>,
    pub tax_amount: Option<MinorUnit>,
    pub payment_method_id: Option<String>,
    pub payment_method: Option<PaymentMethod>,
    pub capture_method: Option<CaptureMethod>,
    #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
    pub capture_on: Option<PrimitiveDateTime>,
    pub confirm: bool,
    pub authentication_type: Option<AuthenticationType>,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub created_at: PrimitiveDateTime,
    #[serde(with = "common_utils::custom_serde::iso8601")]
    pub modified_at: PrimitiveDateTime,
    #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
    pub last_synced: Option<PrimitiveDateTime>,
    pub cancellation_reason: Option<String>,
    pub amount_to_capture: Option<MinorUnit>,
    pub mandate_id: Option<String>,
    pub browser_info: Option<serde_json::Value>,
    pub payment_token: Option<String>,
    pub error_code: Option<String>,
    pub connector_metadata: Option<serde_json::Value>,
    pub payment_experience: Option<PaymentExperience>,
    pub payment_method_type: Option<PaymentMethodType>,
    pub payment_method_data: Option<serde_json::Value>,
    pub business_sub_label: Option<String>,
    pub straight_through_algorithm: Option<serde_json::Value>,
    pub preprocessing_step_id: Option<String>,
    pub mandate_details: Option<MandateDataType>,
    pub error_reason: Option<String>,
    pub connector_response_reference_id: Option<String>,
    pub connector_transaction_id: Option<ConnectorTransactionId>,
    pub multiple_capture_count: Option<i16>,
    pub amount_capturable: MinorUnit,
    pub updated_by: String,
    pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
    pub authentication_data: Option<serde_json::Value>,
    pub encoded_data: Option<String>,
    pub unified_code: Option<String>,
    pub unified_message: Option<String>,
    pub net_amount: Option<MinorUnit>,
    pub external_three_ds_authentication_attempted: Option<bool>,
    pub authentication_connector: Option<String>,
    pub authentication_id: Option<common_utils::id_type::AuthenticationId>,
    pub mandate_data: Option<MandateDetails>,
    pub payment_method_billing_address_id: Option<String>,
    pub fingerprint_id: Option<String>,
    pub charge_id: Option<String>,
    pub client_source: Option<String>,
    pub client_version: Option<String>,
    pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
    pub profile_id: common_utils::id_type::ProfileId,
    pub organization_id: common_utils::id_type::OrganizationId,
    pub shipping_cost: Option<MinorUnit>,
    pub order_tax_amount: Option<MinorUnit>,
    pub processor_transaction_data: Option<String>,
    pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
    pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
    pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
    pub capture_before: Option<PrimitiveDateTime>,
    pub card_discovery: Option<common_enums::CardDiscovery>,
    pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
    pub created_by: Option<String>,
    pub setup_future_usage_applied: Option<common_enums::FutureUsage>,
    pub routing_approach: Option<common_enums::RoutingApproach>,
    pub connector_request_reference_id: Option<String>,
    pub network_transaction_id: Option<String>,
}

#[cfg(feature = "v1")]
#[allow(dead_code)]
impl PaymentAttemptBatchNew {
    // Used to verify compatibility with PaymentAttemptTable
    fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew {
        PaymentAttemptNew {
            payment_id: self.payment_id,
            merchant_id: self.merchant_id,
            attempt_id: self.attempt_id,
            status: self.status,
            amount: self.amount,
            currency: self.currency,
            save_to_locker: self.save_to_locker,
            connector: self.connector,
            error_message: self.error_message,
            offer_amount: self.offer_amount,
            surcharge_amount: self.surcharge_amount,
            tax_amount: self.tax_amount,
            payment_method_id: self.payment_method_id,
            payment_method: self.payment_method,
            capture_method: self.capture_method,
            capture_on: self.capture_on,
            confirm: self.confirm,
            authentication_type: self.authentication_type,
            created_at: self.created_at,
            modified_at: self.modified_at,
            last_synced: self.last_synced,
            cancellation_reason: self.cancellation_reason,
            amount_to_capture: self.amount_to_capture,
            mandate_id: self.mandate_id,
            browser_info: self.browser_info,
            payment_token: self.payment_token,
            error_code: self.error_code,
            connector_metadata: self.connector_metadata,
            payment_experience: self.payment_experience,
            payment_method_type: self.payment_method_type,
            card_network: self
                .payment_method_data
                .as_ref()
                .and_then(|data| data.as_object())
                .and_then(|card| card.get("card"))
                .and_then(|v| v.as_object())
                .and_then(|v| v.get("card_network"))
                .and_then(|network| network.as_str())
                .map(|network| network.to_string()),
            payment_method_data: self.payment_method_data,
            business_sub_label: self.business_sub_label,
            straight_through_algorithm: self.straight_through_algorithm,
            preprocessing_step_id: self.preprocessing_step_id,
            mandate_details: self.mandate_details,
            error_reason: self.error_reason,
            multiple_capture_count: self.multiple_capture_count,
            connector_response_reference_id: self.connector_response_reference_id,
            amount_capturable: self.amount_capturable,
            updated_by: self.updated_by,
            merchant_connector_id: self.merchant_connector_id,
            authentication_data: self.authentication_data,
            encoded_data: self.encoded_data,
            unified_code: self.unified_code,
            unified_message: self.unified_message,
            net_amount: self.net_amount,
            external_three_ds_authentication_attempted: self
                .external_three_ds_authentication_attempted,
            authentication_connector: self.authentication_connector,
            authentication_id: self.authentication_id,
            mandate_data: self.mandate_data,
            payment_method_billing_address_id: self.payment_method_billing_address_id,
            fingerprint_id: self.fingerprint_id,
            client_source: self.client_source,
            client_version: self.client_version,
            customer_acceptance: self.customer_acceptance,
            profile_id: self.profile_id,
            organization_id: self.organization_id,
            shipping_cost: self.shipping_cost,
            order_tax_amount: self.order_tax_amount,
            connector_mandate_detail: self.connector_mandate_detail,
            request_extended_authorization: self.request_extended_authorization,
            extended_authorization_applied: self.extended_authorization_applied,
            capture_before: self.capture_before,
            card_discovery: self.card_discovery,
            processor_merchant_id: self.processor_merchant_id,
            created_by: self.created_by,
            setup_future_usage_applied: self.setup_future_usage_applied,
            routing_approach: self.routing_approach,
            connector_request_reference_id: self.connector_request_reference_id,
            network_transaction_id: self.network_transaction_id,
        }
    }
}


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

# Try out hyperswitch on your system

The simplest way to run hyperswitch locally is
[with Docker Compose](#run-hyperswitch-using-docker-compose) by pulling the
latest images from Docker Hub.
However, if you're willing to modify the code and run it, or are a developer
contributing to hyperswitch, then you can either
[set up a development environment using Docker Compose](#set-up-a-development-environment-using-docker-compose),
or [set up a Rust environment on your system](#set-up-a-rust-environment-and-other-dependencies).

Check the Table Of Contents to jump to the relevant section.

**Table Of Contents:**

- [Run hyperswitch using Docker Compose](#run-hyperswitch-using-docker-compose)
  - [Running additional services](#running-additional-services)
- [Set up a development environment using Docker Compose](#set-up-a-development-environment-using-docker-compose)
- [Set up a Nix development environment](#set-up-a-nix-development-environment)
   - [Install Nix](#install-nix)
   - [Using external services through Nix](#using-external-services-through-nix)
   - [Develop in a Nix environment (coming soon)](#develop-in-a-nix-environment-coming-soon)
- [Set up a Rust environment and other dependencies](#set-up-a-rust-environment-and-other-dependencies)
  - [Set up dependencies on Ubuntu-based systems](#set-up-dependencies-on-ubuntu-based-systems)
  - [Set up dependencies on Windows (Ubuntu on WSL2)](#set-up-dependencies-on-windows-ubuntu-on-wsl2)
  - [Set up dependencies on Windows](#set-up-dependencies-on-windows)
  - [Set up dependencies on MacOS](#set-up-dependencies-on-macos)
  - [Set up the database](#set-up-the-database)
  - [Configure the application](#configure-the-application)
  - [Run the application](#run-the-application)
- [Try out our APIs](#try-out-our-apis)
  - [Set up your merchant account](#set-up-your-merchant-account)
  - [Create an API key](#create-an-api-key)
  - [Set up a payment connector account](#set-up-a-payment-connector-account)
  - [Create a Payment](#create-a-payment)
  - [Create a Refund](#create-a-refund)

## Run hyperswitch using Docker Compose

1. Install [Docker Compose][docker-compose-install] or [Podman Compose][podman-compose-install].
2. Clone the repository and switch to the project directory:

   ```shell
   git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch
   cd hyperswitch
   ```

3. (Optional) Configure the application using the
   [`config/docker_compose.toml`][docker-compose-config] file.
   The provided configuration should work as is.
   If you do update the `docker_compose.toml` file, ensure to also update the
   corresponding values in the [`docker-compose.yml`][docker-compose-yml] file.
4. Start all the services using below script:

   ```shell
   scripts/setup.sh
   ```
   You will get prompts to select your preferred setup option.

[docker-compose-install]: https://docs.docker.com/compose/install/
[podman-compose-install]: https://podman.io/docs/installation
[docker-compose-config]: /config/docker_compose.toml
[docker-compose-yml]: /docker-compose.yml
[architecture]: /docs/architecture.md
[data-docs]: /crates/analytics/docs/README.md

## Set up a development environment using Docker Compose

1. Install [Docker Compose][docker-compose-install].
2. Clone the repository and switch to the project directory:

   ```shell
   git clone https://github.com/juspay/hyperswitch
   cd hyperswitch
   ```

3. (Optional) Configure the application using the
   [`config/docker_compose.toml`][docker-compose-config] file.
   The provided configuration should work as is.
   If you do update the `docker_compose.toml` file, ensure to also update the
   corresponding values in the [`docker-compose.yml`][docker-compose-yml] file.
4. Start all the services using Docker Compose:

   ```shell
   docker compose --file docker-compose-development.yml up -d
   ```

   This will compile the payments router, the primary component within
   hyperswitch and then start it.
   Depending on the specifications of your machine, **compilation can take
   around 30 minutes**.

5. (Optional) You can also choose to
   [start the scheduler and/or monitoring services](#running-additional-services)
   in addition to the payments router.

6. Verify that the server is up and running by hitting the health endpoint:

   ```shell
   curl --head --request GET 'http://localhost:8080/health'
   ```

   If the command returned a `200 OK` status code, proceed with
   [trying out our APIs](#try-out-our-apis).

## Set up a Nix development environment

A Nix development environment simplifies the setup of required project dependencies. This is available for MacOS, Linux and WSL2 users.

### Install nix

We recommend that you install Nix using [the DetSys nix-installer][detsys-nixos-installer], which automatically enables flakes.

As an **optional** next step, if you are interested in using Nix to manage your dotfiles and local packages, you can setup [nixos-unified-template][nixos-unified-template-repo].

### Using external services through Nix

Once Nix is installed, you can use it to manage external services via `flakes`. More services will be added soon.

- Run below command in hyperswitch directory

   ```shell
   nix run .#ext-services
   ```

This will start the following services using `process-compose`
- PostgreSQL
   - Creates database and an user to be used by the application
- Redis

### Develop in a Nix environment

The Nix development environment, defined in `flake.nix`, provides a consistent and reproducible setup with all necessary dependencies for building and testing Hyperswitch.

**Available Development Shells:**

Hyperswitch offers three distinct Nix shells tailored for different activities:

1. **Default Shell (`hyperswitch-shell`):**
   ```shell
      nix develop
   ```
   * **Purpose:** Minimal shell for compiling and running the server.
   * **Usage:** Within this shell, you can run DB migrations, compile and run different components. It uses MSRV of `rust` defined for the project.

2. **Development Shell (`hyperswitch-dev-shell`):**
    ```shell
      nix develop .#dev
    ```
   * **Purpose:** Extends the default shell with packages required during active development of the project.
   * **Usage:** Within this shell, you can run clippy checks and validate OpenAPI specs. This shell uses the latest version of `rust` at the time of commit.

3. **QA Shell (`hyperswitch-qa-shell`):**
   ```shell
      nix develop .#qa
   ```
   * **Purpose:** Extends the default shell with tools specifically required for executing Cypress tests.
   * **Usage:** Within this shell, you can execute cypress tests. This also uses MSRV of `rust` defined in the project.

## Set up a Rust environment and other dependencies

If you are using `nix`, please skip the setup dependencies step and jump to
[Set up the database](#set-up-the-database).

### Set up dependencies on Ubuntu-based systems

This section of the guide provides instructions to install dependencies on
Ubuntu-based systems.
If you're running another Linux distribution, install the corresponding packages
for your distribution and follow along.

1. Install the stable Rust toolchain using `rustup`:

   ```shell
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
   ```

   When prompted, proceed with the `default` profile, which installs the stable
   toolchain.

   Optionally, verify that the Rust compiler and `cargo` are successfully
   installed:

   ```shell
   rustc --version
   ```

   _Be careful when running shell scripts downloaded from the Internet.
   We only suggest running this script as there seems to be no `rustup` package
   available in the Ubuntu package repository._

2. Install PostgreSQL and start the `postgresql` systemd service:

   ```shell
   sudo apt update
   sudo apt install postgresql postgresql-contrib libpq-dev
   systemctl start postgresql.service
   ```

   If you're running any other distribution than Ubuntu, you can follow the
   installation instructions on the
   [PostgreSQL documentation website][postgresql-install] to set up PostgreSQL
   on your system.

3. Install Redis and start the `redis` systemd service:

   ```shell
   sudo apt install redis-server
   systemctl start redis.service
   ```

   If you're running a distribution other than Ubuntu, you can follow the
   installation instructions on the [Redis website][redis-install] to set up
   Redis on your system.

4. Install `diesel_cli` using `cargo`:

   ```shell
   cargo install diesel_cli --no-default-features --features postgres
   ```

5. Make sure your system has the `pkg-config` package and OpenSSL installed

   ```shell
   sudo apt install pkg-config libssl-dev
   ```

Once you're done with setting up the dependencies, proceed with
[setting up the database](#set-up-the-database).

[postgresql-install]: https://www.postgresql.org/download/
[redis-install]: https://redis.io/docs/getting-started/installation/
[wsl-config]: https://learn.microsoft.com/en-us/windows/wsl/wsl-config/

### Set up dependencies on Windows (Ubuntu on WSL2)

This section of the guide provides instructions to install dependencies on
Ubuntu on WSL2.
If you prefer running another Linux distribution, install the corresponding
packages for your distribution and follow along.

1. Install Ubuntu on WSL:

   ```shell
   wsl --install -d Ubuntu
   ```

   Refer to the [official installation docs][wsl-install] for more information.
   Launch the WSL instance and set up your username and password.
   The following steps assume that you are running the commands within the WSL
   shell environment.

   > Note that a `SIGKILL` error may occur when compiling certain crates if WSL is unable to use sufficient memory. It may be necessary to allow up to 24GB of memory, but your mileage may vary. You may increase the amount of memory WSL can use via a `.wslconfig` file in your Windows user folder, or by creating a swap file in WSL itself. Refer to the [WSL configuration documentation][wsl-config] for more information.

2. Install the stable Rust toolchain using `rustup`:

   ```shell
   curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
   ```

   When prompted, proceed with the `default` profile, which installs the stable
   toolchain.

   Optionally, verify that the Rust compiler and `cargo` are successfully
   installed:

   ```shell
   rustc --version
   ```

   _Be careful when running shell scripts downloaded from the Internet.
   We only suggest running this script as there seems to be no `rustup` package
   available in the Ubuntu package repository._

3. Install PostgreSQL and start the `postgresql` service:

   ```shell
   sudo apt update
   sudo apt install postgresql postgresql-contrib libpq-dev
   sudo service postgresql start
   ```

   For more information, refer to the docs for
   [installing PostgreSQL on WSL][postgresql-install-wsl].
   If you're running any other distribution than Ubuntu, you can follow the
   installation instructions on the
   [PostgreSQL documentation website][postgresql-install] to set up PostgreSQL
   on your system.

4. Install Redis and start the `redis-server` service:

   ```shell
   sudo apt install redis-server
   sudo service redis-server start
   ```

   For more information, refer to the docs for
   [installing Redis on WSL][redis-install-wsl].
   If you're running a distribution other than Ubuntu, you can follow the
   installation instructions on the [Redis website][redis-install] to set up
   Redis on your system.

5. Make sure your system has the packages necessary for compiling Rust code:

   ```shell
   sudo apt install build-essential
   ```

6. Install `diesel_cli` using `cargo`:

   ```shell
   cargo install diesel_cli --no-default-features --features postgres
   ```

7. Make sure your system has the `pkg-config` package and OpenSSL installed:

   ```shell
   sudo apt install pkg-config libssl-dev
   ```

Once you're done with setting up the dependencies, proceed with
[setting up the database](#set-up-the-database).

[wsl-install]: https://learn.microsoft.com/en-us/windows/wsl/install
[postgresql-install-wsl]: https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-database#install-postgresql
[redis-install-wsl]: https://learn.microsoft.com/en-us/windows/wsl/tutorials/wsl-database#install-redis

### Set up dependencies on Windows

We'll be using [`winget`][winget] in this section of the guide, where possible.
You can opt to use your favorite package manager instead.

1. Install PostgreSQL database, following the
   [official installation docs][postgresql-install-windows].

2. Install Redis, following the
   [official installation docs][redis-install-windows].

3. Install rust with `winget`:

   ```shell
   winget install -e --id Rustlang.Rust.GNU
   ```

4. Install `diesel_cli` using `cargo`:

   ```shell
   cargo install diesel_cli --no-default-features --features postgres
   ```

5. Install OpenSSL with `winget`:

   ```shell
   winget install openssl
   ```

Once you're done with setting up the dependencies, proceed with
[setting up the database](#set-up-the-database).

[winget]: https://github.com/microsoft/winget-cli
[postgresql-install-windows]: https://www.postgresql.org/download/windows/
[redis-install-windows]: https://redis.io/docs/getting-started/installation/install-redis-on-windows

### Set up dependencies on MacOS

We'll be using [Homebrew][homebrew] in this section of the guide.
You can opt to use your favorite package manager instead.

1. Install the stable Rust toolchain using `rustup`:

   ```shell
   brew install rustup
   rustup default stable
   ```

   Optionally, verify that the Rust compiler and `cargo` are successfully
   installed:

   ```shell
   rustc --version
   ```

2. Install PostgreSQL and start the `postgresql` service:

   ```shell
   brew install postgresql@14
   brew services start postgresql@14
   ```

   If a `postgres` database user was not already created, you may have to create
   one:

   ```shell
   createuser -s postgres
   ```

3. Install Redis and start the `redis` service:

   ```shell
   brew install redis
   brew services start redis
   ```

4. Install `diesel_cli` using `cargo`:

   ```shell
   cargo install diesel_cli --no-default-features --features postgres
   ```

   If linking `diesel_cli` fails due to missing `libpq` (if the error message is
   along the lines of `cannot find -lpq`), you may also have to install `libpq`
   and reinstall `diesel_cli`:

   ```shell
   brew install libpq
   export PQ_LIB_DIR="$(brew --prefix libpq)/lib"

   cargo install diesel_cli --no-default-features --features postgres
   ```

   You may also choose to persist the value of `PQ_LIB_DIR` in your shell
   startup file like so:

   ```shell
   echo 'PQ_LIB_DIR="$(brew --prefix libpq)/lib"' >> ~/.zshrc
   ```

5. Install a command runner called `just`:

   In order to make running migrations easier, you can use a command runner called just

   ```shell
   cargo install just
   ```

Once you're done with setting up the dependencies, proceed with
[setting up the database](#set-up-the-database).

[homebrew]: https://brew.sh/

### Set up the database

1. Create the database and database users, modifying the database user
   credentials and database name as required.

   ```shell
   export DB_USER="db_user"
   export DB_PASS="db_pass"
   export DB_NAME="hyperswitch_db"
   ```

   On Ubuntu-based systems (also applicable for Ubuntu on WSL2):

   ```shell
   sudo -u postgres psql -e -c \
      "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;"
   sudo -u postgres psql -e -c \
      "CREATE DATABASE $DB_NAME;"
   ```

   On MacOS:

   ```shell
   psql -e -U postgres -c \
      "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;"
   psql -e -U postgres -c \
      "CREATE DATABASE $DB_NAME"
   ```

2. Clone the repository and switch to the project directory:

   ```shell
   git clone https://github.com/juspay/hyperswitch
   cd hyperswitch
   ```

3. Run database migrations:

   Export the `DATABASE_URL` env variable

   ```shell
   export DATABASE_URL=postgres://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME
   ```

   Run the migrations

   - If you have just installed

   ```shell
   just migrate
   ```

   - Using the diesel-cli command

   ```shell
   diesel migration run
   ```

Once you're done with setting up the database, proceed with
[configuring the application](#configure-the-application).

### Configure the application

The application configuration files are present under the
[`config`][config-directory] directory.

The configuration file read varies with the environment:

- Development: [`config/development.toml`][config-development]
- Sandbox: `config/sandbox.toml`
- Production: `config/production.toml`

Refer to [`config.example.toml`][config-example] for all the available
configuration options.
Refer to [`development.toml`][config-development] for the recommended defaults for
local development.

Ensure to update the [`development.toml`][config-development] file if you opted
to use different database credentials as compared to the sample ones included in
this guide.

Once you're done with configuring the application, proceed with
[running the application](#run-the-application).

[config-directory]: /config
[config-development]: /config/development.toml
[config-example]: /config/config.example.toml
[config-docker-compose]: /config/docker_compose.toml

### Run the application

1. Compile and run the application using `cargo`:

   ```shell
   cargo run
   ```

   If you are using `nix`, you can compile and run the application using `nix`:

   ```shell
   nix run
   ```

2. Verify that the server is up and running by hitting the health endpoint:

   ```shell
   curl --head --request GET 'http://localhost:8080/health'
   ```

   If the command returned a `200 OK` status code, proceed with
   [trying out our APIs](#try-out-our-apis).

## Try out our APIs

### Set up your merchant account

1. Sign up or sign in to [Postman][postman].
2. Open our [Postman collection][postman-collection] and switch to the
   ["Variables" tab][variables].
   Update the value under the "current value" column for the `baseUrl` variable
   to have the hostname and port of the locally running server
   (`http://localhost:8080` by default).

3. While on the "Variables" tab, add the admin API key you configured in the
   application configuration under the "current value" column for the
   `admin_api_key` variable.

   1. If you're running Docker Compose, you can find the configuration file at
      [`config/docker_compose.toml`][config-docker-compose], search for
      `admin_api_key` to find the admin API key.
   2. If you set up the dependencies locally, you can find the configuration
      file at [`config/development.toml`][config-development], search for
      `admin_api_key` to find the admin API key

4. Open the ["Quick Start" folder][quick-start] in the collection.
5. Open the ["Merchant Account - Create"][merchant-account-create] request,
   switch to the "Body" tab and update any request parameters as required.

   - If you want to use a different connector for making payments with
     than the provided default, update the `data` field present
     in the `routing_algorithm` field to your liking.

   Click on the "Send" button to create a merchant account
   (You may need to "create a fork" to fork this collection to your own
   workspace to send a request).
   You should obtain a response containing most of the data included in the
   request, along with some additional fields.
   Store the merchant ID and publishable key returned in the response.

### Create an API key

1. Open the ["API Key - Create"][api-key-create] request, switch to the "Body"
   tab and update any request parameters as required.
   Click on the "Send" button to create an API key.
   You should obtain a response containing the data included in the request,
   along with the plaintext API key.
   Store the API key returned in the response securely.

### Set up a payment connector account

1. Sign up on the payment connector's (say Stripe, Adyen, etc.) dashboard and
   store your connector API key (and any other necessary secrets) securely.
2. Open the ["Payment Connector - Create"][payment-connector-create] request,
   switch to the "Body" tab and update any request parameters as required.

   - Pay special attention to the `connector_name` and
     `connector_account_details` fields and update them.
     You can find connector-specific details to be included in this
     [spreadsheet][connector-specific-details].
   - Open the ["Variables" tab][variables] in the
     [Postman collection][postman-collection] and set the `connector_api_key`
     variable to your connector's API key.

   Click on the "Send" button to create a payment connector account.
   You should obtain a response containing most of the data included in the
   request, along with some additional fields.

3. Follow the above steps if you'd like to add more payment connector accounts.

### Create a Payment

Ensure that you have
[set up your merchant account](#set-up-your-merchant-account) and
[set up at least one payment connector account](#set-up-a-payment-connector-account)
before trying to create a payment.

1. Open the ["Payments - Create"][payments-create] request, switch to the "Body"
   tab and update any request parameters as required.
   Click on the "Send" button to create a payment.
   If all goes well and you had provided the correct connector credentials, the
   payment should be created successfully.
   You should see the `status` field of the response body having a value of
   `succeeded` in this case.

   - If the `status` of the payment created was `requires_confirmation`, set
     `confirm` to `true` in the request body and send the request again.

2. Open the ["Payments - Retrieve"][payments-retrieve] request and click on the
   "Send" button (without modifying anything).
   This should return the payment object for the payment created in Step 2.

### Create a Refund

1. Open the ["Refunds - Create"][refunds-create] request in the
   ["Quick Start" folder][quick-start] folder and switch to the "Body" tab.
   Update the amount to be refunded, if required, and click on the "Send" button.
   This should create a refund against the last payment made for the specified
   amount.
   Check the `status` field of the response body to verify that the refund
   hasn't failed.
2. Open the ["Refunds - Retrieve"][refunds-retrieve] request and switch to the
   "Params" tab.
   Set the `id` path variable in the "Path Variables" table to the `refund_id`
   value returned in the response during the previous step.
   This should return the refund object for the refund created in the previous
   step.

That's it!
Hope you got a hang of our APIs.
To explore more of our APIs, please check the remaining folders in the
[Postman collection][postman-collection].

[postman]: https://www.postman.com
[postman-collection]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/collection/25176162-630b5353-7002-44d1-8ba1-ead6c230f2e3
[variables]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/collection/25176162-630b5353-7002-44d1-8ba1-ead6c230f2e3?tab=variables
[quick-start]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/folder/25176162-0f61a2bb-f9d5-4c60-8b73-9b677bf8ebbc
[merchant-account-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-3c5d5282-931b-4adc-a651-f88c8697ebcb
[api-key-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-98ce39af-0dbc-4583-8c22-dcaa801851e0
[payment-connector-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-295d83c8-957a-4524-95c8-589a26d751cf
[payments-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-ee0549bf-dd38-41fd-9a8a-de74879f3cda
[payments-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-8baf2590-d2af-44d0-ba37-e9cab7ef891a
[refunds-create]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-4d1315c6-ac61-4411-8f7d-15d4e4e736a1
[refunds-retrieve]: https://www.postman.com/hyperswitch/workspace/hyperswitch-development/request/25176162-137d6260-24f7-4752-9e69-26b61b83df0d
[connector-specific-details]: https://docs.google.com/spreadsheets/d/e/2PACX-1vQWHLza9m5iO4Ol-tEBx22_Nnq8Mb3ISCWI53nrinIGLK8eHYmHGnvXFXUXEut8AFyGyI9DipsYaBLG/pubhtml?gid=748960791&single=true
[detsys-nixos-installer]: https://nixos.asia/en/install
[nixos-unified-template-repo]: https://github.com/juspay/nixos-unified-template#on-non-nixos