text
stringlengths
70
351k
source
stringclasses
4 values
<|meta_start|><|file|> hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs<|crate|> hyperswitch_connectors<|connector|> mifinity anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="351" end="364"> fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="350" end="350"> connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let merchant_id = &req.merchant_id; let payment_id = &req.connector_request_reference_id; Ok(format!( "{}api/gateway/payment-status/payment_validation_key_{}_{}", self.base_url(connectors), merchant_id.get_string_repr(), payment_id )) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="386" end="392"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="366" end="384"> fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: mifinity::MifinityPsyncResponse = res .response .parse_struct("mifinity PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="336" end="349"> fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let merchant_id = &req.merchant_id; let payment_id = &req.connector_request_reference_id; Ok(format!( "{}api/gateway/payment-status/payment_validation_key_{}_{}", self.base_url(connectors), merchant_id.get_string_repr(), payment_id )) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="332" end="334"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="408" end="414"> fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/mifinity.rs" role="context" start="396" end="402"> fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs<|crate|> hyperswitch_connectors<|connector|> globalpay anchor=build_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="896" end="909"> fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="895" end="895"> &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}transactions/{}", self.base_url(connectors), refund_id )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="933" end="939"> fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="911" end="931"> fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: GlobalpayPaymentsResponse = res .response .parse_struct("globalpay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="883" end="894"> fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}transactions/{}", self.base_url(connectors), refund_id )) } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="879" end="881"> fn get_content_type(&self) -> &'static str { self.common_get_content_type() } <file_sep path="hyperswitch/crates/hyperswitch_connectors/src/connectors/globalpay.rs" role="context" start="74" end="78"> pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1952" end="1952"> use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; use cards::CardNumber; use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; use crate::ephemeral_key::EphemeralKeyCreateResponse; use crate::mandates::ProcessorPaymentToken; use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; use crate::enums; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2044" end="2081"> fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2027" end="2040"> fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1867" end="1869"> fn default() -> Self { Self::MultiUse(None) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7854" end="7865"> fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1951" end="1951"> type Error = error_stack::Report<ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="536" end="569"> pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6233" end="6308"> fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6702" end="6715"> pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6693" end="6701"> pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6223" end="6229"> fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6204" end="6219"> fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7867" end="7877"> fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4162" end="4169"> pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4154" end="4157"> pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1058" end="1063"> pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1057" end="1057"> pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1042" end="1049"> pub fn update(&mut self, new: Self) { if let Some(new_cons) = new.constants { self.constants = Some(new_cons) } if let Some(new_time_scale) = new.time_scale { self.time_scale = Some(new_time_scale) } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1014" end="1038"> pub fn update(&mut self, new: Self) { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_label_info) = new.label_info { new_label_info.iter().for_each(|new_label_info| { if let Some(existing_label_infos) = &mut self.label_info { let mut updated = false; for existing_label_info in &mut *existing_label_infos { if existing_label_info.mca_id == new_label_info.mca_id { existing_label_info.update_target_time(new_label_info); existing_label_info.update_target_count(new_label_info); updated = true; } } if !updated { existing_label_infos.push(new_label_info.clone()); } } else { self.label_info = Some(vec![new_label_info.clone()]); } }); } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="709" end="735"> pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="246" end="254"> fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="173" end="179"> pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=set_or_reject_duplicate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1853" end="1865"> fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1852" end="1852"> use std::str::FromStr; use serde::de; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2479" end="2572"> fn try_from( item: ( PaymentMethodRecord, id_type::MerchantId, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_id) = item; // if payment instrument id is present then only construct this let connector_mandate_details = if record.payment_instrument_id.is_some() { Some(PaymentsMandateReference(HashMap::from([( mca_id.get_required_value("merchant_connector_id")?, PaymentsMandateReferenceRecord { connector_mandate_id: record .payment_instrument_id .get_required_value("payment_instrument_id")? .peek() .to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record.original_transaction_currency, }, )]))) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id), card: Some(MigrateCardDetail { card_number: record.raw_card_number.unwrap_or(record.card_number_masked), card_exp_month: record.card_expiry_month, card_exp_year: record.card_expiry_year, card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: Some(record.nick_name.clone()), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.unwrap_or_default(), network_token_exp_month: record.network_token_expiry_month.unwrap_or_default(), network_token_exp_year: record.network_token_expiry_year.unwrap_or_default(), card_holder_name: record.name, nick_name: Some(record.nick_name.clone()), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing: Some(payments::Address { address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), phone: Some(payments::PhoneDetails { number: record.phone, country_code: record.phone_country_code, }), email: record.email, }), connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id, }) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2443" end="2468"> fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1779" end="1849"> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1792" end="1845"> fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2718" end="2733"> fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2717" end="2717"> use masking::PeekInterface; use masking::{ExposeInterface, PeekInterface}; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2577" end="2600"> fn from(value: (PaymentMethodRecord, id_type::MerchantId)) -> Self { let (record, merchant_id) = value; Self { customer_id: Some(record.customer_id), merchant_id, name: record.name, email: record.email, phone: record.phone, description: None, phone_country_code: record.phone_country_code, address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), metadata: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2479" end="2572"> fn try_from( item: ( PaymentMethodRecord, id_type::MerchantId, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_id) = item; // if payment instrument id is present then only construct this let connector_mandate_details = if record.payment_instrument_id.is_some() { Some(PaymentsMandateReference(HashMap::from([( mca_id.get_required_value("merchant_connector_id")?, PaymentsMandateReferenceRecord { connector_mandate_id: record .payment_instrument_id .get_required_value("payment_instrument_id")? .peek() .to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record.original_transaction_currency, }, )]))) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id), card: Some(MigrateCardDetail { card_number: record.raw_card_number.unwrap_or(record.card_number_masked), card_exp_month: record.card_expiry_month, card_exp_year: record.card_expiry_year, card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: Some(record.nick_name.clone()), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.unwrap_or_default(), network_token_exp_month: record.network_token_expiry_month.unwrap_or_default(), network_token_exp_year: record.network_token_expiry_year.unwrap_or_default(), card_holder_name: record.name, nick_name: Some(record.nick_name.clone()), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing: Some(payments::Address { address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), phone: Some(payments::PhoneDetails { number: record.phone, country_code: record.phone_country_code, }), email: record.email, }), connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id, }) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="398" end="442"> pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1549" end="1563"> pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { payment_method_type: pm_type.payment_method_type, payment_experience: pm_type.payment_experience, card_networks: pm_type.card_networks, payment_method: pm, connector, merchant_connector_id, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1075" end="1083"> pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/api_event.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="114" end="119"> pub fn new(normalized_time_range: TimeRange) -> Self { Self { time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="113" end="113"> use super::{NameDescription, TimeRange}; <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="129" end="135"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="123" end="125"> fn hash<H: Hasher>(&self, state: &mut H) { self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="95" end="100"> fn from(value: ApiEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="60" end="65"> fn from(value: ApiEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/disputes.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="123" end="136"> pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="122" end="122"> use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{Currency, DisputeStage}; <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="113" end="119"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="105" end="110"> fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); self.currency.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="65" end="70"> fn from(value: DisputeDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/frm.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="135" end="148"> pub fn new( frm_status: Option<String>, frm_name: Option<String>, frm_transaction_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { frm_status, frm_name, frm_transaction_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="134" end="134"> use super::{NameDescription, TimeRange}; <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="125" end="131"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="116" end="121"> fn hash<H: Hasher>(&self, state: &mut H) { self.frm_status.hash(state); self.frm_name.hash(state); self.frm_transaction_type.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="86" end="91"> fn from(value: FrmMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="95" end="100"> fn from(value: FrmDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/sdk_events.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="164" end="182"> pub fn new( payment_method: Option<String>, platform: Option<String>, browser_name: Option<String>, source: Option<String>, component: Option<String>, payment_experience: Option<String>, time_bucket: Option<String>, ) -> Self { Self { payment_method, platform, browser_name, source, component, payment_experience, time_bucket, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="198" end="204"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="186" end="194"> fn hash<H: Hasher>(&self, state: &mut H) { self.payment_method.hash(state); self.platform.hash(state); self.browser_name.hash(state); self.source.hash(state); self.component.hash(state); self.payment_experience.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="144" end="149"> fn from(value: SdkEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="135" end="140"> fn from(value: SdkEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/refunds.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="214" end="235"> pub fn new( currency: Option<Currency>, refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, profile_id: Option<String>, refund_reason: Option<String>, refund_error_message: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="213" end="213"> use crate::enums::{Currency, RefundStatus}; use super::{ForexMetric, NameDescription, TimeRange}; <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="203" end="209"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="191" end="200"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.refund_status.hash(state); self.connector.hash(state); self.refund_type.hash(state); self.profile_id.hash(state); self.refund_reason.hash(state); self.refund_error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="157" end="162"> fn from(value: RefundMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="166" end="171"> fn from(value: RefundDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/auth_events.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="151" end="172"> pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="150" end="150"> use common_enums::{ AuthenticationConnectors, AuthenticationStatus, DecoupledAuthenticationType, TransactionStatus, }; use super::{NameDescription, TimeRange}; <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="189" end="195"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="176" end="185"> fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="125" end="130"> fn from(value: AuthEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="116" end="121"> fn from(value: AuthEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payment_intents.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="177" end="208"> pub fn new( status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, connector, auth_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="176" end="176"> use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="230" end="236"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="212" end="226"> fn hash<H: Hasher>(&self, state: &mut H) { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="146" end="151"> fn from(value: PaymentIntentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="137" end="142"> fn from(value: PaymentIntentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payments.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="213" end="248"> pub fn new( currency: Option<Currency>, status: Option<AttemptStatus>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, status, connector, auth_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="212" end="212"> use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, PaymentMethodType, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="272" end="278"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="252" end="268"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.status.map(|i| i.to_string()).hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.client_source.hash(state); self.client_version.hash(state); self.profile_id.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="178" end="183"> fn from(value: PaymentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="169" end="174"> fn from(value: PaymentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_bank_redirect_payment_method_data_eps kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8359" end="8385"> fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8358" end="8358"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8388" end="8407"> fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8340" end="8356"> fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8306" end="8320"> fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3309" end="3316"> pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2937" end="3078"> pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_bank_debit_payment_method_data_ach kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8409" end="8409"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8461" end="8467"> fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8444" end="8458"> fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8388" end="8407"> fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8359" end="8385"> fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3483" end="3492"> pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2217" end="2280"> pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address_inner kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2284" end="2300"> fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2283" end="2283"> use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2358" end="2445"> pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2283" end="2327"> fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2173" end="2212"> fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2085" end="2111"> fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3081" end="3196"> fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3483" end="3492"> pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2541" end="2543"> pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1779" end="1849"> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1778" end="1778"> use std::collections::{HashMap, HashSet}; use std::str::FromStr; use serde::de; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2443" end="2468"> fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1853" end="1865"> fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1792" end="1845"> fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1788" end="1790"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="340" end="391"> fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{}`", err_msg )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{}`", err_msg )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1667" end="1667"> struct FieldVisitor;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3081" end="3196"> fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3080" end="3080"> use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3419" end="3479"> fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3319" end="3337"> fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2800" end="2805"> fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2780" end="2797"> fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2284" end="2300"> fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3309" end="3316"> pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/active_payments.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/active_payments.rs" role="context" start="45" end="47"> pub fn new(time_bucket: Option<String>) -> Self { Self { time_bucket } } <file_sep path="hyperswitch/crates/api_models/src/analytics/active_payments.rs" role="context" start="57" end="63"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/active_payments.rs" role="context" start="51" end="53"> fn hash<H: Hasher>(&self, state: &mut H) { self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/active_payments.rs" role="context" start="31" end="36"> fn from(value: ActivePaymentsMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_card_payment_method_data_empty_string kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8491" end="8500"> fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8490" end="8490"> use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8538" end="8546"> pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8532" end="8537"> pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8470" end="8488"> fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8461" end="8467"> fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1907" end="1947"> pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=visit_i64 kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7867" end="7877"> fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7866" end="7866"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7887" end="7892"> fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7883" end="7885"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7854" end="7865"> fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7850" end="7852"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6233" end="6308"> fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1951" end="1951"> type Error = error_stack::Report<ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1654" end="1658"> pub enum Amount { Value(NonZeroI64), #[default] Zero, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_card_payment_method_data kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8444" end="8458"> fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8443" end="8443"> use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8470" end="8488"> fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8461" end="8467"> fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8388" end="8407"> fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1907" end="1947"> pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1661" end="1666"> fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1721" end="1726"> pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1670" end="1675"> fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1456" end="1458"> pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1452" end="1454"> pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1654" end="1658"> pub enum Amount { Value(NonZeroI64), #[default] Zero, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=is_surcharge_zero kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1444" end="1447"> pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1443" end="1443"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1452" end="1454"> pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1448" end="1450"> pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1359" end="1381"> fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1336" end="1356"> fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=are_optional_values_invalid kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1187" end="1195"> fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1209" end="1219"> pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1203" end="1207"> pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1179" end="1181"> pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="833" end="835"> pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1224" end="1260"> pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_optional_full_name kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4314" end="4324"> pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4313" end="4313"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="5452" end="5483"> fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4326" end="4352"> pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4258" end="4268"> pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3319" end="3337"> fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3318" end="3318"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3495" end="3515"> fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3419" end="3479"> fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3081" end="3196"> fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2800" end="2805"> fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3495" end="3515"> fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3494" end="3494"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3655" end="3663"> fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3581" end="3631"> fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3419" end="3479"> fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3319" end="3337"> fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/admin.rs<|crate|> api_models anchor=mask_value kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2731" end="2752"> fn mask_value(value: &str) -> String { let value_len = value.len(); let masked_value = if value_len <= 4 { "*".repeat(value_len) } else { value .char_indices() .map(|(index, ch)| { if index < 2 || index >= value_len - 2 { // Show the first two and last two characters, mask the rest with '*' ch } else { // Mask the remaining characters '*' } }) .collect::<String>() }; masked_value } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2778" end="2799"> pub fn validate(&self) -> Result<(), &str> { // Validate host domain name let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2754" end="2761"> pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self { let masked_headers = headers .into_iter() .map(|(key, value)| (key, Self::mask_value(value.peek()))) .collect(); Self(masked_headers) } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1702" end="1706"> pub fn get_payment_method_type( &self, ) -> Option<&Vec<payment_methods::RequestPaymentMethodTypes>> { self.payment_method_types.as_ref() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1697" end="1699"> pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2173" end="2212"> fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2172" end="2172"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2283" end="2327"> fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2284" end="2300"> fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2085" end="2111"> fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2044" end="2081"> fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=validate_customer_details_in_request kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1224" end="1260"> pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1223" end="1223"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1274" end="1284"> pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1262" end="1272"> pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1209" end="1219"> pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1203" end="1207"> pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1187" end="1195"> fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="82" end="102"> pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2283" end="2327"> fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2282" end="2282"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2447" end="2485"> pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2358" end="2445"> pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2284" end="2300"> fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2173" end="2212"> fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3483" end="3492"> pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=get_payment_method_create_from_payment_method_migrate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="398" end="442"> pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="397" end="397"> use cards::CardNumber; use crate::payouts; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="458" end="466"> pub fn get_tokenize_connector_id( &self, ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> { self.psp_tokenization .clone() .get_required_value("psp_tokenization") .map(|psp| psp.connector_id) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="447" end="457"> pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!(payment_method_data, PaymentMethodCreateData::Card(_)) } _ => false, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="340" end="391"> fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{}`", err_msg )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{}`", err_msg )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="332" end="337"> fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2718" end="2733"> fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="536" end="569"> pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="297" end="299"> pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="224" end="276"> pub struct PaymentMethodMigrate { /// Merchant id pub merchant_id: id_type::MerchantId, /// The type of payment method use for the payment. pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details pub card: Option<MigrateCardDetail>, /// Network token details pub network_token: Option<MigrateNetworkTokenDetail>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. pub customer_id: Option<id_type::CustomerId>, /// The card network pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] pub wallet: Option<payouts::Wallet>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method pub billing: Option<payments::Address>, /// The connector mandate details of the payment method #[serde(deserialize_with = "deserialize_connector_mandate_details")] pub connector_mandate_details: Option<CommonMandateReference>, // The CIT (customer initiated transaction) transaction id associated with the payment method pub network_transaction_id: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=get_payment_method_create_from_payment_method_migrate kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="398" end="442"> pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="397" end="397"> use cards::CardNumber; use crate::payouts; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="458" end="466"> pub fn get_tokenize_connector_id( &self, ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> { self.psp_tokenization .clone() .get_required_value("psp_tokenization") .map(|psp| psp.connector_id) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="447" end="457"> pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!(payment_method_data, PaymentMethodCreateData::Card(_)) } _ => false, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="340" end="391"> fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{}`", err_msg )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{}`", err_msg )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="332" end="337"> fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2718" end="2733"> fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="536" end="569"> pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="297" end="299"> pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1663" end="1740"> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1662" end="1662"> use std::collections::{HashMap, HashSet}; use std::str::FromStr; use serde::de; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1792" end="1845"> fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1788" end="1790"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1676" end="1736"> fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1672" end="1674"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1853" end="1865"> fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2358" end="2445"> pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2357" end="2357"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2546" end="2566"> fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2447" end="2485"> pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2283" end="2327"> fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2284" end="2300"> fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7903" end="7908"> pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2479" end="2572"> fn try_from( item: ( PaymentMethodRecord, id_type::MerchantId, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_id) = item; // if payment instrument id is present then only construct this let connector_mandate_details = if record.payment_instrument_id.is_some() { Some(PaymentsMandateReference(HashMap::from([( mca_id.get_required_value("merchant_connector_id")?, PaymentsMandateReferenceRecord { connector_mandate_id: record .payment_instrument_id .get_required_value("payment_instrument_id")? .peek() .to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record.original_transaction_currency, }, )]))) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id), card: Some(MigrateCardDetail { card_number: record.raw_card_number.unwrap_or(record.card_number_masked), card_exp_month: record.card_expiry_month, card_exp_year: record.card_expiry_year, card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: Some(record.nick_name.clone()), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.unwrap_or_default(), network_token_exp_month: record.network_token_expiry_month.unwrap_or_default(), network_token_exp_year: record.network_token_expiry_year.unwrap_or_default(), card_holder_name: record.name, nick_name: Some(record.nick_name.clone()), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing: Some(payments::Address { address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), phone: Some(payments::PhoneDetails { number: record.phone, country_code: record.phone_country_code, }), email: record.email, }), connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id, }) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> use std::collections::{HashMap, HashSet}; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, crypto::OptionalEncryptableName, errors, ext_traits::OptionExt, id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; use crate::payouts; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2718" end="2733"> fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2577" end="2600"> fn from(value: (PaymentMethodRecord, id_type::MerchantId)) -> Self { let (record, merchant_id) = value; Self { customer_id: Some(record.customer_id), merchant_id, name: record.name, email: record.email, phone: record.phone, description: None, phone_country_code: record.phone_country_code, address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), metadata: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2443" end="2468"> fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1853" end="1865"> fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2370" end="2404"> pub struct PaymentMethodRecord { pub customer_id: id_type::CustomerId, pub name: Option<masking::Secret<String>>, pub email: Option<pii::Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: masking::Secret<String>, pub payment_instrument_id: Option<masking::Secret<String>>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_scheme: Option<String>, pub original_transaction_id: Option<String>, pub billing_address_zip: masking::Secret<String>, pub billing_address_state: masking::Secret<String>, pub billing_address_first_name: masking::Secret<String>, pub billing_address_last_name: masking::Secret<String>, pub billing_address_city: String, pub billing_address_country: Option<api_enums::CountryAlpha2>, pub billing_address_line1: masking::Secret<String>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub raw_card_number: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub original_transaction_amount: Option<i64>, pub original_transaction_currency: Option<common_enums::Currency>, pub line_number: Option<i64>, pub network_token_number: Option<CardNumber>, pub network_token_expiry_month: Option<masking::Secret<String>>, pub network_token_expiry_year: Option<masking::Secret<String>>, pub network_token_requestor_ref_id: Option<String>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund -----------------------
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payments.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="178" end="183"> fn from(value: PaymentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="252" end="268"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.status.map(|i| i.to_string()).hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.client_source.hash(state); self.client_version.hash(state); self.profile_id.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="213" end="248"> pub fn new( currency: Option<Currency>, status: Option<AttemptStatus>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, status, connector, auth_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="169" end="174"> fn from(value: PaymentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="123" end="131"> fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::AvgTicketSize | Self::SessionizedPaymentProcessedAmount | Self::SessionizedAvgTicketSize ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="64" end="87"> pub enum PaymentDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, PaymentMethod, PaymentMethodType, Currency, #[strum(serialize = "authentication_type")] #[serde(rename = "authentication_type")] AuthType, #[strum(serialize = "status")] #[serde(rename = "status")] PaymentStatus, ClientSource, ClientVersion, ProfileId, CardNetwork, MerchantId, #[strum(serialize = "card_last_4")] #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payments.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="169" end="174"> fn from(value: PaymentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="213" end="248"> pub fn new( currency: Option<Currency>, status: Option<AttemptStatus>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, status, connector, auth_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="178" end="183"> fn from(value: PaymentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="123" end="131"> fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::AvgTicketSize | Self::SessionizedPaymentProcessedAmount | Self::SessionizedAvgTicketSize ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="103" end="120"> pub enum PaymentMetrics { PaymentSuccessRate, PaymentCount, PaymentSuccessCount, PaymentProcessedAmount, AvgTicketSize, RetriesCount, ConnectorSuccessRate, SessionizedPaymentSuccessRate, SessionizedPaymentCount, SessionizedPaymentSuccessCount, SessionizedPaymentProcessedAmount, SessionizedAvgTicketSize, SessionizedRetriesCount, SessionizedConnectorSuccessRate, PaymentsDistribution, FailureReasons, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/frm.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="95" end="100"> fn from(value: FrmDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="125" end="131"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="116" end="121"> fn hash<H: Hasher>(&self, state: &mut H) { self.frm_status.hash(state); self.frm_name.hash(state); self.frm_transaction_type.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="86" end="91"> fn from(value: FrmMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="135" end="148"> pub fn new( frm_status: Option<String>, frm_name: Option<String>, frm_transaction_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { frm_status, frm_name, frm_transaction_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="55" end="59"> pub enum FrmDimensions { FrmStatus, FrmName, FrmTransactionType, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/frm.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="86" end="91"> fn from(value: FrmMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="116" end="121"> fn hash<H: Hasher>(&self, state: &mut H) { self.frm_status.hash(state); self.frm_name.hash(state); self.frm_transaction_type.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="95" end="100"> fn from(value: FrmDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="135" end="148"> pub fn new( frm_status: Option<String>, frm_name: Option<String>, frm_transaction_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { frm_status, frm_name, frm_transaction_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/frm.rs" role="context" start="75" end="78"> pub enum FrmMetrics { FrmTriggeredAttempts, FrmBlockedRate, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payment_intents.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="146" end="151"> fn from(value: PaymentIntentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="212" end="226"> fn hash<H: Hasher>(&self, state: &mut H) { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="177" end="208"> pub fn new( status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, connector, auth_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="137" end="142"> fn from(value: PaymentIntentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="110" end="118"> fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::SmartRetriedAmount | Self::SessionizedPaymentProcessedAmount | Self::SessionizedSmartRetriedAmount ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="59" end="78"> pub enum PaymentIntentDimensions { #[strum(serialize = "status")] #[serde(rename = "status")] PaymentIntentStatus, Currency, ProfileId, Connector, #[strum(serialize = "authentication_type")] #[serde(rename = "authentication_type")] AuthType, PaymentMethod, PaymentMethodType, CardNetwork, MerchantId, #[strum(serialize = "card_last_4")] #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payment_intents.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="137" end="142"> fn from(value: PaymentIntentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="177" end="208"> pub fn new( status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, connector, auth_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="146" end="151"> fn from(value: PaymentIntentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="110" end="118"> fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::SmartRetriedAmount | Self::SessionizedPaymentProcessedAmount | Self::SessionizedSmartRetriedAmount ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/payment_intents.rs" role="context" start="94" end="108"> pub enum PaymentIntentMetrics { SuccessfulSmartRetries, TotalSmartRetries, SmartRetriedAmount, PaymentIntentCount, PaymentsSuccessRate, PaymentProcessedAmount, SessionizedSuccessfulSmartRetries, SessionizedTotalSmartRetries, SessionizedSmartRetriedAmount, SessionizedPaymentIntentCount, SessionizedPaymentsSuccessRate, SessionizedPaymentProcessedAmount, SessionizedPaymentsDistribution, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/api_event.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="60" end="65"> fn from(value: ApiEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="114" end="119"> pub fn new(normalized_time_range: TimeRange) -> Self { Self { time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="95" end="100"> fn from(value: ApiEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="51" end="57"> pub enum ApiEventDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE StatusCode, FlowType, ApiFlow, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/refunds.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="166" end="171"> fn from(value: RefundDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="203" end="209"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="191" end="200"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.refund_status.hash(state); self.connector.hash(state); self.refund_type.hash(state); self.profile_id.hash(state); self.refund_reason.hash(state); self.refund_error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="157" end="162"> fn from(value: RefundMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="141" end="146"> fn is_forex_metric(&self) -> bool { matches!( self, Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="214" end="235"> pub fn new( currency: Option<Currency>, refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, profile_id: Option<String>, refund_reason: Option<String>, refund_error_message: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="68" end="76"> pub enum RefundDimensions { Currency, RefundStatus, Connector, RefundType, ProfileId, RefundReason, RefundErrorMessage, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/auth_events.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="125" end="130"> fn from(value: AuthEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="176" end="185"> fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="151" end="172"> pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="116" end="121"> fn from(value: AuthEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="46" end="56"> pub enum AuthEventDimensions { AuthenticationStatus, #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, AcsReferenceNumber, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/auth_events.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="116" end="121"> fn from(value: AuthEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="151" end="172"> pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="125" end="130"> fn from(value: AuthEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="72" end="83"> pub enum AuthEventMetrics { AuthenticationCount, AuthenticationAttemptCount, AuthenticationSuccessCount, ChallengeFlowCount, FrictionlessFlowCount, FrictionlessSuccessCount, ChallengeAttemptCount, ChallengeSuccessCount, AuthenticationErrorMessage, AuthenticationFunnel, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/disputes.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="74" end="79"> fn from(value: DisputeMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="113" end="119"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="105" end="110"> fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); self.currency.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="65" end="70"> fn from(value: DisputeDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="32" end="37"> fn is_forex_metric(&self) -> bool { matches!( self, Self::TotalAmountDisputed | Self::TotalDisputeLostAmount ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="123" end="136"> pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="23" end="30"> pub enum DisputeMetrics { DisputeStatusMetric, TotalAmountDisputed, TotalDisputeLostAmount, SessionizedDisputeStatusMetric, SessionizedTotalAmountDisputed, SessionizedTotalDisputeLostAmount, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/disputes.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="65" end="70"> fn from(value: DisputeDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="105" end="110"> fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); self.currency.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="74" end="79"> fn from(value: DisputeMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="32" end="37"> fn is_forex_metric(&self) -> bool { matches!( self, Self::TotalAmountDisputed | Self::TotalDisputeLostAmount ) } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="123" end="136"> pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/disputes.rs" role="context" start="56" end="62"> pub enum DisputeDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, DisputeStage, Currency, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/sdk_events.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="144" end="149"> fn from(value: SdkEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="186" end="194"> fn hash<H: Hasher>(&self, state: &mut H) { self.payment_method.hash(state); self.platform.hash(state); self.browser_name.hash(state); self.source.hash(state); self.component.hash(state); self.payment_experience.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="164" end="182"> pub fn new( payment_method: Option<String>, platform: Option<String>, browser_name: Option<String>, source: Option<String>, component: Option<String>, payment_experience: Option<String>, time_bucket: Option<String>, ) -> Self { Self { payment_method, platform, browser_name, source, component, payment_experience, time_bucket, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="135" end="140"> fn from(value: SdkEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="47" end="56"> pub enum SdkEventDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE PaymentMethod, Platform, BrowserName, Source, Component, PaymentExperience, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/admin.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1065" end="1073"> pub fn new( connector_label: String, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { connector_label, merchant_connector_id, } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1064" end="1064"> use common_utils::{ consts, crypto::Encryptable, errors::{self, CustomResult}, ext_traits::Encode, id_type, link_utils, pii, }; <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1276" end="1281"> pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1153" end="1158"> pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="938" end="950"> pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="930" end="936"> pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="242" end="246"> pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { Vec::<PrimaryBusinessDetails>::new().encode_to_value() }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/admin.rs<|crate|> api_models anchor=get_primary_details_as_value kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="242" end="246"> pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { Vec::<PrimaryBusinessDetails>::new().encode_to_value() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="241" end="241"> use common_utils::{ consts, crypto::Encryptable, errors::{self, CustomResult}, ext_traits::Encode, id_type, link_utils, pii, }; <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="383" end="390"> pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="374" end="381"> pub fn get_primary_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.primary_business_details .as_ref() .map(|primary_business_details| primary_business_details.encode_to_value()) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="233" end="240"> pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="224" end="231"> pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1065" end="1073"> pub fn new( connector_label: String, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { connector_label, merchant_connector_id, } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="648" end="653"> pub struct PrimaryBusinessDetails { #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, #[schema(example = "food")] pub business: String, } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="648" end="653"> pub struct PrimaryBusinessDetails { #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, #[schema(example = "food")] pub business: String, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_card_payment_method_data_empty kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8461" end="8467"> fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8491" end="8500"> fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8470" end="8488"> fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8444" end="8458"> fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1907" end="1947"> pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=deserialize kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7903" end="7908"> pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7902" end="7902"> use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::ephemeral_key::EphemeralKeyCreateResponse; use crate::mandates::ProcessorPaymentToken; use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; use crate::enums; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7923" end="7929"> fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7909" end="7914"> pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7894" end="7899"> fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7887" end="7892"> fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2358" end="2445"> pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7841" end="7841"> struct AmountVisitor; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1951" end="1951"> type Error = error_stack::Report<ValidationError>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1654" end="1658"> pub enum Amount { Value(NonZeroI64), #[default] Zero, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6182" end="6189"> fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6181" end="6181"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6204" end="6219"> fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6194" end="6200"> fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6156" end="6165"> fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="6132" end="6152"> fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1806" end="1811"> pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/admin.rs<|crate|> api_models anchor=from_headers kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2754" end="2761"> pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self { let masked_headers = headers .into_iter() .map(|(key, value)| (key, Self::mask_value(value.peek()))) .collect(); Self(masked_headers) } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2753" end="2753"> use std::collections::{HashMap, HashSet}; use masking::{PeekInterface, Secret}; <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2820" end="2844"> pub fn validate(&self) -> Result<(), &str> { let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payment_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .map(|allowed_domains| { allowed_domains .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)) }) .unwrap_or(true); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payment_link_config"); } Ok(()) } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2778" end="2799"> pub fn validate(&self) -> Result<(), &str> { // Validate host domain name let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="2731" end="2752"> fn mask_value(value: &str) -> String { let value_len = value.len(); let masked_value = if value_len <= 4 { "*".repeat(value_len) } else { value .char_indices() .map(|(index, ch)| { if index < 2 || index >= value_len - 2 { // Show the first two and last two characters, mask the rest with '*' ch } else { // Mask the remaining characters '*' } }) .collect::<String>() }; masked_value } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="1702" end="1706"> pub fn get_payment_method_type( &self, ) -> Option<&Vec<payment_methods::RequestPaymentMethodTypes>> { self.payment_method_types.as_ref() }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/api_event.rs<|crate|> api_models anchor=eq kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="129" end="135"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="128" end="128"> use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="123" end="125"> fn hash<H: Hasher>(&self, state: &mut H) { self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/api_event.rs" role="context" start="114" end="119"> pub fn new(normalized_time_range: TimeRange) -> Self { Self { time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/refunds.rs<|crate|> api_models anchor=eq kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="203" end="209"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="202" end="202"> use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="214" end="235"> pub fn new( currency: Option<Currency>, refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, profile_id: Option<String>, refund_reason: Option<String>, refund_error_message: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="191" end="200"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.refund_status.hash(state); self.connector.hash(state); self.refund_type.hash(state); self.profile_id.hash(state); self.refund_reason.hash(state); self.refund_error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/refunds.rs" role="context" start="166" end="171"> fn from(value: RefundDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/payments.rs<|crate|> api_models anchor=eq kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="272" end="278"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="271" end="271"> use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="252" end="268"> fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.status.map(|i| i.to_string()).hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.client_source.hash(state); self.client_version.hash(state); self.profile_id.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/payments.rs" role="context" start="213" end="248"> pub fn new( currency: Option<Currency>, status: Option<AttemptStatus>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, status, connector, auth_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/auth_events.rs<|crate|> api_models anchor=eq kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="189" end="195"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="188" end="188"> use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="176" end="185"> fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.acs_reference_number.hash(state); self.error_message.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/auth_events.rs" role="context" start="151" end="172"> pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/analytics/sdk_events.rs<|crate|> api_models anchor=eq kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="198" end="204"> fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="197" end="197"> use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="186" end="194"> fn hash<H: Hasher>(&self, state: &mut H) { self.payment_method.hash(state); self.platform.hash(state); self.browser_name.hash(state); self.source.hash(state); self.component.hash(state); self.payment_experience.hash(state); self.time_bucket.hash(state); } <file_sep path="hyperswitch/crates/api_models/src/analytics/sdk_events.rs" role="context" start="164" end="182"> pub fn new( payment_method: Option<String>, platform: Option<String>, browser_name: Option<String>, source: Option<String>, component: Option<String>, payment_experience: Option<String>, time_bucket: Option<String>, ) -> Self { Self { payment_method, platform, browser_name, source, component, payment_experience, time_bucket, } }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1002" end="1010"> fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1042" end="1049"> pub fn update(&mut self, new: Self) { if let Some(new_cons) = new.constants { self.constants = Some(new_cons) } if let Some(new_time_scale) = new.time_scale { self.time_scale = Some(new_time_scale) } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1014" end="1038"> pub fn update(&mut self, new: Self) { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_label_info) = new.label_info { new_label_info.iter().for_each(|new_label_info| { if let Some(existing_label_infos) = &mut self.label_info { let mut updated = false; for existing_label_info in &mut *existing_label_infos { if existing_label_info.mca_id == new_label_info.mca_id { existing_label_info.update_target_time(new_label_info); existing_label_info.update_target_count(new_label_info); updated = true; } } if !updated { existing_label_infos.push(new_label_info.clone()); } } else { self.label_info = Some(vec![new_label_info.clone()]); } }); } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="989" end="991"> pub fn update_target_count(&mut self, new: &Self) { self.target_count = new.target_count; } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="985" end="987"> pub fn update_target_time(&mut self, new: &Self) { self.target_time = new.target_time; } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="839" end="853"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(2), default_success_rate: Some(100.0), max_aggregates_size: Some(3), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: Some(5), max_total_count: Some(2), }), specificity_level: SuccessRateSpecificityLevel::default(), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="996" end="999"> pub enum ContractBasedTimeScale { Day, Month, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="969" end="972"> pub struct ContractBasedRoutingConfigBody { pub constants: Option<Vec<f64>>, pub time_scale: Option<ContractBasedTimeScale>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_valid_case_where_customer_details_are_passed_only_once kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1323" end="1333"> fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1359" end="1381"> fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1336" end="1356"> fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1298" end="1312"> pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1286" end="1296"> pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="849" end="1160"> pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="246" end="254"> fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="317" end="337"> fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> { match &value { RoutingAlgorithmSerde::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match value { RoutingAlgorithmSerde::Single(i) => Self::Single(i), RoutingAlgorithmSerde::Priority(i) => Self::Priority(i), RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i), RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i), }) } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="264" end="269"> pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self { Self { routable_connector_choice, status, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="225" end="242"> fn from(value: RoutableChoiceSerde) -> Self { match value { RoutableChoiceSerde::OnlyConnector(connector) => Self { choice_kind: RoutableChoiceKind::OnlyConnector, connector: *connector, merchant_connector_id: None, }, RoutableChoiceSerde::FullStruct { connector, merchant_connector_id, } => Self { choice_kind: RoutableChoiceKind::FullStruct, connector, merchant_connector_id, }, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="216" end="219"> fn eq(&self, other: &Self) -> bool { self.connector.eq(&other.connector) && self.merchant_connector_id.eq(&other.merchant_connector_id) } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1058" end="1063"> pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="182" end="185"> pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="173" end="179"> pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=visit_str kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7780" end="7787"> fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7779" end="7779"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7797" end="7802"> fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7793" end="7795"> fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7776" end="7778"> fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7749" end="7756"> pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4186" end="4195"> pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4186" end="4195"> pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=visit_str kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7702" end="7709"> fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7701" end="7701"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7719" end="7724"> fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7715" end="7717"> fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7698" end="7700"> fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7601" end="7611"> pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4186" end="4195"> pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4186" end="4195"> pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=new kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1549" end="1563"> pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { payment_method_type: pm_type.payment_method_type, payment_experience: pm_type.payment_experience, card_networks: pm_type.card_networks, payment_method: pm, connector, merchant_connector_id, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1548" end="1548"> use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1672" end="1674"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1612" end="1614"> pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { Some(self.payment_method_type) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1498" end="1502"> fn from(value: Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>) -> Self { Self { percentage: value.get_percentage(), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1484" end="1489"> fn from(value: Surcharge) -> Self { match value { Surcharge::Fixed(amount) => Self::Fixed(amount), Surcharge::Rate(percentage) => Self::Rate(percentage.into()), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2718" end="2733"> fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1567" end="1608"> pub struct RequestPaymentMethodTypes { #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, #[schema(value_type = Option<PaymentExperience>)] pub payment_experience: Option<api_enums::PaymentExperience>, #[schema(value_type = Option<Vec<CardNetwork>>)] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<admin::AcceptedCurrencies>, /// List of Countries accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<admin::AcceptedCountries>, /// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) #[schema(example = 1)] pub minimum_amount: Option<MinorUnit>, /// Maximum amount supported by the processor. To be represented in the lowest denomination of /// the target currency (For example, for USD it should be in cents) #[schema(example = 1313)] pub maximum_amount: Option<MinorUnit>, /// Boolean to enable recurring payments / mandates. Default is true. #[schema(default = true, example = false)] pub recurring_enabled: bool, /// Boolean to enable installment / EMI / BNPL payments. Default is true. #[schema(default = true, example = false)] pub installment_payment_enabled: bool, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70"> ADD COLUMN redirection_data JSONB, ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS feature_metadata JSONB; ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); ALTER TABLE refund ADD COLUMN IF NOT EXISTS id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=visit_u64 kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7854" end="7865"> fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7853" end="7853"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7883" end="7885"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7867" end="7877"> fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7850" end="7852"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7827" end="7834"> pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="7696" end="7696"> type Value = PaymentIdType; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1951" end="1951"> type Error = error_stack::Report<ValidationError>; <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="839" end="853"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(2), default_success_rate: Some(100.0), max_aggregates_size: Some(3), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: Some(5), max_total_count: Some(2), }), specificity_level: SuccessRateSpecificityLevel::default(), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="933" end="949"> pub fn update(&mut self, new: Self) { if let Some(min_aggregates_size) = new.min_aggregates_size { self.min_aggregates_size = Some(min_aggregates_size) } if let Some(default_success_rate) = new.default_success_rate { self.default_success_rate = Some(default_success_rate) } if let Some(max_aggregates_size) = new.max_aggregates_size { self.max_aggregates_size = Some(max_aggregates_size) } if let Some(current_block_threshold) = new.current_block_threshold { self.current_block_threshold .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } self.specificity_level = new.specificity_level } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="922" end="929"> 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)); } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="821" end="829"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(2), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="737" end="764"> pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1002" end="1010"> fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="885" end="889"> pub enum SuccessRateSpecificityLevel { #[default] Merchant, Global, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="878" end="881"> pub struct CurrentBlockThreshold { pub duration_in_mins: Option<u64>, pub max_total_count: Option<u64>, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="857" end="865"> pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, Currency, Country, CardNetwork, CardBin, } <file_sep path="hyperswitch/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql" role="context" start="54" end="70"> ADD COLUMN redirection_data JSONB, ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS feature_metadata JSONB; ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_fingerprint_id VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_type_v2 VARCHAR(64), ADD COLUMN IF NOT EXISTS payment_method_subtype VARCHAR(64); ALTER TABLE refund ADD COLUMN IF NOT EXISTS id VARCHAR(64), ADD COLUMN IF NOT EXISTS merchant_reference_id VARCHAR(64), ADD COLUMN IF NOT EXISTS connector_id VARCHAR(64);
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_wallet_payment_method_data_paypal kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8340" end="8356"> fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8339" end="8339"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8388" end="8407"> fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8359" end="8385"> fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8306" end="8320"> fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8261" end="8291"> fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3795" end="3799"> pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3520" end="3578"> pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=test_paylater_payment_method_data_klarna kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8388" end="8407"> fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8387" end="8387"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8444" end="8458"> fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8410" end="8441"> fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8359" end="8385"> fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="8340" end="8356"> fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="1953" end="1983"> fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2504" end="2539"> pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="2137" end="2170"> pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=update_algorithm_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="709" end="735"> pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="708" end="708"> use common_utils::{errors::ParsingError, ext_traits::ValueExt, pii}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="821" end="829"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(2), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="737" end="764"> pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="703" end="705"> pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="697" end="699"> pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1058" end="1063"> pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="915" end="919"> pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="781" end="786"> pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] None, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="673" end="678"> pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/routing.rs<|crate|> api_models anchor=disable_algorithm_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="737" end="764"> pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="736" end="736"> pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="839" end="853"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(2), default_success_rate: Some(100.0), max_aggregates_size: Some(3), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: Some(5), max_total_count: Some(2), }), specificity_level: SuccessRateSpecificityLevel::default(), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="821" end="829"> fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(2), }), } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="709" end="735"> pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="703" end="705"> pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="1058" end="1063"> pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="915" end="919"> pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="689" end="694"> pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } <file_sep path="hyperswitch/crates/api_models/src/routing.rs" role="context" start="673" end="678"> pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3956" end="4000"> fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3955" end="3955"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use masking::{PeekInterface, Secret, WithType}; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4212" end="4232"> fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4004" end="4042"> pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3655" end="3663"> fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3581" end="3631"> fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4374" end="4381"> pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=deserialize_connector_mandate_details kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="340" end="391"> fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{}`", err_msg )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{}`", err_msg )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="339" end="339"> use serde::de; use crate::payouts; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="447" end="457"> pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!(payment_method_data, PaymentMethodCreateData::Card(_)) } _ => false, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="398" end="442"> pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="332" end="337"> fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="326" end="328"> fn from(common_mandate: CommonMandateReference) -> Self { common_mandate.payments.unwrap_or_default() } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1779" end="1849"> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payment_methods.rs<|crate|> api_models anchor=visit_map kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1676" end="1736"> fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1675" end="1675"> use serde::de; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1788" end="1790"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1663" end="1740"> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1672" end="1674"> fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1612" end="1614"> pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { Some(self.payment_method_type) } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1853" end="1865"> fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="2478" end="2478"> type Error = error_stack::Report<errors::ValidationError>; <file_sep path="hyperswitch/crates/api_models/src/payment_methods.rs" role="context" start="1670" end="1670"> type Value = PaymentMethodListRequest;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/api_models/src/payments.rs<|crate|> api_models anchor=get_billing_address kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3419" end="3479"> fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3418" end="3418"> use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3581" end="3631"> fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3495" end="3515"> fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3319" end="3337"> fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="3081" end="3196"> fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4237" end="4239"> fn default() -> Self { Self::PaymentIntentId(Default::default()) } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4275" end="4311"> pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } <file_sep path="hyperswitch/crates/api_models/src/payments.rs" role="context" start="4244" end="4252"> pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } <file_sep path="hyperswitch/crates/api_models/src/payouts.rs" role="context" start="270" end="290"> pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } <file_sep path="hyperswitch/migrations/2025-02-06-111828_drop_int_id_column_accross_database/up.sql" role="context" start="20" end="36"> ------------------------ Payment Attempt ----------------------- ALTER TABLE payment_attempt DROP COLUMN id; ------------------------ Payment Methods ----------------------- ALTER TABLE payment_methods DROP COLUMN IF EXISTS id; ------------------------ Address ----------------------- ALTER TABLE address DROP COLUMN IF EXISTS id; ------------------------ Dispute ----------------------- ALTER TABLE dispute DROP COLUMN IF EXISTS id; ------------------------ Mandate ----------------------- ALTER TABLE mandate DROP COLUMN IF EXISTS id; ------------------------ Refund ----------------------- <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=try_from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="204" end="204"> use common_utils::{errors, ext_traits::ValueExt, link_utils::GenericLinkStatus}; use error_stack::{report, Report, ResultExt}; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="159" end="200"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PaymentMethodCollect => { let link_data = db_val .link_data .parse_value("PaymentMethodCollectLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PaymentMethodCollect(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!( "Invalid status for PaymentMethodCollectLink - {:?}", db_val.link_status ) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!( "Invalid link_type for PaymentMethodCollectLink - {}", db_val.link_type ) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="127" end="154"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let link_data = match db_val.link_type { common_enums::GenericLinkType::PaymentMethodCollect => { let link_data = db_val .link_data .parse_value("PaymentMethodCollectLinkData")?; GenericLinkData::PaymentMethodCollect(link_data) } common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; GenericLinkData::PayoutLink(link_data) } }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status: db_val.link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="84" end="98"> pub async fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="27" end="38"> pub async fn insert_pm_collect_link( self, conn: &PgPooledConn, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="126" end="126"> type Error = Report<errors::ParsingError>; <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="157" end="172"> pub struct PayoutLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: PayoutLinkData, pub link_status: PayoutLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } <file_sep path="hyperswitch/migrations/2024-04-17-084906_add_generic_link_table/up.sql" role="context" start="1" end="14"> CREATE TYPE "GenericLinkType" as ENUM( 'payment_method_collect', 'payout_link' ); CREATE TABLE generic_link ( link_id VARCHAR (64) NOT NULL PRIMARY KEY, primary_reference VARCHAR (64) NOT NULL, merchant_id VARCHAR (64) NOT NULL, created_at timestamp NOT NULL DEFAULT NOW():: timestamp, last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp, expiry timestamp NOT NULL, link_data JSONB NOT NULL, link_status JSONB NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/process_tracker.rs<|crate|> diesel_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="144" end="154"> fn default() -> Self { Self { name: Option::default(), retry_count: Option::default(), schedule_time: Option::default(), tracking_data: Option::default(), business_status: Option::default(), status: Option::default(), updated_at: Some(common_utils::date_time::now()), } } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="143" end="143"> use common_utils::ext_traits::Encode; <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="207" end="212"> fn test_enum_to_string() { let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); let enum_format: ProcessTrackerRunner = string_format.parse_enum("ProcessTrackerRunner").unwrap(); assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="158" end="196"> fn from(process_tracker_update: ProcessTrackerUpdate) -> Self { match process_tracker_update { ProcessTrackerUpdate::Update { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, } => Self { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, }, ProcessTrackerUpdate::StatusUpdate { status, business_status, } => Self { status: Some(status), business_status, ..Default::default() }, ProcessTrackerUpdate::StatusRetryUpdate { status, retry_count, schedule_time, } => Self { status: Some(status), retry_count: Some(retry_count), schedule_time: Some(schedule_time), ..Default::default() }, } } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="73" end="106"> pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> where T: Serialize + std::fmt::Debug, { let current_time = common_utils::date_time::now(); Ok(Self { id: process_tracker_id.into(), name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data .encode_to_value() .change_context(errors::DatabaseError::Others) .attach_printable("Failed to serialize process tracker tracking data")?, business_status: String::from(business_status::PENDING), status: storage_enums::ProcessTrackerStatus::New, event: vec![], created_at: current_time, updated_at: current_time, version: api_version, }) } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="47" end="49"> pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { valid_statuses.iter().any(|&x| x == self.business_status) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/authentication.rs<|crate|> diesel_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/authentication.rs" role="context" start="201" end="233"> fn default() -> Self { Self { connector_authentication_id: Default::default(), payment_method_id: Default::default(), authentication_type: Default::default(), authentication_status: Default::default(), authentication_lifecycle_status: Default::default(), modified_at: common_utils::date_time::now(), error_message: Default::default(), error_code: Default::default(), connector_metadata: Default::default(), maximum_supported_version: Default::default(), threeds_server_transaction_id: Default::default(), cavv: Default::default(), authentication_flow_type: Default::default(), message_version: Default::default(), eci: Default::default(), trans_status: Default::default(), acquirer_bin: Default::default(), acquirer_merchant_id: Default::default(), three_ds_method_data: Default::default(), three_ds_method_url: Default::default(), acs_url: Default::default(), challenge_request: Default::default(), acs_reference_number: Default::default(), acs_trans_id: Default::default(), acs_signed_content: Default::default(), ds_trans_id: Default::default(), directory_server_id: Default::default(), acquirer_country_code: Default::default(), service_details: Default::default(), } } <file_sep path="hyperswitch/crates/diesel_models/src/authentication.rs" role="context" start="309" end="442"> fn from(auth_update: AuthenticationUpdate) -> Self { match auth_update { AuthenticationUpdate::ErrorUpdate { error_message, error_code, authentication_status, connector_authentication_id, } => Self { error_code, error_message, authentication_status: Some(authentication_status), connector_authentication_id, authentication_type: None, authentication_lifecycle_status: None, modified_at: common_utils::date_time::now(), payment_method_id: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PostAuthorizationUpdate { authentication_lifecycle_status, } => Self { connector_authentication_id: None, payment_method_id: None, authentication_type: None, authentication_status: None, authentication_lifecycle_status: Some(authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_message: None, error_code: None, connector_metadata: None, ..Default::default() }, AuthenticationUpdate::PreAuthenticationUpdate { threeds_server_transaction_id, maximum_supported_3ds_version, connector_authentication_id, three_ds_method_data, three_ds_method_url, message_version, connector_metadata, authentication_status, acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), maximum_supported_version: Some(maximum_supported_3ds_version), connector_authentication_id: Some(connector_authentication_id), three_ds_method_data, three_ds_method_url, message_version: Some(message_version), connector_metadata, authentication_status: Some(authentication_status), acquirer_bin, acquirer_merchant_id, directory_server_id, acquirer_country_code, ..Default::default() }, AuthenticationUpdate::AuthenticationUpdate { authentication_value, trans_status, authentication_type, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status, ds_trans_id, } => Self { cavv: authentication_value, trans_status: Some(trans_status), authentication_type: Some(authentication_type), acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status: Some(authentication_status), ds_trans_id, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, authentication_value, eci, authentication_status, } => Self { trans_status: Some(trans_status), cavv: authentication_value, eci, authentication_status: Some(authentication_status), ..Default::default() }, AuthenticationUpdate::PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version, message_version, } => Self { maximum_supported_version: Some(maximum_supported_3ds_version), message_version: Some(message_version), ..Default::default() }, AuthenticationUpdate::PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id, three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, } => Self { threeds_server_transaction_id: Some(threeds_server_transaction_id), three_ds_method_data, three_ds_method_url, acquirer_bin, acquirer_merchant_id, connector_metadata, ..Default::default() }, AuthenticationUpdate::AuthenticationStatusUpdate { trans_status, authentication_status, } => Self { trans_status: Some(trans_status), authentication_status: Some(authentication_status), ..Default::default() }, } } <file_sep path="hyperswitch/crates/diesel_models/src/authentication.rs" role="context" start="237" end="305"> pub fn apply_changeset(self, source: Authentication) -> Authentication { let Self { connector_authentication_id, payment_method_id, authentication_type, authentication_status, authentication_lifecycle_status, modified_at: _, error_code, error_message, connector_metadata, maximum_supported_version, threeds_server_transaction_id, cavv, authentication_flow_type, message_version, eci, trans_status, acquirer_bin, acquirer_merchant_id, three_ds_method_data, three_ds_method_url, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, ds_trans_id, directory_server_id, acquirer_country_code, service_details, } = self; Authentication { connector_authentication_id: connector_authentication_id .or(source.connector_authentication_id), payment_method_id: payment_method_id.unwrap_or(source.payment_method_id), authentication_type: authentication_type.or(source.authentication_type), authentication_status: authentication_status.unwrap_or(source.authentication_status), authentication_lifecycle_status: authentication_lifecycle_status .unwrap_or(source.authentication_lifecycle_status), modified_at: common_utils::date_time::now(), error_code: error_code.or(source.error_code), error_message: error_message.or(source.error_message), connector_metadata: connector_metadata.or(source.connector_metadata), maximum_supported_version: maximum_supported_version .or(source.maximum_supported_version), threeds_server_transaction_id: threeds_server_transaction_id .or(source.threeds_server_transaction_id), cavv: cavv.or(source.cavv), authentication_flow_type: authentication_flow_type.or(source.authentication_flow_type), message_version: message_version.or(source.message_version), eci: eci.or(source.eci), trans_status: trans_status.or(source.trans_status), acquirer_bin: acquirer_bin.or(source.acquirer_bin), acquirer_merchant_id: acquirer_merchant_id.or(source.acquirer_merchant_id), three_ds_method_data: three_ds_method_data.or(source.three_ds_method_data), three_ds_method_url: three_ds_method_url.or(source.three_ds_method_url), acs_url: acs_url.or(source.acs_url), challenge_request: challenge_request.or(source.challenge_request), acs_reference_number: acs_reference_number.or(source.acs_reference_number), acs_trans_id: acs_trans_id.or(source.acs_trans_id), acs_signed_content: acs_signed_content.or(source.acs_signed_content), ds_trans_id: ds_trans_id.or(source.ds_trans_id), directory_server_id: directory_server_id.or(source.directory_server_id), acquirer_country_code: acquirer_country_code.or(source.acquirer_country_code), service_details: service_details.or(source.service_details), ..source } } <file_sep path="hyperswitch/crates/diesel_models/src/authentication.rs" role="context" start="55" end="59"> pub fn is_separate_authn_required(&self) -> bool { self.maximum_supported_version .as_ref() .is_some_and(|version| version.get_major() == 2) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/payment_method.rs<|crate|> diesel_models anchor=from_sql kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1166" end="1206"> fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1165" end="1165"> use common_utils::{ encryption::Encryption, errors::{CustomResult, ParsingError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::{enums as storage_enums, schema::payment_methods}; use crate::{enums as storage_enums, schema_v2::payment_methods}; <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1211" end="1216"> fn from(payment_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payment_reference), payouts: None, } } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1117" end="1157"> fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1098" end="1108"> fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let payments = self.get_mandate_details_value()?; <serde_json::Value as diesel::serialize::ToSql< diesel::sql_types::Jsonb, diesel::pg::Pg, >>::to_sql(&payments, &mut out.reborrow()) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="985" end="987"> pub struct PaymentsTokenReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>, );
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/events.rs<|crate|> diesel_models anchor=apply_filters kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="214" end="267"> fn apply_filters<T>( mut query: T, profile_id: Option<common_utils::id_type::ProfileId>, (column, created_after, created_before): ( dsl::created_at, time::PrimitiveDateTime, time::PrimitiveDateTime, ), limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, ) -> T where T: diesel::query_dsl::methods::LimitDsl<Output = T> + diesel::query_dsl::methods::OffsetDsl<Output = T>, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::GtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::LtEq<dsl::created_at, time::PrimitiveDateTime>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::business_profile_id, common_utils::id_type::ProfileId>, Output = T, >, T: diesel::query_dsl::methods::FilterDsl< diesel::dsl::Eq<dsl::is_overall_delivery_successful, bool>, Output = T, >, { if let Some(profile_id) = profile_id { query = query.filter(dsl::business_profile_id.eq(profile_id)); } query = query .filter(column.ge(created_after)) .filter(column.le(created_before)); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if let Some(is_delivered) = is_delivered { query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered)); } query } <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="213" end="213"> use diesel::{ associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, }; use crate::{ events::{Event, EventNew, EventUpdateInternal}, schema::events::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="269" end="313"> pub async fn count_initial_attempts_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> StorageResult<i64> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .count() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .into_boxed(); query = Self::apply_filters( query, profile_id, (dsl::created_at, created_after, created_before), None, None, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>( query.get_result_async::<i64>(conn), DatabaseOperation::Count, ) .await .change_context(DatabaseError::Others) .attach_printable("Error counting events by constraints") } <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="193" end="212"> pub async fn update_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: EventUpdateInternal, ) -> StorageResult<Self> { generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), event, ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="176" end="191"> pub async fn list_by_profile_id_initial_attempt_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::business_profile_id .eq(profile_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="132" end="174"> pub async fn list_initial_attempts_by_profile_id_constraints( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") } <file_sep path="hyperswitch/crates/diesel_models/src/query/events.rs" role="context" start="52" end="94"> pub async fn list_initial_attempts_by_merchant_id_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, ) -> StorageResult<Vec<Self>> { use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{debug_query, pg::Pg, QueryDsl}; use error_stack::ResultExt; use router_env::logger; use super::generics::db_metrics::{track_database_call, DatabaseOperation}; use crate::errors::DatabaseError; let mut query = Self::table() .filter( dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .order(dsl::created_at.desc()) .into_boxed(); query = Self::apply_filters( query, None, (dsl::created_at, created_after, created_before), limit, offset, is_delivered, ); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<Self, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(DatabaseError::Others) // Query returns empty Vec when no records are found .attach_printable("Error filtering events by constraints") }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generics.rs<|crate|> diesel_models anchor=to_optional kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="446" end="454"> fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> { match arg { Ok(value) => Ok(Some(value)), Err(err) => match err.current_context() { errors::DatabaseError::NotFound => Ok(None), _ => Err(err), }, } } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="445" end="445"> use crate::{errors, PgPooledConn, StorageResult}; <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="404" end="444"> pub async fn generic_filter<T, P, O, R>( conn: &PgPooledConn, predicate: P, limit: Option<i64>, offset: Option<i64>, order: Option<O>, ) -> StorageResult<Vec<R>> where T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + 'static, IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>> + LimitDsl<Output = IntoBoxed<'static, T, Pg>> + OffsetDsl<Output = IntoBoxed<'static, T, Pg>> + OrderDsl<O, Output = IntoBoxed<'static, T, Pg>> + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send, O: Expression, R: Send + 'static, { let mut query = T::table().into_boxed(); query = query.filter(predicate); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if let Some(order) = order { query = query.order(order); } logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(errors::DatabaseError::NotFound) .attach_printable("Error filtering records by predicate") } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="392" end="402"> pub async fn generic_find_one_optional<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<Option<R>> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="350" end="363"> pub async fn generic_find_by_id_optional<T, Pk, R>( conn: &PgPooledConn, id: Pk, ) -> StorageResult<Option<R>> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, <T as HasTable>::Table: FindDsl<Pk>, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await) } <file_sep path="hyperswitch/crates/diesel_models/src/errors.rs" role="context" start="2" end="16"> pub enum DatabaseError { #[error("An error occurred when obtaining database connection")] DatabaseConnectionError, #[error("The requested resource was not found in the database")] NotFound, #[error("A unique constraint violation occurred")] UniqueViolation, #[error("No fields were provided to be updated")] NoFieldsToUpdate, #[error("An error occurred when generating typed SQL query")] QueryGenerationFailed, // InsertFailed, #[error("An unknown error occurred")] Others, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/payment_method.rs<|crate|> diesel_models anchor=to_sql kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1098" end="1108"> fn to_sql<'b>( &'b self, out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>, ) -> diesel::serialize::Result { let payments = self.get_mandate_details_value()?; <serde_json::Value as diesel::serialize::ToSql< diesel::sql_types::Jsonb, diesel::pg::Pg, >>::to_sql(&payments, &mut out.reborrow()) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1097" end="1097"> use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::{enums as storage_enums, schema::payment_methods}; use crate::{enums as storage_enums, schema_v2::payment_methods}; <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1166" end="1206"> fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsTokenReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1117" end="1157"> fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { let value = <serde_json::Value as diesel::deserialize::FromSql< diesel::sql_types::Jsonb, DB, >>::from_sql(bytes)?; let payments_data = value .clone() .as_object_mut() .map(|obj| { obj.remove("payouts"); serde_json::from_value::<PaymentsMandateReference>(serde_json::Value::Object( obj.clone(), )) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payments data", )) }) .transpose()?; let payouts_data = serde_json::from_value::<Option<Self>>(value) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {}", err); }) .change_context(ParsingError::StructParseFailure( "Failed to parse payouts data", )) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) })?; Ok(Self { payments: payments_data, payouts: payouts_data, }) } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1079" end="1094"> pub fn insert_payment_token_reference_record( &mut self, connector_id: &common_utils::id_type::MerchantConnectorAccountId, record: ConnectorTokenReferenceRecord, ) { match self.payments { Some(ref mut payments_reference) => { payments_reference.insert(connector_id.clone(), record); } None => { let mut payments_reference = HashMap::new(); payments_reference.insert(connector_id.clone(), record); self.payments = Some(PaymentsTokenReference(payments_reference)); } } } <file_sep path="hyperswitch/crates/diesel_models/src/payment_method.rs" role="context" start="1055" end="1075"> pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> { let mut payments = self .payments .as_ref() .map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value) .change_context(ParsingError::StructParseFailure("payment mandate details"))?; self.payouts .as_ref() .map(|payouts_mandate| { serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| { payments.as_object_mut().map(|payments_object| { payments_object.insert("payouts".to_string(), payouts_mandate_value); }) }) }) .transpose() .change_context(ParsingError::StructParseFailure("payout mandate details"))?; Ok(payments) }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/generic_link.rs<|crate|> diesel_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="83" end="99"> fn default() -> Self { let now = common_utils::date_time::now(); Self { link_id: String::default(), primary_reference: String::default(), merchant_id: common_utils::id_type::MerchantId::default(), created_at: Some(now), last_modified_at: Some(now), expiry: now + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY), link_data: serde_json::Value::default(), link_status: GenericLinkStatus::default(), link_type: common_enums::GenericLinkType::default(), url: Secret::default(), return_url: Option::default(), } } <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="82" end="82"> use common_utils::{ consts, link_utils::{ EnabledPaymentMethod, GenericLinkStatus, GenericLinkUiConfig, PaymentMethodCollectStatus, PayoutLinkData, PayoutLinkStatus, }, }; use masking::Secret; use time::{Duration, PrimitiveDateTime}; <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="116" end="121"> pub fn get_payout_link_data(&self) -> Result<&PayoutLinkData, String> { match self { Self::PayoutLink(pl) => Ok(pl), _ => Err("Invalid link type for fetching payout link data".to_string()), } } <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="110" end="115"> pub fn get_payment_method_collect_data(&self) -> Result<&PaymentMethodCollectLinkData, String> { match self { Self::PaymentMethodCollect(pm) => Ok(pm), _ => Err("Invalid link type for fetching payment method collect data".to_string()), } } <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="698" end="700"> pub struct MerchantId { pub merchant_id: id_type::MerchantId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/process_tracker.rs<|crate|> diesel_models anchor=from kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=1<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="158" end="196"> fn from(process_tracker_update: ProcessTrackerUpdate) -> Self { match process_tracker_update { ProcessTrackerUpdate::Update { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, } => Self { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, }, ProcessTrackerUpdate::StatusUpdate { status, business_status, } => Self { status: Some(status), business_status, ..Default::default() }, ProcessTrackerUpdate::StatusRetryUpdate { status, retry_count, schedule_time, } => Self { status: Some(status), retry_count: Some(retry_count), schedule_time: Some(schedule_time), ..Default::default() }, } } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="207" end="212"> fn test_enum_to_string() { let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); let enum_format: ProcessTrackerRunner = string_format.parse_enum("ProcessTrackerRunner").unwrap(); assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="144" end="154"> fn default() -> Self { Self { name: Option::default(), retry_count: Option::default(), schedule_time: Option::default(), tracking_data: Option::default(), business_status: Option::default(), status: Option::default(), updated_at: Some(common_utils::date_time::now()), } } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="73" end="106"> pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> where T: Serialize + std::fmt::Debug, { let current_time = common_utils::date_time::now(); Ok(Self { id: process_tracker_id.into(), name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data .encode_to_value() .change_context(errors::DatabaseError::Others) .attach_printable("Failed to serialize process tracker tracking data")?, business_status: String::from(business_status::PENDING), status: storage_enums::ProcessTrackerStatus::New, event: vec![], created_at: current_time, updated_at: current_time, version: api_version, }) } <file_sep path="hyperswitch/crates/diesel_models/src/process_tracker.rs" role="context" start="110" end="129"> pub enum ProcessTrackerUpdate { Update { name: Option<String>, retry_count: Option<i32>, schedule_time: Option<PrimitiveDateTime>, tracking_data: Option<serde_json::Value>, business_status: Option<String>, status: Option<storage_enums::ProcessTrackerStatus>, updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { status: storage_enums::ProcessTrackerStatus, business_status: Option<String>, }, StatusRetryUpdate { status: storage_enums::ProcessTrackerStatus, retry_count: i32, schedule_time: PrimitiveDateTime, }, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/user_role.rs<|crate|> diesel_models anchor=check_user_in_lineage kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="29" end="76"> fn check_user_in_lineage( tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { // Checking in user roles, for a user in token hierarchy, only one of the relations will be true: // either tenant level, org level, merchant level, or profile level // Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null) // Org-level: (org_id = ? && merchant_id = null && profile_id = null) // Merchant-level: (org_id = ? && merchant_id = ? && profile_id = null) // Profile-level: (org_id = ? && merchant_id = ? && profile_id = ?) Box::new( // Tenant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .or( // Org-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ) .or( // Merchant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::profile_id.is_null()), ) .or( // Profile-level condition dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ), ) } <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="28" end="28"> use common_utils::id_type; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use crate::{ enums::{UserRoleVersion, UserStatus}, errors, query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="103" end="155"> pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, update: UserRoleUpdate, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .or( // Org-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ) .or( // Merchant-level condition dsl::tenant_id .eq(tenant_id.clone()) .and(dsl::org_id.eq(org_id.clone())) .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::profile_id.is_null()), ) .or( // Profile-level condition dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, UserRoleUpdateInternal, _, _, >(conn, predicate, update.into()) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="78" end="100"> pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = Self::check_user_in_lineage( tenant_id, Some(org_id), Some(merchant_id), Some(profile_id), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="23" end="25"> pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> { generics::generic_insert(conn, self).await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user_role.rs" role="context" start="157" end="180"> pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { let check_lineage = Self::check_user_in_lineage( tenant_id, Some(org_id), Some(merchant_id), Some(profile_id), ); let predicate = dsl::user_id .eq(user_id) .and(check_lineage) .and(dsl::version.eq(version)); generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate) .await } <file_sep path="hyperswitch/crates/diesel_models/src/business_profile.rs" role="context" start="22" end="73"> pub struct Profile { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: bool, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: bool, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub is_recon_enabled: bool, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub payment_link_config: Option<BusinessPaymentLinkConfig>, pub session_expiry: Option<i64>, pub authentication_connector_details: Option<AuthenticationConnectorDetails>, pub payout_link_config: Option<BusinessPayoutLinkConfig>, pub is_extended_card_info_enabled: Option<bool>, pub extended_card_info_config: Option<pii::SecretSerdeValue>, pub is_connector_agnostic_mit_enabled: Option<bool>, pub use_billing_as_payment_method_billing: Option<bool>, pub collect_shipping_details_from_wallet_connector: Option<bool>, pub collect_billing_details_from_wallet_connector: Option<bool>, pub outgoing_webhook_custom_http_headers: Option<Encryption>, pub always_collect_billing_details_from_wallet_connector: Option<bool>, pub always_collect_shipping_details_from_wallet_connector: Option<bool>, pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_tax_connector_enabled: Option<bool>, pub version: common_enums::ApiVersion, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, pub is_click_to_pay_enabled: bool, pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, pub is_clear_pan_retries_enabled: bool, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, } <file_sep path="hyperswitch-card-vault/migrations/2023-10-21-104200_create-tables/up.sql" role="context" start="1" end="11"> -- Your SQL goes here CREATE TABLE merchant ( id SERIAL, tenant_id VARCHAR(255) NOT NULL, merchant_id VARCHAR(255) NOT NULL, enc_key BYTEA NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT now()::TIMESTAMP, PRIMARY KEY (tenant_id, merchant_id) ); <file_sep path="hyperswitch/crates/api_models/src/admin.rs" role="context" start="698" end="700"> pub struct MerchantId { pub merchant_id: id_type::MerchantId, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/mandate.rs<|crate|> diesel_models anchor=convert_to_mandate_update kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="104" end="111"> pub fn convert_to_mandate_update( self, storage_scheme: MerchantStorageScheme, ) -> MandateUpdateInternal { let mut updated_object = MandateUpdateInternal::from(self); updated_object.updated_by = Some(storage_scheme.to_string()); updated_object } <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="103" end="103"> use common_enums::MerchantStorageScheme; <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="184" end="205"> pub fn apply_changeset(self, source: Mandate) -> Mandate { let Self { mandate_status, amount_captured, connector_mandate_ids, connector_mandate_id, payment_method_id, original_payment_id, updated_by, } = self; Mandate { mandate_status: mandate_status.unwrap_or(source.mandate_status), amount_captured: amount_captured.map_or(source.amount_captured, Some), connector_mandate_ids: connector_mandate_ids.map_or(source.connector_mandate_ids, Some), connector_mandate_id: connector_mandate_id.map_or(source.connector_mandate_id, Some), payment_method_id: payment_method_id.unwrap_or(source.payment_method_id), original_payment_id: original_payment_id.map_or(source.original_payment_id, Some), updated_by: updated_by.map_or(source.updated_by, Some), ..source } } <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="141" end="180"> fn from(mandate_update: MandateUpdate) -> Self { match mandate_update { MandateUpdate::StatusUpdate { mandate_status } => Self { mandate_status: Some(mandate_status), connector_mandate_ids: None, amount_captured: None, connector_mandate_id: None, payment_method_id: None, original_payment_id: None, updated_by: None, }, MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { mandate_status: None, amount_captured, connector_mandate_ids: None, connector_mandate_id: None, payment_method_id: None, original_payment_id: None, updated_by: None, }, MandateUpdate::ConnectorReferenceUpdate { connector_mandate_ids, } => Self { connector_mandate_ids, ..Default::default() }, MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id, connector_mandate_ids, payment_method_id, original_payment_id, } => Self { connector_mandate_id, connector_mandate_ids, payment_method_id: Some(payment_method_id), original_payment_id, ..Default::default() }, } } <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="79" end="81"> pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="209" end="238"> fn from(mandate_new: &MandateNew) -> Self { Self { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id.clone(), merchant_id: mandate_new.merchant_id.clone(), payment_method_id: mandate_new.payment_method_id.clone(), mandate_status: mandate_new.mandate_status, mandate_type: mandate_new.mandate_type, customer_accepted_at: mandate_new.customer_accepted_at, customer_ip_address: mandate_new.customer_ip_address.clone(), customer_user_agent: mandate_new.customer_user_agent.clone(), network_transaction_id: mandate_new.network_transaction_id.clone(), previous_attempt_id: mandate_new.previous_attempt_id.clone(), created_at: mandate_new .created_at .unwrap_or_else(common_utils::date_time::now), mandate_amount: mandate_new.mandate_amount, mandate_currency: mandate_new.mandate_currency, amount_captured: mandate_new.amount_captured, connector: mandate_new.connector.clone(), connector_mandate_id: mandate_new.connector_mandate_id.clone(), start_date: mandate_new.start_date, end_date: mandate_new.end_date, metadata: mandate_new.metadata.clone(), connector_mandate_ids: mandate_new.connector_mandate_ids.clone(), original_payment_id: mandate_new.original_payment_id.clone(), merchant_connector_id: mandate_new.merchant_connector_id.clone(), updated_by: mandate_new.updated_by.clone(), } } <file_sep path="hyperswitch/crates/diesel_models/src/mandate.rs" role="context" start="130" end="138"> pub struct MandateUpdateInternal { mandate_status: Option<storage_enums::MandateStatus>, amount_captured: Option<i64>, connector_mandate_ids: Option<pii::SecretSerdeValue>, connector_mandate_id: Option<String>, payment_method_id: Option<String>, original_payment_id: Option<common_utils::id_type::PaymentId>, updated_by: Option<String>, } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="41" end="55"> pm.collectionVariables.set("mandate_id", jsonData.mandate_id); console.log( "- use {{mandate_id}} as collection variable for value", jsonData.mandate_id, ); } else { console.log( "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.", ); } // pm.collectionVariables - Set client_secret as variable for jsonData.client_secret if (jsonData?.client_secret) { pm.collectionVariables.set("client_secret", jsonData.client_secret); console.log(
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/user/theme.rs<|crate|> diesel_models anchor=find_by_lineage kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="123" end="132"> pub async fn find_by_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, Self::lineage_filter(lineage), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="122" end="122"> use common_utils::types::theme::ThemeLineage; use diesel::{ associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, }; use crate::{ errors::DatabaseError, query::generics::{ self, db_metrics::{track_database_call, DatabaseOperation}, }, schema::themes::dsl, user::theme::{Theme, ThemeNew}, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="134" end="146"> pub async fn delete_by_theme_id_and_lineage( conn: &PgPooledConn, theme_id: String, lineage: ThemeLineage, ) -> StorageResult<Self> { generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id .eq(theme_id) .and(Self::lineage_filter(lineage)), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="88" end="121"> pub async fn find_most_specific_theme_in_lineage( conn: &PgPooledConn, lineage: ThemeLineage, ) -> StorageResult<Self> { let query = <Self as HasTable>::table().into_boxed(); let query = lineage .get_same_and_higher_lineages() .into_iter() .fold(query, |mut query, lineage| { query = query.or_filter(Self::lineage_filter(lineage)); query }); logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); let data: Vec<Self> = match track_database_call::<Self, _, _>( query.get_results_async(conn), DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), _ => Err(report!(err)).change_context(DatabaseError::Others), }, }?; data.into_iter() .min_by_key(|theme| theme.entity_type) .ok_or(report!(DatabaseError::NotFound)) } <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="80" end="86"> pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::theme_id.eq(theme_id), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/user/theme.rs" role="context" start="32" end="78"> fn lineage_filter( lineage: ThemeLineage, ) -> Box< dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + 'static, > { match lineage { ThemeLineage::Tenant { tenant_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.is_null()) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()) .nullable(), ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.is_null()) .and(dsl::profile_id.is_null()), ), ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.is_null()), ), ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => Box::new( dsl::tenant_id .eq(tenant_id) .and(dsl::org_id.eq(org_id)) .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), ), } } <file_sep path="hyperswitch/crates/diesel_models/src/lib.rs" role="context" start="66" end="66"> pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/gsm.rs<|crate|> diesel_models anchor=retrieve_decision kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="35" end="46"> pub async fn retrieve_decision( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<String> { Self::find(conn, connector, flow, sub_flow, code, message) .await .map(|item| item.decision) } <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="34" end="34"> use crate::{ errors, gsm::*, query::generics, schema::gateway_status_map::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="81" end="99"> pub async fn delete( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="48" end="79"> pub async fn update( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, gsm: GatewayStatusMappingUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::< <Self as HasTable>::Table, GatewayStatusMapperUpdateInternal, _, _, >( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), gsm.into(), ) .await? .first() .cloned() .ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Error while updating gsm entry") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="15" end="33"> pub async fn find( conn: &PgPooledConn, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector .eq(connector) .and(dsl::flow.eq(flow)) .and(dsl::sub_flow.eq(sub_flow)) .and(dsl::code.eq(code)) .and(dsl::message.eq(message)), ) .await } <file_sep path="hyperswitch/crates/diesel_models/src/query/gsm.rs" role="context" start="9" end="11"> pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GatewayStatusMap> { generics::generic_insert(conn, self).await } <file_sep path="hyperswitch/crates/diesel_models/src/lib.rs" role="context" start="66" end="66"> pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=insert kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="17" end="25"> pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GenericLinkState> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="16" end="16"> use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="40" end="48"> pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="27" end="38"> pub async fn insert_pm_collect_link( self, conn: &PgPooledConn, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="19" end="34"> pub struct GenericLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: serde_json::Value, pub link_status: GenericLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } <file_sep path="hyperswitch/migrations/2024-04-17-084906_add_generic_link_table/up.sql" role="context" start="1" end="14"> CREATE TYPE "GenericLinkType" as ENUM( 'payment_method_collect', 'payout_link' ); CREATE TABLE generic_link ( link_id VARCHAR (64) NOT NULL PRIMARY KEY, primary_reference VARCHAR (64) NOT NULL, merchant_id VARCHAR (64) NOT NULL, created_at timestamp NOT NULL DEFAULT NOW():: timestamp, last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp, expiry timestamp NOT NULL, link_data JSONB NOT NULL, link_status JSONB NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=insert_payout_link kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="40" end="48"> pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="39" end="39"> use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="68" end="82"> pub async fn find_pm_collect_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="52" end="66"> pub async fn find_generic_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<GenericLinkState> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="27" end="38"> pub async fn insert_pm_collect_link( self, conn: &PgPooledConn, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="17" end="25"> pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GenericLinkState> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="157" end="172"> pub struct PayoutLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: PayoutLinkData, pub link_status: PayoutLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, } <file_sep path="hyperswitch/migrations/2024-04-17-084906_add_generic_link_table/up.sql" role="context" start="1" end="14"> CREATE TYPE "GenericLinkType" as ENUM( 'payment_method_collect', 'payout_link' ); CREATE TABLE generic_link ( link_id VARCHAR (64) NOT NULL PRIMARY KEY, primary_reference VARCHAR (64) NOT NULL, merchant_id VARCHAR (64) NOT NULL, created_at timestamp NOT NULL DEFAULT NOW():: timestamp, last_modified_at timestamp NOT NULL DEFAULT NOW():: timestamp, expiry timestamp NOT NULL, link_data JSONB NOT NULL, link_status JSONB NOT NULL,
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generics.rs<|crate|> diesel_models anchor=generic_find_one_optional kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="392" end="402"> pub async fn generic_find_one_optional<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<Option<R>> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="391" end="391"> use diesel::{ associations::HasTable, debug_query, dsl::{Find, Limit}, helper_types::{Filter, IntoBoxed}, insertable::CanInsertInSingleQuery, pg::{Pg, PgConnection}, query_builder::{ AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment, QueryId, UpdateStatement, }, query_dsl::{ methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl}, LoadQuery, RunQueryDsl, }, result::Error as DieselError, Expression, Insertable, QueryDsl, QuerySource, Table, }; use crate::{errors, PgPooledConn, StorageResult}; <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="446" end="454"> fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> { match arg { Ok(value) => Ok(Some(value)), Err(err) => match err.current_context() { errors::DatabaseError::NotFound => Ok(None), _ => Err(err), }, } } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="404" end="444"> pub async fn generic_filter<T, P, O, R>( conn: &PgPooledConn, predicate: P, limit: Option<i64>, offset: Option<i64>, order: Option<O>, ) -> StorageResult<Vec<R>> where T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + 'static, IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>> + LimitDsl<Output = IntoBoxed<'static, T, Pg>> + OffsetDsl<Output = IntoBoxed<'static, T, Pg>> + OrderDsl<O, Output = IntoBoxed<'static, T, Pg>> + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send, O: Expression, R: Send + 'static, { let mut query = T::table().into_boxed(); query = query.filter(predicate); if let Some(limit) = limit { query = query.limit(limit); } if let Some(offset) = offset { query = query.offset(offset); } if let Some(order) = order { query = query.order(order); } logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter) .await .change_context(errors::DatabaseError::NotFound) .attach_printable("Error filtering records by predicate") } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="383" end="390"> pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { generic_find_one_core::<T, _, _>(conn, predicate).await } <file_sep path="hyperswitch/crates/diesel_models/src/query/generics.rs" role="context" start="365" end="381"> async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + 'static, { let query = <T as HasTable>::table().filter(predicate); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne) .await .map_err(|err| match err { DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound), _ => report!(err).change_context(errors::DatabaseError::Others), }) .attach_printable("Error finding record by predicate") } <file_sep path="hyperswitch/crates/diesel_models/src/lib.rs" role="context" start="66" end="66"> pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/payouts.rs<|crate|> diesel_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/payouts.rs" role="context" start="140" end="161"> fn default() -> Self { Self { amount: None, destination_currency: None, source_currency: None, description: None, recurring: None, auto_fulfill: None, return_url: None, entity_type: None, metadata: None, payout_method_id: None, profile_id: None, status: None, last_modified_at: common_utils::date_time::now(), attempt_count: None, confirm: None, payout_type: None, address_id: None, customer_id: None, } } <file_sep path="hyperswitch/crates/diesel_models/src/payouts.rs" role="context" start="139" end="139"> use common_utils::{pii, types::MinorUnit}; <file_sep path="hyperswitch/crates/diesel_models/src/payouts.rs" role="context" start="222" end="264"> pub fn apply_changeset(self, source: Payouts) -> Payouts { let PayoutsUpdateInternal { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, payout_method_id, profile_id, status, last_modified_at, attempt_count, confirm, payout_type, address_id, customer_id, } = self.into(); Payouts { amount: amount.unwrap_or(source.amount), destination_currency: destination_currency.unwrap_or(source.destination_currency), source_currency: source_currency.unwrap_or(source.source_currency), description: description.or(source.description), recurring: recurring.unwrap_or(source.recurring), auto_fulfill: auto_fulfill.unwrap_or(source.auto_fulfill), return_url: return_url.or(source.return_url), entity_type: entity_type.unwrap_or(source.entity_type), metadata: metadata.or(source.metadata), payout_method_id: payout_method_id.or(source.payout_method_id), profile_id: profile_id.unwrap_or(source.profile_id), status: status.unwrap_or(source.status), last_modified_at, attempt_count: attempt_count.unwrap_or(source.attempt_count), confirm: confirm.or(source.confirm), payout_type: payout_type.or(source.payout_type), address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), ..source } } <file_sep path="hyperswitch/crates/diesel_models/src/payouts.rs" role="context" start="165" end="218"> fn from(payout_update: PayoutsUpdate) -> Self { match payout_update { PayoutsUpdate::Update { amount, destination_currency, source_currency, description, recurring, auto_fulfill, return_url, entity_type, metadata, profile_id, status, confirm, payout_type, address_id, customer_id, } => Self { amount: Some(amount), destination_currency: Some(destination_currency), source_currency: Some(source_currency), description, recurring: Some(recurring), auto_fulfill: Some(auto_fulfill), return_url, entity_type: Some(entity_type), metadata, profile_id, status, confirm, payout_type, address_id, customer_id, ..Default::default() }, PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self { payout_method_id: Some(payout_method_id), ..Default::default() }, PayoutsUpdate::RecurringUpdate { recurring } => Self { recurring: Some(recurring), ..Default::default() }, PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self { attempt_count: Some(attempt_count), ..Default::default() }, PayoutsUpdate::StatusUpdate { status } => Self { status: Some(status), ..Default::default() }, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=find_payout_link_by_link_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="84" end="98"> pub async fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="83" end="83"> use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="127" end="154"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let link_data = match db_val.link_type { common_enums::GenericLinkType::PaymentMethodCollect => { let link_data = db_val .link_data .parse_value("PaymentMethodCollectLinkData")?; GenericLinkData::PaymentMethodCollect(link_data) } common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; GenericLinkData::PayoutLink(link_data) } }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status: db_val.link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="102" end="122"> pub async fn update_payout_link( self, conn: &PgPooledConn, payout_link_update: PayoutLinkUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::link_id.eq(self.link_id.to_owned()), GenericLinkUpdateInternal::from(payout_link_update), ) .await .and_then(|mut payout_links| { payout_links .pop() .ok_or(error_stack::report!(db_errors::DatabaseError::NotFound)) }) .or_else(|error| match error.current_context() { db_errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="68" end="82"> pub async fn find_pm_collect_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="52" end="66"> pub async fn find_generic_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<GenericLinkState> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/generic_link.rs" role="context" start="157" end="172"> pub struct PayoutLink { pub link_id: String, pub primary_reference: String, pub merchant_id: common_utils::id_type::MerchantId, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: PrimitiveDateTime, pub link_data: PayoutLinkData, pub link_status: PayoutLinkStatus, pub link_type: storage_enums::GenericLinkType, pub url: Secret<String>, pub return_url: Option<String>, }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=find_generic_link_by_link_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="52" end="66"> pub async fn find_generic_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<GenericLinkState> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="51" end="51"> use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="84" end="98"> pub async fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="68" end="82"> pub async fn find_pm_collect_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="40" end="48"> pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="27" end="38"> pub async fn insert_pm_collect_link( self, conn: &PgPooledConn, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/lib.rs" role="context" start="66" end="66"> pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/payout_attempt.rs<|crate|> diesel_models anchor=default kind=fn pack=symbol_neighborhood lang=rust role_window=k2 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/payout_attempt.rs" role="context" start="134" end="154"> fn default() -> Self { Self { payout_token: None, connector_payout_id: None, status: None, error_message: None, error_code: None, is_eligible: None, business_country: None, business_label: None, connector: None, routing_info: None, merchant_connector_id: None, last_modified_at: common_utils::date_time::now(), address_id: None, customer_id: None, unified_code: None, unified_message: None, additional_payout_method_data: None, } } <file_sep path="hyperswitch/crates/diesel_models/src/payout_attempt.rs" role="context" start="133" end="133"> use common_utils::{ payout_method_utils, types::{UnifiedCode, UnifiedMessage}, }; <file_sep path="hyperswitch/crates/diesel_models/src/payout_attempt.rs" role="context" start="215" end="256"> pub fn apply_changeset(self, source: PayoutAttempt) -> PayoutAttempt { let PayoutAttemptUpdateInternal { payout_token, connector_payout_id, status, error_message, error_code, is_eligible, business_country, business_label, connector, routing_info, last_modified_at, address_id, customer_id, merchant_connector_id, unified_code, unified_message, additional_payout_method_data, } = self.into(); PayoutAttempt { payout_token: payout_token.or(source.payout_token), connector_payout_id: connector_payout_id.or(source.connector_payout_id), status: status.unwrap_or(source.status), error_message: error_message.or(source.error_message), error_code: error_code.or(source.error_code), is_eligible: is_eligible.or(source.is_eligible), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), connector: connector.or(source.connector), routing_info: routing_info.or(source.routing_info), last_modified_at, address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), additional_payout_method_data: additional_payout_method_data .or(source.additional_payout_method_data), ..source } } <file_sep path="hyperswitch/crates/diesel_models/src/payout_attempt.rs" role="context" start="158" end="211"> fn from(payout_update: PayoutAttemptUpdate) -> Self { match payout_update { PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self { payout_token: Some(payout_token), ..Default::default() }, PayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, unified_code, unified_message, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { business_country, business_label, address_id, customer_id, } => Self { business_country, business_label, address_id, customer_id, ..Default::default() }, PayoutAttemptUpdate::UpdateRouting { connector, routing_info, merchant_connector_id, } => Self { connector: Some(connector), routing_info, merchant_connector_id, ..Default::default() }, PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate { additional_payout_method_data, } => Self { additional_payout_method_data, ..Default::default() }, } } <file_sep path="hyperswitch/postman/collection-dir/powertranz/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js" role="context" start="61" end="78"> "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.", ); } // Response body should have value "succeeded" for "status" if (jsonData?.status) { pm.test( "[POST]::/payments - Content check if value for 'status' matches 'succeeded'", function () { pm.expect(jsonData.status).to.eql("succeeded"); }, ); }
symbol_neighborhood
<|meta_start|><|file|> hyperswitch/crates/diesel_models/src/query/generic_link.rs<|crate|> diesel_models anchor=find_pm_collect_link_by_link_id kind=fn pack=symbol_neighborhood lang=rust role_window=k3 hops=2<|meta_end|> <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="68" end="82"> pub async fn find_pm_collect_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PaymentMethodCollectLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PaymentMethodCollectLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payment method collect link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="67" end="67"> use diesel::{associations::HasTable, ExpressionMethods}; use super::generics; use crate::{ errors as db_errors, generic_link::{ GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal, PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate, }, schema::generic_link::dsl, PgPooledConn, StorageResult, }; <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="102" end="122"> pub async fn update_payout_link( self, conn: &PgPooledConn, payout_link_update: PayoutLinkUpdate, ) -> StorageResult<Self> { generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>( conn, dsl::link_id.eq(self.link_id.to_owned()), GenericLinkUpdateInternal::from(payout_link_update), ) .await .and_then(|mut payout_links| { payout_links .pop() .ok_or(error_stack::report!(db_errors::DatabaseError::NotFound)) }) .or_else(|error| match error.current_context() { db_errors::DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="84" end="98"> pub async fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="52" end="66"> pub async fn find_generic_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<GenericLinkState> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::link_id.eq(link_id.to_owned()), ) .await .and_then(|res: Self| { GenericLinkState::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse generic link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="40" end="48"> pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> { generics::generic_insert(conn, self) .await .and_then(|res: GenericLink| { PayoutLink::try_from(res) .change_context(db_errors::DatabaseError::Others) .attach_printable("failed to parse payout link data from DB") }) } <file_sep path="hyperswitch/crates/diesel_models/src/query/generic_link.rs" role="context" start="205" end="238"> fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> { let (link_data, link_status) = match db_val.link_type { common_enums::GenericLinkType::PayoutLink => { let link_data = db_val.link_data.parse_value("PayoutLinkData")?; let link_status = match db_val.link_status { GenericLinkStatus::PayoutLink(status) => Ok(status), _ => Err(report!(errors::ParsingError::EnumParseFailure( "GenericLinkStatus" ))) .attach_printable_lazy(|| { format!("Invalid status for PayoutLink - {:?}", db_val.link_status) }), }?; (link_data, link_status) } _ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| { format!("Invalid link_type for PayoutLink - {}", db_val.link_type) })?, }; Ok(Self { link_id: db_val.link_id, primary_reference: db_val.primary_reference, merchant_id: db_val.merchant_id, created_at: db_val.created_at, last_modified_at: db_val.last_modified_at, expiry: db_val.expiry, link_data, link_status, link_type: db_val.link_type, url: db_val.url, return_url: db_val.return_url, }) } <file_sep path="hyperswitch/crates/diesel_models/src/lib.rs" role="context" start="66" end="66"> pub type PgPooledConn = async_bb8_diesel::Connection<diesel::PgConnection>;
symbol_neighborhood