id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
large_file_api_models_-2418982772947466949
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/routing.rs // File size: 56099 bytes use std::fmt::Debug; use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule}; use common_utils::{ errors::{ParsingError, ValidationError}, ext_traits::ValueExt, pii, }; use euclid::frontend::ast::Program; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{RoutableConnectors, TransactionType}, open_router, }; // Define constants for default values const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0; const DEFAULT_BUCKET_SIZE: i32 = 200; const DEFAULT_HEDGING_PERCENT: f64 = 5.0; const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35; const DEFAULT_PAYMENT_METHOD: &str = "CARD"; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } impl ConnectorSelection { pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> { match self { Self::Priority(list) => list.clone(), Self::VolumeSplit(splits) => { splits.iter().map(|split| split.connector.clone()).collect() } } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: String, pub description: String, pub algorithm: StaticRoutingAlgorithm, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: Option<String>, pub description: Option<String>, pub algorithm: Option<StaticRoutingAlgorithm>, #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct ProfileDefaultRoutingConfig { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub connectors: Vec<RoutableConnectorChoice>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { pub limit: Option<u16>, pub offset: Option<u8>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingActivatePayload { pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQuery { pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQueryWrapper { pub routing_query: RoutingRetrieveQuery, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Response of the retrieved routing configs for a merchant account pub struct RoutingRetrieveResponse { pub algorithm: Option<MerchantRoutingAlgorithm>, } #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum LinkedRoutingConfigRetrieveResponse { MerchantAccountBased(Box<RoutingRetrieveResponse>), ProfileBased(Vec<RoutingDictionaryRecord>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Routing Algorithm specific to merchants pub struct MerchantRoutingAlgorithm { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, pub algorithm: RoutingAlgorithmWrapper, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, } impl EuclidDirFilter for ConnectorSelection { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::CardBin, DirKeyKind::CardType, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::UpiType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::AuthenticationType, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, DirKeyKind::CaptureMethod, DirKeyKind::BillingCountry, DirKeyKind::BusinessCountry, DirKeyKind::BusinessLabel, DirKeyKind::MetaData, DirKeyKind::RewardType, DirKeyKind::VoucherType, DirKeyKind::CardRedirectType, DirKeyKind::BankTransferType, DirKeyKind::RealTimePaymentType, ]; } impl EuclidAnalysable for ConnectorSelection { fn get_dir_value_for_analysis( &self, rule_name: String, ) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> { self.get_connector_list() .into_iter() .map(|connector_choice| { let connector_name = connector_choice.connector.to_string(); let mca_id = connector_choice.merchant_connector_id.clone(); ( euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())), std::collections::HashMap::from_iter([( "CONNECTOR_SELECTION".to_string(), serde_json::json!({ "rule_name": rule_name, "connector_name": connector_name, "mca_id": mca_id, }), )]), ) }) .collect() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } /// Routable Connector chosen for a payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")] 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>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)] pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum RoutableChoiceSerde { OnlyConnector(Box<RoutableConnectors>), FullStruct { connector: RoutableConnectors, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } impl std::fmt::Display for RoutableConnectorChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let base = self.connector.to_string(); if let Some(mca_id) = &self.merchant_connector_id { return write!(f, "{}:{}", base, mca_id.get_string_repr()); } write!(f, "{base}") } } impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { connector: value.connector, } } } impl PartialEq for RoutableConnectorChoice { fn eq(&self, other: &Self) -> bool { self.connector.eq(&other.connector) && self.merchant_connector_id.eq(&other.merchant_connector_id) } } impl Eq for RoutableConnectorChoice {} impl From<RoutableChoiceSerde> for RoutableConnectorChoice { 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, }, } } } impl From<RoutableConnectorChoice> for RoutableChoiceSerde { 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, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithStatus { pub routable_connector_choice: RoutableConnectorChoice, pub status: bool, } impl RoutableConnectorChoiceWithStatus { pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self { Self { routable_connector_choice, status, } } } #[derive( Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, ThreeDsDecisionRule, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingPayloadWrapper { pub updated_config: Vec<RoutableConnectorChoice>, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum RoutingAlgorithmWrapper { Static(StaticRoutingAlgorithm), Dynamic(DynamicRoutingAlgorithm), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum DynamicRoutingAlgorithm { EliminationBasedAlgorithm(EliminationRoutingConfig), SuccessBasedAlgorithm(SuccessBasedRoutingConfig), ContractBasedAlgorithm(ContractBasedRoutingConfig), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "RoutingAlgorithmSerde" )] pub enum StaticRoutingAlgorithm { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), #[schema(value_type=ProgramConnectorSelection)] Advanced(Program<ConnectorSelection>), #[schema(value_type=ProgramThreeDsDecisionRule)] ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } #[derive(Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct ProgramThreeDsDecisionRule { pub default_selection: ThreeDSDecisionRule, #[schema(value_type = RuleThreeDsDecisionRule)] pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>, #[schema(value_type = HashMap<String, serde_json::Value>)] pub metadata: std::collections::HashMap<String, serde_json::Value>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct RuleThreeDsDecisionRule { pub name: String, pub connector_selection: ThreeDSDecision, #[schema(value_type = Vec<IfStatement>)] pub statements: Vec<ast::IfStatement>, } impl StaticRoutingAlgorithm { pub fn should_validate_connectors_in_routing_config(&self) -> bool { match self { Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true, Self::ThreeDsDecisionRule(_) => false, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), Advanced(Program<ConnectorSelection>), ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm { type Error = error_stack::Report<ParsingError>; 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), RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i), }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "StraightThroughAlgorithmSerde", into = "StraightThroughAlgorithmSerde" )] pub enum StraightThroughAlgorithm { #[schema(title = "Single")] Single(Box<RoutableConnectorChoice>), #[schema(title = "Priority")] Priority(Vec<RoutableConnectorChoice>), #[schema(title = "VolumeSplit")] VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StraightThroughAlgorithmInner { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum StraightThroughAlgorithmSerde { Direct(StraightThroughAlgorithmInner), Nested { algorithm: StraightThroughAlgorithmInner, }, } impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> { let inner = match value { StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm, StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm, }; match &inner { StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match inner { StraightThroughAlgorithmInner::Single(single) => Self::Single(single), StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist), StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit), }) } } impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { fn from(value: StraightThroughAlgorithm) -> Self { let inner = match value { StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn), StraightThroughAlgorithm::Priority(plist) => { StraightThroughAlgorithmInner::Priority(plist) } StraightThroughAlgorithm::VolumeSplit(vsplit) => { StraightThroughAlgorithmInner::VolumeSplit(vsplit) } }; Self::Nested { algorithm: inner } } } impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm { fn from(value: StraightThroughAlgorithm) -> Self { match value { StraightThroughAlgorithm::Single(conn) => Self::Single(conn), StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns), StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl StaticRoutingAlgorithm { pub fn get_kind(&self) -> RoutingAlgorithmKind { match self { Self::Single(_) => RoutingAlgorithmKind::Single, Self::Priority(_) => RoutingAlgorithmKind::Priority, Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit, Self::Advanced(_) => RoutingAlgorithmKind::Advanced, Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule, } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingAlgorithmRef { pub algorithm_id: Option<common_utils::id_type::RoutingId>, pub timestamp: i64, pub config_algo_id: Option<String>, pub surcharge_config_algo_id: Option<String>, } impl RoutingAlgorithmRef { pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) { self.algorithm_id = Some(new_id); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_conditional_config_id(&mut self, ids: String) { self.config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_surcharge_config_id(&mut self, ids: String) { self.surcharge_config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn parse_routing_algorithm( value: Option<pii::SecretSerdeValue>, ) -> Result<Option<Self>, error_stack::Report<ParsingError>> { value .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef")) .transpose() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub kind: RoutingAlgorithmKind, pub description: String, pub created_at: i64, pub modified_at: i64, pub algorithm_for: Option<TransactionType>, pub decision_engine_routing_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionary { #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, pub active_id: Option<String>, pub records: Vec<RoutingDictionaryRecord>, } #[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)] #[serde(untagged)] pub enum RoutingKind { Config(RoutingDictionary), RoutingAlgorithm(Vec<RoutingDictionaryRecord>), } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct RoutingAlgorithmId { #[schema(value_type = String)] pub routing_algorithm_id: common_utils::id_type::RoutingId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingLinkWrapper { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: RoutingAlgorithmId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicAlgorithmWithTimestamp<T> { pub algorithm_id: Option<T>, pub timestamp: i64, } impl<T> DynamicAlgorithmWithTimestamp<T> { pub fn new(algorithm_id: Option<T>) -> Self { Self { algorithm_id, timestamp: common_utils::date_time::now_unix_timestamp(), } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, pub contract_based_routing: Option<ContractRoutingAlgorithm>, #[serde(default)] pub is_merchant_created_in_decision_engine: bool, } pub trait DynamicRoutingAlgoAccessor { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>; fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures; } impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl EliminationRoutingAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl SuccessBasedAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl DynamicRoutingAlgorithmRef { pub fn update(&mut self, new: Self) { if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(elimination_routing_algorithm) } if let Some(success_based_algorithm) = new.success_based_algorithm { self.success_based_algorithm = Some(success_based_algorithm) } if let Some(contract_based_routing) = new.contract_based_routing { self.contract_based_routing = Some(contract_based_routing) } } pub fn update_enabled_features( &mut self, algo_type: DynamicRoutingType, feature_to_enable: DynamicRoutingFeatures, ) { match algo_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } } } pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) { self.is_merchant_created_in_decision_engine = is_created; } pub fn is_success_rate_routing_enabled(&self) -> bool { self.success_based_algorithm .as_ref() .map(|success_based_routing| { success_based_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } pub fn is_elimination_enabled(&self) -> bool { self.elimination_routing_algorithm .as_ref() .map(|elimination_routing| { elimination_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplit { pub routing_type: RoutingType, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplitWrapper { pub routing_info: RoutingVolumeSplit, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum RoutingType { #[default] Static, Dynamic, } impl RoutingType { pub fn is_dynamic_routing(self) -> bool { self == Self::Dynamic } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } impl EliminationRoutingAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl SuccessBasedAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl DynamicRoutingAlgorithmRef { 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, }) } }; } pub fn update_feature( &mut self, 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(None), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } }; } 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, }); } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingVolumeSplitQuery { pub split: u8, } #[derive( Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] None, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingUpdateConfigQuery { #[schema(value_type = String)] pub algorithm_id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ToggleDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ToggleDynamicRoutingPath { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct CreateDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, pub payload: DynamicRoutingPayload, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum DynamicRoutingPayload { SuccessBasedRoutingPayload(SuccessBasedRoutingConfig), EliminationRoutingPayload(EliminationRoutingConfig), } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct RoutingVolumeSplitResponse { pub split: u8, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, #[schema(value_type = DecisionEngineEliminationData)] pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationAnalyserConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } impl EliminationAnalyserConfig { pub fn update(&mut self, new: Self) { if let Some(bucket_size) = new.bucket_size { self.bucket_size = Some(bucket_size) } if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs { self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs) } } } impl Default for EliminationRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(60), }), decision_engine_configs: None, } } } impl EliminationRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.elimination_analyser_config { self.elimination_analyser_config .as_mut() .map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { elimination_analyser_config: None, params: None, decision_engine_configs: Some(open_router::DecisionEngineEliminationData { threshold: DEFAULT_ELIMINATION_THRESHOLD, }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, #[schema(value_type = DecisionEngineSuccessRateData)] pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>, } impl Default for SuccessBasedRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(5), default_success_rate: Some(100.0), max_aggregates_size: Some(8), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: None, max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), exploration_percent: Some(20.0), shuffle_on_tie_during_exploitation: Some(false), }), decision_engine_configs: None, } } } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display, )] pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, Currency, Country, CardNetwork, CardBin, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, pub shuffle_on_tie_during_exploitation: Option<bool>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct CurrentBlockThreshold { pub duration_in_mins: Option<u64>, pub max_total_count: Option<u64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, Copy, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SuccessRateSpecificityLevel { #[default] Merchant, Global, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedRoutingPayloadWrapper { pub updated_config: SuccessBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingPayloadWrapper { pub updated_config: EliminationRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingPayloadWrapper { pub updated_config: ContractBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingSetupPayloadWrapper { pub config: Option<ContractBasedRoutingConfig>, pub profile_id: common_utils::id_type::ProfileId, pub features_to_enable: DynamicRoutingFeatures, } #[derive( Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq, )] pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } impl SuccessBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { params: None, config: None, decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData { default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD), default_bucket_size: Some(DEFAULT_BUCKET_SIZE), default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT), default_lower_reset_factor: None, default_upper_reset_factor: None, default_gateway_extra_score: None, sub_level_input_config: Some(vec![ open_router::DecisionEngineSRSubLevelInputConfig { payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()), payment_method: None, latency_threshold: None, bucket_size: Some(DEFAULT_BUCKET_SIZE), hedging_percent: Some(DEFAULT_HEDGING_PERCENT), lower_reset_factor: None, upper_reset_factor: None, gateway_extra_score: None, }, ]), }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } impl SuccessBasedRoutingConfigBody { 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; if let Some(exploration_percent) = new.exploration_percent { self.exploration_percent = Some(exploration_percent); } if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation { self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation); } } } impl CurrentBlockThreshold { pub fn update(&mut self, new: Self) { if let Some(max_total_count) = new.max_total_count { self.max_total_count = Some(max_total_count) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfig { pub config: Option<ContractBasedRoutingConfigBody>, pub label_info: Option<Vec<LabelInformation>>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfigBody { pub constants: Option<Vec<f64>>, pub time_scale: Option<ContractBasedTimeScale>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct LabelInformation { pub label: String, pub target_count: u64, pub target_time: u64, #[schema(value_type = String)] pub mca_id: common_utils::id_type::MerchantConnectorAccountId, } impl LabelInformation { pub fn update_target_time(&mut self, new: &Self) { self.target_time = new.target_time; } pub fn update_target_count(&mut self, new: &Self) { self.target_count = new.target_count; } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ContractBasedTimeScale { Day, Month, } impl Default for ContractBasedRoutingConfig { fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } } impl ContractBasedRoutingConfig { 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()]); } }); } } } impl ContractBasedRoutingConfigBody { 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) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithBucketName { pub routable_connector_choice: RoutableConnectorChoice, pub bucket_name: String, } impl RoutableConnectorChoiceWithBucketName { pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateConfigEventRequest { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<CalSuccessRateConfigEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventBucketConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<EliminationRoutingEventBucketConfig>, } /// API-1 types #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalContractScoreEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<ContractBasedRoutingConfig>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithScoreEventResponse { pub score: f64, pub label: String, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventResponse { pub labels_with_score: Vec<LabelWithScoreEventResponse>, pub routing_approach: RoutingApproach, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RoutingApproach { Exploitation, Exploration, Elimination, ContractBased, Default, } impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::Exploitation, "SR_V3_HEDGING" => Self::Exploration, _ => Self::Default, } } } impl std::fmt::Display for RoutingApproach { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Exploitation => write!(f, "Exploitation"), Self::Exploration => write!(f, "Exploration"), Self::Elimination => write!(f, "Elimination"), Self::ContractBased => write!(f, "ContractBased"), Self::Default => write!(f, "Default"), } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RuleMigrationQuery { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub limit: Option<u32>, pub offset: Option<u32>, } impl RuleMigrationQuery { pub fn validated_limit(&self) -> u32 { self.limit.unwrap_or(50).min(1000) } } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResult { pub success: Vec<RuleMigrationResponse>, pub errors: Vec<RuleMigrationError>, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResponse { pub profile_id: common_utils::id_type::ProfileId, pub euclid_algorithm_id: common_utils::id_type::RoutingId, pub decision_engine_algorithm_id: String, pub is_active_rule: bool, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationError { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: common_utils::id_type::RoutingId, pub error: String, } impl RuleMigrationResponse { pub fn new( profile_id: common_utils::id_type::ProfileId, euclid_algorithm_id: common_utils::id_type::RoutingId, decision_engine_algorithm_id: String, is_active_rule: bool, ) -> Self { Self { profile_id, euclid_algorithm_id, decision_engine_algorithm_id, is_active_rule, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingResultSource { /// External Decision Engine DecisionEngine, /// Inbuilt Hyperswitch Routing Engine HyperswitchRouting, } //TODO: temporary change will be refactored afterwards #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct RoutingEvaluateRequest { pub created_by: String, #[schema(value_type = Object)] ///Parameters that can be used in the routing evaluate request. ///eg: {"parameters": { /// "payment_method": {"type": "enum_variant", "value": "card"}, /// "payment_method_type": {"type": "enum_variant", "value": "credit"}, /// "amount": {"type": "number", "value": 10}, /// "currency": {"type": "str_value", "value": "INR"}, /// "authentication_type": {"type": "enum_variant", "value": "three_ds"}, /// "card_bin": {"type": "str_value", "value": "424242"}, /// "capture_method": {"type": "enum_variant", "value": "scheduled"}, /// "business_country": {"type": "str_value", "value": "IN"}, /// "billing_country": {"type": "str_value", "value": "IN"}, /// "business_label": {"type": "str_value", "value": "business_label"}, /// "setup_future_usage": {"type": "enum_variant", "value": "off_session"}, /// "card_network": {"type": "enum_variant", "value": "visa"}, /// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"}, /// "mandate_type": {"type": "enum_variant", "value": "single_use"}, /// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"}, /// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}} /// }} pub parameters: std::collections::HashMap<String, Option<ValueType>>, pub fallback_output: Vec<DeRoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {} #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RoutingEvaluateResponse { pub status: String, pub output: serde_json::Value, #[serde(deserialize_with = "deserialize_connector_choices")] pub evaluated_output: Vec<RoutableConnectorChoice>, #[serde(deserialize_with = "deserialize_connector_choices")] pub eligible_connectors: Vec<RoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {} fn deserialize_connector_choices<'de, D>( deserializer: D, ) -> Result<Vec<RoutableConnectorChoice>, D::Error> where D: serde::Deserializer<'de>, { let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; Ok(infos .into_iter() .map(RoutableConnectorChoice::from) .collect()) } impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { fn from(choice: DeRoutableConnectorChoice) -> Self { Self { choice_kind: RoutableChoiceKind::FullStruct, connector: choice.gateway_name, merchant_connector_id: choice.gateway_id, } } } /// Routable Connector chosen for a payment #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DeRoutableConnectorChoice { pub gateway_name: RoutableConnectors, #[schema(value_type = String)] pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(u64), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), /// Represents a global reference, which is a reference to a global variable GlobalRef(String), /// Represents an array of numbers. This is basically used for /// "one of the given numbers" operations /// eg: payment.method.amount = (1, 2, 3) NumberArray(Vec<u64>), /// Similar to NumberArray but for enum variants /// eg: payment.method.cardtype = (debit, credit) EnumVariantArray(Vec<String>), /// Like a number array but can include comparisons. Useful for /// conditions like "500 < amount < 1000" /// eg: payment.amount = (> 500, < 1000) NumberComparisonArray(Vec<NumberComparison>), } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: u64, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, }
{ "crate": "api_models", "file": "crates/api_models/src/routing.rs", "file_size": 56099, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_7259240787410408945
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payouts.rs // File size: 45586 bytes use std::collections::HashMap; use cards::CardNumber; #[cfg(feature = "v2")] use common_utils::types::BrowserInformation; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; #[cfg(feature = "v1")] use payments::BrowserInformation; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<id_type::PayoutId>, /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// 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<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<BrowserInformation>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), BankRedirect(BankRedirect), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] 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>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// 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>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// 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>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: 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>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { ApplePayDecrypt(ApplePayDecrypt), Paypal(Paypal), Venmo(Venmo), } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirect { Interac(Interac), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Interac { /// Customer email linked with interac account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Email, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct ApplePayDecrypt { /// The dpan number associated with card number #[schema(value_type = String, example = "4242424242424242")] pub dpan: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// 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<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), #[schema(value_type = BankRedirectAdditionalData)] BankRedirect(Box<payout_method_utils::BankRedirectAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub starting_after: Option<id_type::PayoutId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub ending_before: Option<id_type::PayoutId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<id_type::PayoutId>, /// The merchant order reference ID for payout #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payout_id: id_type::PayoutId, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: id_type::PayoutId, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } Wallet::ApplePayDecrypt(ApplePayDecrypt { expiry_month, expiry_year, card_holder_name, .. }) => Self::ApplePayDecrypt(Box::new( payout_method_utils::ApplePayDecryptAdditionalData { card_exp_month: expiry_month, card_exp_year: expiry_year, card_holder_name, }, )), } } } impl From<BankRedirect> for payout_method_utils::BankRedirectAdditionalData { fn from(bank_redirect: BankRedirect) -> Self { match bank_redirect { BankRedirect::Interac(Interac { email }) => { Self::Interac(Box::new(payout_method_utils::InteracAdditionalData { email: Some(ForeignFrom::foreign_from(email)), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } payout_method_utils::AdditionalPayoutMethodData::BankRedirect(bank_redirect) => { Self::BankRedirect(bank_redirect) } } } }
{ "crate": "api_models", "file": "crates/api_models/src/payouts.rs", "file_size": 45586, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_2673341667090594883
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/authentication.rs // File size: 24227 bytes use common_enums::{enums, AuthenticationConnectors}; #[cfg(feature = "v1")] use common_utils::errors::{self, CustomResult}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, id_type, }; #[cfg(feature = "v1")] use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::payments::{Address, BrowserInformation, PaymentMethodData}; use crate::payments::{CustomerDetails, DeviceChannel, SdkInformation, ThreeDsCompletionIndicator}; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationCreateRequest { /// The unique identifier for this authentication. #[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: Option<id_type::AuthenticationId>, /// The business profile that is associated with this authentication #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Customer details. #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<CustomerDetails>, /// The amount for the transaction, required. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// The currency for the transaction, required. #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The URL to which the user should be redirected after authentication. #[schema(value_type = Option<String>, example = "https://example.com/redirect")] pub return_url: Option<String>, /// Force 3DS challenge. #[serde(default)] pub force_3ds_challenge: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Profile Acquirer ID get from profile acquirer configuration #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, /// Acquirer details information #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AcquirerDetails { /// The bin of the card. #[schema(value_type = Option<String>, example = "123456")] pub acquirer_bin: Option<String>, /// The merchant id of the card. #[schema(value_type = Option<String>, example = "merchant_abc")] pub acquirer_merchant_id: Option<String>, /// The country code of the card. #[schema(value_type = Option<String>, example = "US/34456")] pub merchant_country_code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationResponse { /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The client secret for this authentication, to be used for client-side operations. #[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<masking::Secret<String>>, /// The amount for the transaction. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The currency for the transaction. #[schema(value_type = Currency)] pub currency: enums::Currency, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// Whether 3DS challenge was forced. pub force_3ds_challenge: Option<bool>, /// The URL to which the user should be redirected after authentication, if provided. pub return_url: Option<String>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Acquirer details information #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, /// Profile Acquirer ID get from profile acquirer configuration #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, } impl ApiEventMetric for AuthenticationCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.authentication_id .as_ref() .map(|id| ApiEventsType::Authentication { authentication_id: id.clone(), }) } } impl ApiEventMetric for AuthenticationResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct AuthenticationEligibilityRequest { /// Payment method-specific data such as card details, wallet info, etc. /// This holds the raw information required to process the payment method. #[schema(value_type = PaymentMethodData)] pub payment_method_data: PaymentMethodData, /// Enum representing the type of payment method being used /// (e.g., Card, Wallet, UPI, BankTransfer, etc.). #[schema(value_type = PaymentMethod)] pub payment_method: common_enums::PaymentMethod, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "debit")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Optional secret value used to identify and authorize the client making the request. /// This can help ensure that the payment session is secure and valid. #[schema(value_type = Option<String>)] pub client_secret: Option<masking::Secret<String>>, /// Optional identifier for the business profile associated with the payment. /// This determines which configurations, rules, and branding are applied to the transaction. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Optional billing address of the customer. /// This can be used for fraud detection, authentication, or compliance purposes. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Optional shipping address of the customer. /// This can be useful for logistics, verification, or additional risk checks. #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Optional information about the customer's browser (user-agent, language, etc.). /// This is typically used to support 3DS authentication flows and improve risk assessment. #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Optional email address of the customer. /// Used for customer identification, communication, and possibly for 3DS or fraud checks. #[schema(value_type = Option<String>)] pub email: Option<common_utils::pii::Email>, } #[cfg(feature = "v1")] impl AuthenticationEligibilityRequest { pub fn get_next_action_api( &self, base_url: String, authentication_id: String, ) -> CustomResult<NextAction, errors::ParsingError> { let url = format!("{base_url}/authentication/{authentication_id}/authenticate"); Ok(NextAction { url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?, http_method: common_utils::request::Method::Post, }) } pub fn get_billing_address(&self) -> Option<Address> { self.billing.clone() } pub fn get_shipping_address(&self) -> Option<Address> { self.shipping.clone() } pub fn get_browser_information(&self) -> Option<BrowserInformation> { self.browser_information.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Serialize, ToSchema)] pub struct AuthenticationEligibilityResponse { /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// The URL to which the user should be redirected after authentication. #[schema(value_type = NextAction)] pub next_action: NextAction, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The 3DS data for this authentication. #[schema(value_type = Option<EligibilityResponseParams>)] pub eligibility_response_params: Option<EligibilityResponseParams>, /// The metadata for this authentication. #[schema(value_type = serde_json::Value)] pub connector_metadata: Option<serde_json::Value>, /// The unique identifier for this authentication. #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The error message for this authentication. #[schema(value_type = Option<String>)] pub error_message: Option<String>, /// The error code for this authentication. #[schema(value_type = Option<String>)] pub error_code: Option<String>, /// The connector used for this authentication. #[schema(value_type = Option<AuthenticationConnectors>)] pub authentication_connector: Option<AuthenticationConnectors>, /// Billing address #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Shipping address #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Browser information #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Email #[schema(value_type = Option<String>)] pub email: common_utils::crypto::OptionalEncryptableEmail, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } #[derive(Debug, Serialize, ToSchema)] pub enum EligibilityResponseParams { ThreeDsData(ThreeDsData), } #[derive(Debug, Serialize, ToSchema)] pub struct ThreeDsData { /// The unique identifier for this authentication from the 3DS server. #[schema(value_type = String)] pub three_ds_server_transaction_id: Option<String>, /// The maximum supported 3DS version. #[schema(value_type = String)] pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier for this authentication from the connector. #[schema(value_type = String)] pub connector_authentication_id: Option<String>, /// The data required to perform the 3DS method. #[schema(value_type = String)] pub three_ds_method_data: Option<String>, /// The URL to which the user should be redirected after authentication. #[schema(value_type = String, example = "https://example.com/redirect")] pub three_ds_method_url: Option<url::Url>, /// The version of the message. #[schema(value_type = String)] pub message_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier for this authentication. #[schema(value_type = String)] pub directory_server_id: Option<String>, } #[derive(Debug, Serialize, ToSchema)] pub struct NextAction { /// The URL for authenticatating the user. #[schema(value_type = String)] pub url: url::Url, /// The HTTP method to use for the request. #[schema(value_type = Method)] pub http_method: common_utils::request::Method, } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationEligibilityRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationEligibilityResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationAuthenticateRequest { /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, /// Client secret for the authentication #[schema(value_type = String)] pub client_secret: Option<masking::Secret<String>>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } impl ApiEventMetric for AuthenticationAuthenticateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationAuthenticateResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = Option<TransactionStatus>)] pub transaction_status: Option<common_enums::TransactionStatus>, /// Access Server URL to be used for challenge submission pub acs_url: Option<url::Url>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_ds_server_transaction_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, /// The error message for this authentication. #[schema(value_type = String)] pub error_message: Option<String>, /// The error code for this authentication. #[schema(value_type = String)] pub error_code: Option<String>, /// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. #[schema(value_type = String)] pub authentication_value: Option<masking::Secret<String>>, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// The unique identifier for this authentication. #[schema(value_type = AuthenticationId, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// The ECI value for this authentication. #[schema(value_type = String)] pub eci: Option<String>, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } impl ApiEventMetric for AuthenticationAuthenticateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct AuthenticationSyncResponse { // Core Authentication Fields (from AuthenticationResponse) /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// This is an identifier for the merchant account. #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, /// The current status of the authentication. #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The client secret for this authentication. #[schema(value_type = Option<String>)] pub client_secret: Option<masking::Secret<String>>, /// The amount for the transaction. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The currency for the transaction. #[schema(value_type = Currency)] pub currency: enums::Currency, /// The connector used for authentication. #[schema(value_type = Option<AuthenticationConnectors>)] pub authentication_connector: Option<AuthenticationConnectors>, /// Whether 3DS challenge was forced. pub force_3ds_challenge: Option<bool>, /// The URL to which the user should be redirected after authentication. pub return_url: Option<String>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The business profile that is associated with this authentication. #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// SCA exemption type for this authentication. #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, /// The unique identifier from the 3DS server. #[schema(value_type = Option<String>)] pub threeds_server_transaction_id: Option<String>, /// The maximum supported 3DS version. #[schema(value_type = Option<String>)] pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier from the connector. #[schema(value_type = Option<String>)] pub connector_authentication_id: Option<String>, /// The data required to perform the 3DS method. #[schema(value_type = Option<String>)] pub three_ds_method_data: Option<String>, /// The URL for the 3DS method. #[schema(value_type = Option<String>)] pub three_ds_method_url: Option<String>, /// The version of the message. #[schema(value_type = Option<String>)] pub message_version: Option<common_utils::types::SemanticVersion>, /// The metadata for this authentication. #[schema(value_type = Option<serde_json::Value>)] pub connector_metadata: Option<serde_json::Value>, /// The unique identifier for the directory server. #[schema(value_type = Option<String>)] pub directory_server_id: Option<String>, /// Billing address. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Shipping address. #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Browser information. #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Email. #[schema(value_type = Option<String>)] pub email: common_utils::crypto::OptionalEncryptableEmail, /// Indicates the transaction status. #[serde(rename = "trans_status")] #[schema(value_type = Option<TransactionStatus>)] pub transaction_status: Option<common_enums::TransactionStatus>, /// Access Server URL for challenge submission. pub acs_url: Option<String>, /// Challenge request to be sent to acs_url. pub challenge_request: Option<String>, /// Unique identifier assigned by EMVCo. pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS. pub acs_trans_id: Option<String>, /// JWS object created by the ACS for the ARes message. pub acs_signed_content: Option<String>, /// Three DS Requestor URL. pub three_ds_requestor_url: Option<String>, /// Merchant app URL for OOB authentication. pub three_ds_requestor_app_url: Option<String>, /// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. #[schema(value_type = Option<String>)] pub authentication_value: Option<masking::Secret<String>>, /// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. pub eci: Option<String>, // Common Error Fields (present in multiple responses) /// Error message if any. #[schema(value_type = Option<String>)] pub error_message: Option<String>, /// Error code if any. #[schema(value_type = Option<String>)] pub error_code: Option<String>, /// Profile Acquirer ID #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationSyncResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationSyncRequest { /// The client secret for this authentication. #[schema(value_type = String)] pub client_secret: Option<masking::Secret<String>>, /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationSyncPostUpdateRequest { /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncPostUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/authentication.rs", "file_size": 24227, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-7122072980695273820
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/refunds.rs // File size: 22339 bytes use std::collections::HashMap; pub use common_utils::types::MinorUnit; use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; #[cfg(feature = "v1")] use crate::admin; use crate::{admin::MerchantConnectorInfo, enums}; #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { /// The payment id against which refund is to be initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: Option<String>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer` #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>)] pub split_refunds: Option<common_types::refunds::SplitRefund>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund given by the Merchant. #[schema( max_length = 64, min_length = 1, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub merchant_reference_id: common_utils::id_type::RefundReferenceId, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrievePayload { /// `force_sync` with the connector to get refund details pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v1")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: String, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: common_utils::id_type::GlobalRefundId, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorAuthDetails>)] pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { #[serde(skip)] pub refund_id: String, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundMetadataUpdateRequest { /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// 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#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { #[serde(skip)] pub refund_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The status for refund pub status: Option<RefundStatus>, /// The code for the error pub error_code: Option<String>, /// The error message pub error_message: Option<String>, } #[cfg(feature = "v1")] /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v2")] /// To indicate whether the refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { Scheduled, #[default] Instant, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code pub currency: String, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive pub reason: Option<String>, /// 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>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error message pub error_message: Option<String>, /// The code for the error pub error_code: Option<String>, /// Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601::option")] pub updated_at: Option<PrimitiveDateTime>, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe")] pub connector: String, /// The id of business profile for this refund #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, /// Error code received from the issuer in case of failed refunds pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed refunds pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.refund_id.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Global Refund Id for the refund #[schema(value_type = String)] pub id: common_utils::id_type::GlobalRefundId, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// The refund amount #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object pub reason: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error details for the refund pub error_details: Option<RefundErrorDetails>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe", value_type = Connector)] pub connector: enums::Connector, /// The id of business profile for this refund #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = String)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The reference id of the connector for the refund pub connector_refund_reference_id: Option<String>, } #[cfg(feature = "v2")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.id.get_string_repr().to_owned() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundErrorDetails { pub code: String, pub message: String, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::PaymentId>, /// The identifier for the refund pub refund_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::GlobalPaymentId>, /// The identifier for the refund #[schema(value_type = String)] pub refund_id: Option<common_utils::id_type::GlobalRefundId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub connector_id_list: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, /// The total number of refunds in the list pub total_count: i64, /// The List of refund response object pub data: Vec<RefundResponse>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)] pub struct RefundListMetaData { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } /// The status for refunds #[derive( Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display, strum::EnumIter, )] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, } impl From<enums::RefundStatus> for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, enums::RefundStatus::ManualReview => Self::Review, enums::RefundStatus::Pending => Self::Pending, enums::RefundStatus::Success => Self::Succeeded, } } } impl From<RefundStatus> for enums::RefundStatus { fn from(status: RefundStatus) -> Self { match status { RefundStatus::Failed => Self::Failure, RefundStatus::Review => Self::ManualReview, RefundStatus::Pending => Self::Pending, RefundStatus::Succeeded => Self::Success, } } }
{ "crate": "api_models", "file": "crates/api_models/src/refunds.rs", "file_size": 22339, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-2998818449555947580
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/subscription.rs // File size: 18450 bytes use common_enums::connector_enums::InvoiceStatus; use common_types::payments::CustomerAcceptance; use common_utils::{ events::ApiEventMetric, id_type::{ CustomerId, InvoiceId, MerchantConnectorAccountId, MerchantId, PaymentId, ProfileId, SubscriptionId, }, types::{MinorUnit, Url}, }; use masking::Secret; use utoipa::ToSchema; use crate::{ enums::{ AuthenticationType, CaptureMethod, Currency, FutureUsage, IntentStatus, PaymentExperience, PaymentMethod, PaymentMethodType, PaymentType, }, mandates::RecurringDetails, payments::{Address, NextActionData, PaymentMethodDataRequest}, }; /// Request payload for creating a subscription. /// /// This struct captures details required to create a subscription, /// including plan, profile, merchant connector, and optional customer info. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionRequest { /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the subscription plan. pub plan_id: Option<String>, /// Optional coupon code applied to the subscription. pub coupon_code: Option<String>, /// customer ID associated with this subscription. pub customer_id: CustomerId, /// payment details for the subscription. pub payment_details: CreateSubscriptionPaymentDetails, /// billing address for the subscription. pub billing: Option<Address>, /// shipping address for the subscription. pub shipping: Option<Address>, } /// Response payload returned after successfully creating a subscription. /// /// Includes details such as subscription ID, status, plan, merchant, and customer info. #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, /// Merchant identifier owning this subscription. pub merchant_id: MerchantId, /// Optional coupon code applied to this subscription. pub coupon_code: Option<String>, /// Optional customer ID associated with this subscription. pub customer_id: CustomerId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, } /// Possible states of a subscription lifecycle. /// /// - `Created`: Subscription was created but not yet activated. /// - `Active`: Subscription is currently active. /// - `InActive`: Subscription is inactive. /// - `Pending`: Subscription is pending activation. /// - `Trial`: Subscription is in a trial period. /// - `Paused`: Subscription is paused. /// - `Unpaid`: Subscription is unpaid. /// - `Onetime`: Subscription is a one-time payment. /// - `Cancelled`: Subscription has been cancelled. /// - `Failed`: Subscription has failed. #[derive(Debug, Clone, serde::Serialize, strum::EnumString, strum::Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SubscriptionStatus { /// Subscription is active. Active, /// Subscription is created but not yet active. Created, /// Subscription is inactive. InActive, /// Subscription is in pending state. Pending, /// Subscription is in trial state. Trial, /// Subscription is paused. Paused, /// Subscription is unpaid. Unpaid, /// Subscription is a one-time payment. Onetime, /// Subscription is cancelled. Cancelled, /// Subscription has failed. Failed, } impl SubscriptionResponse { /// Creates a new [`CreateSubscriptionResponse`] with the given identifiers. /// /// By default, `client_secret`, `coupon_code`, and `customer` fields are `None`. #[allow(clippy::too_many_arguments)] pub fn new( id: SubscriptionId, merchant_reference_id: Option<String>, status: SubscriptionStatus, plan_id: Option<String>, item_price_id: Option<String>, profile_id: ProfileId, merchant_id: MerchantId, client_secret: Option<Secret<String>>, customer_id: CustomerId, payment: Option<PaymentResponseData>, invoice: Option<Invoice>, ) -> Self { Self { id, merchant_reference_id, status, plan_id, item_price_id, profile_id, client_secret, merchant_id, coupon_code: None, customer_id, payment, invoice, } } } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct GetPlansResponse { pub plan_id: String, pub name: String, pub description: Option<String>, pub price_id: Vec<SubscriptionPlanPrices>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionPlanPrices { pub price_id: String, pub plan_id: Option<String>, pub amount: MinorUnit, pub currency: Currency, pub interval: PeriodUnit, pub interval_count: i64, pub trial_period: Option<i64>, pub trial_period_unit: Option<PeriodUnit>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub enum PeriodUnit { Day, Week, Month, Year, } /// For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecret(String); impl ClientSecret { pub fn new(secret: String) -> Self { Self(secret) } pub fn as_str(&self) -> &str { &self.0 } pub fn as_string(&self) -> &String { &self.0 } } #[derive(serde::Deserialize, serde::Serialize, Debug, ToSchema)] pub struct GetPlansQuery { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, pub limit: Option<u32>, pub offset: Option<u32>, } impl ApiEventMetric for SubscriptionResponse {} impl ApiEventMetric for CreateSubscriptionRequest {} impl ApiEventMetric for GetPlansQuery {} impl ApiEventMetric for GetPlansResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionPaymentDetails { pub shipping: Option<Address>, pub billing: Option<Address>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateSubscriptionPaymentDetails { /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = String)] pub return_url: Url, pub setup_future_usage: Option<FutureUsage>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentDetails { pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub setup_future_usage: Option<FutureUsage>, pub customer_acceptance: Option<CustomerAcceptance>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_type: Option<PaymentType>, } // Creating new type for PaymentRequest API call as usage of api_models::PaymentsRequest will result in invalid payment request during serialization // Eg: Amount will be serialized as { amount: {Value: 100 }} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreatePaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmPaymentsRequestData { pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub payment_method: PaymentMethod, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: PaymentMethodDataRequest, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CreateAndConfirmPaymentsRequestData { pub amount: MinorUnit, pub currency: Currency, pub customer_id: Option<CustomerId>, pub confirm: bool, pub billing: Option<Address>, pub shipping: Option<Address>, pub profile_id: Option<ProfileId>, pub setup_future_usage: Option<FutureUsage>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub capture_method: Option<CaptureMethod>, pub authentication_type: Option<AuthenticationType>, pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<PaymentMethodDataRequest>, pub customer_acceptance: Option<CustomerAcceptance>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentResponseData { pub payment_id: PaymentId, pub status: IntentStatus, pub amount: MinorUnit, pub currency: Currency, pub profile_id: Option<ProfileId>, pub connector: Option<String>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<Secret<String>>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<Url>, pub next_action: Option<NextActionData>, pub payment_experience: Option<PaymentExperience>, pub error_code: Option<String>, pub error_message: Option<String>, pub payment_method_type: Option<PaymentMethodType>, #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<Secret<String>>, pub billing: Option<Address>, pub shipping: Option<Address>, pub payment_type: Option<PaymentType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateMitPaymentRequestData { pub amount: MinorUnit, pub currency: Currency, pub confirm: bool, pub customer_id: Option<CustomerId>, pub recurring_details: Option<RecurringDetails>, pub off_session: Option<bool>, pub profile_id: Option<ProfileId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConfirmSubscriptionRequest { #[schema(value_type = Option<String>)] /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<ClientSecret>, /// Payment details for the invoice. pub payment_details: ConfirmSubscriptionPaymentDetails, } impl ConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .billing .as_ref() .or(self.payment_details.billing.as_ref()) .cloned() } } impl ApiEventMetric for ConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateAndConfirmSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: CustomerId, /// Billing address for the subscription. pub billing: Option<Address>, /// Shipping address for the subscription. pub shipping: Option<Address>, /// Payment details for the invoice. pub payment_details: PaymentDetails, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, } impl CreateAndConfirmSubscriptionRequest { pub fn get_billing_address(&self) -> Option<Address> { self.payment_details .payment_method_data .as_ref() .and_then(|data| data.billing.clone()) .or(self.billing.clone()) } } impl ApiEventMetric for CreateAndConfirmSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ConfirmSubscriptionResponse { /// Unique identifier for the subscription. pub id: SubscriptionId, /// Merchant specific Unique identifier. pub merchant_reference_id: Option<String>, /// Current status of the subscription. pub status: SubscriptionStatus, /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Optional coupon code applied to this subscription. pub coupon: Option<String>, /// Associated profile ID. pub profile_id: ProfileId, /// Payment details for the invoice. pub payment: Option<PaymentResponseData>, /// Customer ID associated with this subscription. pub customer_id: Option<CustomerId>, /// Invoice Details for the subscription. pub invoice: Option<Invoice>, /// Billing Processor subscription ID. pub billing_processor_subscription_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct Invoice { /// Unique identifier for the invoice. pub id: InvoiceId, /// Unique identifier for the subscription. pub subscription_id: SubscriptionId, /// Identifier for the merchant. pub merchant_id: MerchantId, /// Identifier for the profile. pub profile_id: ProfileId, /// Identifier for the merchant connector account. pub merchant_connector_id: MerchantConnectorAccountId, /// Identifier for the Payment. pub payment_intent_id: Option<PaymentId>, /// Identifier for Payment Method #[schema(value_type = Option<String>, example = "pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<String>, /// Identifier for the Customer. pub customer_id: CustomerId, /// Invoice amount. pub amount: MinorUnit, /// Currency for the invoice payment. pub currency: Currency, /// Status of the invoice. pub status: InvoiceStatus, } impl ApiEventMetric for ConfirmSubscriptionResponse {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpdateSubscriptionRequest { /// Identifier for the associated plan_id. pub plan_id: String, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, } impl ApiEventMetric for UpdateSubscriptionRequest {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EstimateSubscriptionQuery { /// Identifier for the associated subscription plan. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: String, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, } impl ApiEventMetric for EstimateSubscriptionQuery {} #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct EstimateSubscriptionResponse { /// Estimated amount to be charged for the invoice. pub amount: MinorUnit, /// Currency for the amount. pub currency: Currency, /// Identifier for the associated plan_id. pub plan_id: Option<String>, /// Identifier for the associated item_price_id for the subscription. pub item_price_id: Option<String>, /// Identifier for the coupon code for the subscription. pub coupon_code: Option<String>, /// Identifier for customer. pub customer_id: Option<CustomerId>, pub line_items: Vec<SubscriptionLineItem>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct SubscriptionLineItem { /// Unique identifier for the line item. pub item_id: String, /// Type of the line item. pub item_type: String, /// Description of the line item. pub description: String, /// Amount for the line item. pub amount: MinorUnit, /// Currency for the line item pub currency: Currency, /// Quantity of the line item. pub quantity: i64, } impl ApiEventMetric for EstimateSubscriptionResponse {}
{ "crate": "api_models", "file": "crates/api_models/src/subscription.rs", "file_size": 18450, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-371809284769464924
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/customers.rs // File size: 18426 bytes use common_utils::{crypto, custom_serde, id_type, pii, types::Description}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::payments; /// The customer details #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequest { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequestWithConstraints { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, /// Unique identifier for a customer pub customer_id: Option<id_type::CustomerId>, /// Filter with created time range #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, } #[cfg(feature = "v1")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some( self.customer_id .to_owned() .unwrap_or_else(common_utils::generate_customer_id_of_default_length), ) } pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { self.email.clone() } } /// The customer details #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerRequest { /// The merchant identifier for the customer object. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Secret<String>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: pii::Email, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { Some(self.email.clone()) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] pub default_payment_method_id: Option<String>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v1")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some(self.customer_id.clone()) } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Connector specific customer reference ids #[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))] pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String> ,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v2")] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerUpdateRequest { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// Customer's tax registration ID #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v1")] impl CustomerUpdateRequest { pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// 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 = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the payment method #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// The customer's tax registration number. #[schema(max_length = 255, value_type = Option<String>, example = "123456789")] pub tax_registration_id: Option<Secret<String>>, } #[cfg(feature = "v2")] impl CustomerUpdateRequest { pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub customer_id: id_type::CustomerId, pub request: CustomerUpdateRequest, } #[cfg(feature = "v2")] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub id: id_type::GlobalCustomerId, pub request: CustomerUpdateRequest, } #[derive(Debug, Serialize, ToSchema)] pub struct CustomerListResponse { /// List of customers pub data: Vec<CustomerResponse>, /// Total count of customers pub total_count: usize, }
{ "crate": "api_models", "file": "crates/api_models/src/customers.rs", "file_size": 18426, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_7836978701455006643
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/webhooks.rs // File size: 17754 bytes use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "payouts")] use crate::payouts; use crate::{disputes, enums as api_enums, mandates, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { /// Authorization + Capture failure PaymentIntentFailure, /// Authorization + Capture success PaymentIntentSuccess, PaymentIntentProcessing, PaymentIntentPartiallyFunded, PaymentIntentCancelled, PaymentIntentCancelFailure, PaymentIntentAuthorizationSuccess, PaymentIntentAuthorizationFailure, PaymentIntentExtendAuthorizationSuccess, PaymentIntentExtendAuthorizationFailure, PaymentIntentCaptureSuccess, PaymentIntentCaptureFailure, PaymentIntentExpired, PaymentActionRequired, EventNotSupported, SourceChargeable, SourceTransactionCreated, RefundFailure, RefundSuccess, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, MandateActive, MandateRevoked, EndpointVerification, ExternalAuthenticationARes, FrmApproved, FrmRejected, #[cfg(feature = "payouts")] PayoutSuccess, #[cfg(feature = "payouts")] PayoutFailure, #[cfg(feature = "payouts")] PayoutProcessing, #[cfg(feature = "payouts")] PayoutCancelled, #[cfg(feature = "payouts")] PayoutCreated, #[cfg(feature = "payouts")] PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentFailure, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentSuccess, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentPending, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryInvoiceCancel, SetupWebhook, InvoiceGenerated, } impl IncomingWebhookEvent { /// Convert UCS event type integer to IncomingWebhookEvent /// Maps from proto WebhookEventType enum values to IncomingWebhookEvent variants pub fn from_ucs_event_type(event_type: i32) -> Self { match event_type { 0 => Self::EventNotSupported, // Payment intent events 1 => Self::PaymentIntentFailure, 2 => Self::PaymentIntentSuccess, 3 => Self::PaymentIntentProcessing, 4 => Self::PaymentIntentPartiallyFunded, 5 => Self::PaymentIntentCancelled, 6 => Self::PaymentIntentCancelFailure, 7 => Self::PaymentIntentAuthorizationSuccess, 8 => Self::PaymentIntentAuthorizationFailure, 9 => Self::PaymentIntentCaptureSuccess, 10 => Self::PaymentIntentCaptureFailure, 11 => Self::PaymentIntentExpired, 12 => Self::PaymentActionRequired, // Source events 13 => Self::SourceChargeable, 14 => Self::SourceTransactionCreated, // Refund events 15 => Self::RefundFailure, 16 => Self::RefundSuccess, // Dispute events 17 => Self::DisputeOpened, 18 => Self::DisputeExpired, 19 => Self::DisputeAccepted, 20 => Self::DisputeCancelled, 21 => Self::DisputeChallenged, 22 => Self::DisputeWon, 23 => Self::DisputeLost, // Mandate events 24 => Self::MandateActive, 25 => Self::MandateRevoked, // Miscellaneous events 26 => Self::EndpointVerification, 27 => Self::ExternalAuthenticationARes, 28 => Self::FrmApproved, 29 => Self::FrmRejected, // Payout events #[cfg(feature = "payouts")] 30 => Self::PayoutSuccess, #[cfg(feature = "payouts")] 31 => Self::PayoutFailure, #[cfg(feature = "payouts")] 32 => Self::PayoutProcessing, #[cfg(feature = "payouts")] 33 => Self::PayoutCancelled, #[cfg(feature = "payouts")] 34 => Self::PayoutCreated, #[cfg(feature = "payouts")] 35 => Self::PayoutExpired, #[cfg(feature = "payouts")] 36 => Self::PayoutReversed, _ => Self::EventNotSupported, } } } pub enum WebhookFlow { Payment, #[cfg(feature = "payouts")] Payout, Refund, Dispute, Subscription, ReturnResponse, BankTransfer, Mandate, ExternalAuthentication, FraudCheck, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] Recovery, Setup, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] /// This enum tells about the affect a webhook had on an object pub enum WebhookResponseTracker { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "payouts")] Payout { payout_id: common_utils::id_type::PayoutId, status: common_enums::PayoutStatus, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v1")] Dispute { dispute_id: String, payment_id: common_utils::id_type::PaymentId, status: common_enums::DisputeStatus, }, #[cfg(feature = "v2")] Dispute { dispute_id: String, payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::DisputeStatus, }, Mandate { mandate_id: String, status: common_enums::MandateStatus, }, #[cfg(feature = "v1")] PaymentMethod { payment_method_id: String, status: common_enums::PaymentMethodStatus, }, NoEffect, Relay { relay_id: common_utils::id_type::RelayId, status: common_enums::RelayStatus, }, } impl WebhookResponseTracker { #[cfg(feature = "v1")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } #[cfg(feature = "v1")] pub fn get_payment_method_id(&self) -> Option<String> { match self { Self::PaymentMethod { payment_method_id, .. } => Some(payment_method_id.to_owned()), Self::Payment { .. } | Self::Refund { .. } | Self::Dispute { .. } | Self::NoEffect | Self::Mandate { .. } | Self::Relay { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, } } #[cfg(feature = "v2")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } } impl From<IncomingWebhookEvent> for WebhookFlow { fn from(evt: IncomingWebhookEvent) -> Self { match evt { IncomingWebhookEvent::PaymentIntentFailure | IncomingWebhookEvent::PaymentIntentSuccess | IncomingWebhookEvent::PaymentIntentProcessing | IncomingWebhookEvent::PaymentActionRequired | IncomingWebhookEvent::PaymentIntentPartiallyFunded | IncomingWebhookEvent::PaymentIntentCancelled | IncomingWebhookEvent::PaymentIntentCancelFailure | IncomingWebhookEvent::PaymentIntentAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentAuthorizationFailure | IncomingWebhookEvent::PaymentIntentCaptureSuccess | IncomingWebhookEvent::PaymentIntentCaptureFailure | IncomingWebhookEvent::PaymentIntentExpired | IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure => Self::Payment, IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse, IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => { Self::Refund } IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => { Self::Mandate } IncomingWebhookEvent::DisputeOpened | IncomingWebhookEvent::DisputeAccepted | IncomingWebhookEvent::DisputeExpired | IncomingWebhookEvent::DisputeCancelled | IncomingWebhookEvent::DisputeChallenged | IncomingWebhookEvent::DisputeWon | IncomingWebhookEvent::DisputeLost => Self::Dispute, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, IncomingWebhookEvent::SourceChargeable | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer, IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication, IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => { Self::FraudCheck } #[cfg(feature = "payouts")] IncomingWebhookEvent::PayoutSuccess | IncomingWebhookEvent::PayoutFailure | IncomingWebhookEvent::PayoutProcessing | IncomingWebhookEvent::PayoutCancelled | IncomingWebhookEvent::PayoutCreated | IncomingWebhookEvent::PayoutExpired | IncomingWebhookEvent::PayoutReversed => Self::Payout, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] IncomingWebhookEvent::RecoveryInvoiceCancel | IncomingWebhookEvent::RecoveryPaymentFailure | IncomingWebhookEvent::RecoveryPaymentPending | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, IncomingWebhookEvent::SetupWebhook => Self::Setup, IncomingWebhookEvent::InvoiceGenerated => Self::Subscription, } } } pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum RefundIdType { RefundId(String), ConnectorRefundId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum MandateIdType { MandateId(String), ConnectorMandateId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum AuthenticationIdType { AuthenticationId(common_utils::id_type::AuthenticationId), ConnectorAuthenticationId(String), } #[cfg(feature = "payouts")] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum PayoutIdType { PayoutAttemptId(String), ConnectorPayoutId(String), } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum ObjectReferenceId { PaymentId(payments::PaymentIdType), RefundId(RefundIdType), MandateId(MandateIdType), ExternalAuthenticationID(AuthenticationIdType), #[cfg(feature = "payouts")] PayoutId(PayoutIdType), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] InvoiceId(InvoiceIdType), SubscriptionId(common_utils::id_type::SubscriptionId), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub enum InvoiceIdType { ConnectorInvoiceId(String), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl ObjectReferenceId { pub fn get_connector_transaction_id_as_string( self, ) -> Result<String, common_utils::errors::ValidationError> { match self { Self::PaymentId( payments::PaymentIdType::ConnectorTransactionId(id) ) => Ok(id), Self::PaymentId(_)=>Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant", }, ), Self::RefundId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received RefundId", }, ), Self::MandateId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received MandateId", }, ), Self::ExternalAuthenticationID(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received ExternalAuthenticationID", }, ), #[cfg(feature = "payouts")] Self::PayoutId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received PayoutId", }, ), Self::InvoiceId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received InvoiceId", }, ), Self::SubscriptionId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received SubscriptionId", }, ), } } } pub struct IncomingWebhookDetails { pub object_reference_id: ObjectReferenceId, pub resource_object: Vec<u8>, } #[derive(Debug, Serialize, ToSchema)] pub struct OutgoingWebhook { /// The merchant id of the merchant #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique event id for each webhook pub event_id: String, /// The type of event this webhook corresponds to. #[schema(value_type = EventType)] pub event_type: api_enums::EventType, /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, /// The time at which webhook was sent #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v1")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize)] pub struct ConnectorWebhookSecrets { pub secret: Vec<u8>, pub additional_secret: Option<masking::Secret<String>>, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl IncomingWebhookEvent { pub fn is_recovery_transaction_event(&self) -> bool { matches!( self, Self::RecoveryPaymentFailure | Self::RecoveryPaymentSuccess | Self::RecoveryPaymentPending ) } }
{ "crate": "api_models", "file": "crates/api_models/src/webhooks.rs", "file_size": 17754, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_1888206638980586583
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/events/payment.rs // File size: 17341 bytes use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "v2")] use super::{ PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, RecoveryPaymentsCreate, RecoveryPaymentsResponse, }; #[cfg(feature = "v2")] use crate::payment_methods::{ ListMethodsForPaymentMethodsRequest, PaymentMethodListResponseForSession, }; use crate::{ payment_methods::{ self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse, RedirectionResponse, }, }; #[cfg(feature = "v1")] use crate::{ payment_methods::{PaymentMethodListRequest, PaymentMethodListResponse}, payments::{ ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, }, }; #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.resource_id { PaymentIdType::PaymentIntentId(ref id) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsStartRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.to_owned(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsUpdateMetadataRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsUpdateMetadataResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelPostCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExtendAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsApproveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRejectRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.payment_id { Some(PaymentIdType::PaymentIntentId(ref id)) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsEligibilityRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsEligibilityResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsCreateIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::GiftCardBalanceCheckResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsGetIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentAttemptListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_intent_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentAttemptListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsIntentResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCancelResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentMethodResponse { #[cfg(feature = "v1")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: self.payment_method, payment_method_type: self.payment_method_type, }) } #[cfg(feature = "v2")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodMigrateResponse { #[cfg(feature = "v1")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.payment_method_id.clone(), payment_method: self.payment_method_response.payment_method, payment_method_type: self.payment_method_response.payment_method_type, }) } #[cfg(feature = "v2")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.id.clone(), payment_method_type: self.payment_method_response.payment_method_type, payment_method_subtype: self.payment_method_response.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodUpdate {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::DefaultPaymentMethod { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: None, payment_method_subtype: None, }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } impl ApiEventMetric for payment_methods::CustomerPaymentMethodsListResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodList { payment_id: self .client_secret .as_ref() .and_then(|cs| cs.rsplit_once("_secret_")) .map(|(pid, _)| pid.to_string()), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for ListMethodsForPaymentMethodsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodList { payment_id: self .client_secret .as_ref() .and_then(|cs| cs.rsplit_once("_secret_")) .map(|(pid, _)| pid.to_string()), }) } } impl ApiEventMetric for ListCountriesCurrenciesRequest {} impl ApiEventMetric for ListCountriesCurrenciesResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodListResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(), payment_method: Some(self.payment_method), payment_method_type: self.payment_method_type, }) } } impl ApiEventMetric for PaymentMethodCollectLinkRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.pm_collect_link_id .as_ref() .map(|id| ApiEventsType::PaymentMethodCollectLink { link_id: id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkRenderRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFiltersV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v2")] impl ApiEventMetric for RecoveryPaymentsCreate { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for RecoveryPaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListResponseV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentsAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RedirectionResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for ExtendedCardInfoResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentsSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentStartRedirectionRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentMethodListResponseForPayments { // Payment id would be populated by the request fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodListResponseForSession {} #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCaptureResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/events/payment.rs", "file_size": 17341, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_5827519295279039671
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics.rs // File size: 16808 bytes use std::collections::HashSet; pub use common_utils::types::TimeRange; use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo}; use masking::Secret; use self::{ active_payments::ActivePaymentsMetrics, api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundDistributions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; pub mod active_payments; pub mod api_event; pub mod auth_events; pub mod connector_events; pub mod disputes; pub mod frm; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; pub mod refunds; pub mod routing_events; pub mod sdk_events; pub mod search; #[derive(Debug, serde::Serialize)] pub struct NameDescription { pub name: String, pub desc: String, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetInfoResponse { pub metrics: Vec<NameDescription>, pub download_dimensions: Option<Vec<NameDescription>>, pub dimensions: Vec<NameDescription>, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub struct TimeSeries { pub granularity: Granularity, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum Granularity { #[serde(rename = "G_ONEMIN")] OneMin, #[serde(rename = "G_FIVEMIN")] FiveMin, #[serde(rename = "G_FIFTEENMIN")] FifteenMin, #[serde(rename = "G_THIRTYMIN")] ThirtyMin, #[serde(rename = "G_ONEHOUR")] OneHour, #[serde(rename = "G_ONEDAY")] OneDay, } pub trait ForexMetric { fn is_forex_metric(&self) -> bool; } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AnalyticsRequest { pub payment_intent: Option<GetPaymentIntentMetricRequest>, pub payment_attempt: Option<GetPaymentMetricRequest>, pub refund: Option<GetRefundMetricRequest>, pub dispute: Option<GetDisputeMetricRequest>, } impl AnalyticsRequest { pub fn requires_forex_functionality(&self) -> bool { self.payment_attempt .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .payment_intent .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .refund .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .dispute .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, #[serde(default)] pub filters: payments::PaymentFilters, pub metrics: HashSet<PaymentMetrics>, pub distribution: Option<PaymentDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum QueryLimit { #[serde(rename = "TOP_5")] Top5, #[serde(rename = "TOP_10")] Top10, } #[allow(clippy::from_over_into)] impl Into<u64> for QueryLimit { fn into(self) -> u64 { match self { Self::Top5 => 5, Self::Top10 => 10, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentDistributionBody { pub distribution_for: PaymentDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundDistributionBody { pub distribution_for: RefundDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ReportRequest { pub time_range: TimeRange, pub emails: Option<Vec<Secret<String, EmailStrategy>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GenerateReportRequest { pub request: ReportRequest, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub auth: AuthInfo, pub email: Secret<String, EmailStrategy>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, #[serde(default)] pub filters: payment_intents::PaymentIntentFilters, pub metrics: HashSet<PaymentIntentMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, #[serde(default)] pub filters: refunds::RefundFilters, pub metrics: HashSet<RefundMetrics>, pub distribution: Option<RefundDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, #[serde(default)] pub filters: frm::FrmFilters, pub metrics: HashSet<FrmMetrics>, #[serde(default)] pub delta: bool, } impl ApiEventMetric for GetFrmMetricRequest {} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, #[serde(default)] pub filters: sdk_events::SdkEventFilters, pub metrics: HashSet<SdkEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, #[serde(default)] pub filters: AuthEventFilters, #[serde(default)] pub metrics: HashSet<AuthEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetActivePaymentsMetricRequest { #[serde(default)] pub metrics: HashSet<ActivePaymentsMetrics>, pub time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct AnalyticsMetadata { pub current_time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct PaymentsAnalyticsMetadata { pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, pub total_failure_reasons_count: Option<u64>, pub total_failure_reasons_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct PaymentIntentsAnalyticsMetadata { pub total_success_rate: Option<f64>, pub total_success_rate_without_smart_retries: Option<f64>, pub total_smart_retried_amount: Option<u64>, pub total_smart_retried_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_smart_retried_amount_in_usd: Option<u64>, pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundsAnalyticsMetadata { pub total_refund_success_rate: Option<f64>, pub total_refund_processed_amount: Option<u64>, pub total_refund_processed_amount_in_usd: Option<u64>, pub total_refund_processed_count: Option<u64>, pub total_refund_reason_count: Option<u64>, pub total_refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFiltersResponse { pub query_data: Vec<FilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct FilterValue { pub dimension: PaymentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFiltersResponse { pub query_data: Vec<PaymentIntentFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFilterValue { pub dimension: PaymentIntentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFiltersResponse { pub query_data: Vec<RefundFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, } impl ApiEventMetric for GetFrmFilterRequest {} #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFiltersResponse { pub query_data: Vec<FrmFilterValue>, } impl ApiEventMetric for FrmFiltersResponse {} #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFilterValue { pub dimension: FrmDimensions, pub values: Vec<String>, } impl ApiEventMetric for FrmFilterValue {} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFiltersResponse { pub query_data: Vec<SdkEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFilterValue { pub dimension: SdkEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] pub struct DisputesAnalyticsMetadata { pub total_disputed_amount: Option<u64>, pub total_dispute_lost_amount: Option<u64>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentIntentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [RefundsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct DisputesMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [DisputesAnalyticsMetadata; 1], } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFiltersResponse { pub query_data: Vec<ApiEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFilterValue { pub dimension: ApiEventDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, #[serde(default)] pub filters: api_event::ApiEventFilters, pub metrics: HashSet<ApiEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFiltersResponse { pub query_data: Vec<DisputeFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFilterValue { pub dimension: DisputeDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, #[serde(default)] pub filters: disputes::DisputeFilters, pub metrics: HashSet<DisputeMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, Default, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SankeyResponse { pub count: i64, pub status: String, pub refunds_status: Option<String>, pub dispute_status: Option<String>, pub first_attempt: i64, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFiltersResponse { pub query_data: Vec<AuthEventFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFilterValue { pub dimension: AuthEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthEventMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AuthEventsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] pub struct AuthEventsAnalyticsMetadata { pub total_error_message_count: Option<u64>, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics.rs", "file_size": 16808, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_3348291150145270102
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/enums.rs // File size: 15856 bytes use std::str::FromStr; pub use common_enums::*; use utoipa::ToSchema; pub use super::connector_enums::Connector; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } #[cfg(feature = "payouts")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutConnectors { Adyen, Adyenplatform, Cybersource, Ebanx, Gigadat, Loonio, Nomupay, Nuvei, Payone, Paypal, Stripe, Wise, Worldpay, } #[cfg(feature = "v2")] /// Whether active attempt is to be set/unset #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum UpdateActiveAttempt { /// Request to set the active attempt id #[schema(value_type = Option<String>)] Set(common_utils::id_type::GlobalAttemptId), /// To unset the active attempt id Unset, } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for RoutableConnectors { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for Connector { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Gigadat => Self::Gigadat, PayoutConnectors::Loonio => Self::Loonio, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Nuvei => Self::Nuvei, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, PayoutConnectors::Worldpay => Self::Worldpay, } } } #[cfg(feature = "payouts")] impl TryFrom<Connector> for PayoutConnectors { type Error = String; fn try_from(value: Connector) -> Result<Self, Self::Error> { match value { Connector::Adyen => Ok(Self::Adyen), Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), Connector::Gigadat => Ok(Self::Gigadat), Connector::Loonio => Ok(Self::Loonio), Connector::Nuvei => Ok(Self::Nuvei), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Stripe => Ok(Self::Stripe), Connector::Wise => Ok(Self::Wise), Connector::Worldpay => Ok(Self::Worldpay), _ => Err(format!("Invalid payout connector {value}")), } } } #[cfg(feature = "frm")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmConnectors { /// Signifyd Risk Manager. Official docs: https://docs.signifyd.com/ Signifyd, Riskified, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TaxConnectors { Taxjar, } #[derive(Clone, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BillingConnectors { Chargebee, Recurly, Stripebilling, Custombilling, #[cfg(feature = "dummy_connector")] DummyBillingConnector, } #[derive(Clone, Copy, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum VaultConnectors { Vgs, HyperswitchVault, Tokenex, } impl From<VaultConnectors> for Connector { fn from(value: VaultConnectors) -> Self { match value { VaultConnectors::Vgs => Self::Vgs, VaultConnectors::HyperswitchVault => Self::HyperswitchVault, VaultConnectors::Tokenex => Self::Tokenex, } } } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmAction { CancelTxn, AutoRefund, ManualReview, } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmPreferredFlowTypes { Pre, Post, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct UnresolvedResponseReason { pub code: String, /// A message to merchant to give hint on next action he/she should do to resolve pub message: String, } /// Possible field type of required fields in payment_method_data #[derive( Clone, Debug, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FieldType { UserCardNumber, UserCardExpiryMonth, UserCardExpiryYear, UserCardCvc, UserCardNetwork, UserFullName, UserEmailAddress, UserPhoneNumber, UserPhoneNumberCountryCode, //phone number's country code UserCountry { options: Vec<String> }, //for country inside payment method data ex- bank redirect UserCurrency { options: Vec<String> }, UserCryptoCurrencyNetwork, //for crypto network associated with the cryptopcurrency UserBillingName, UserAddressLine1, UserAddressLine2, UserAddressCity, UserAddressPincode, UserAddressState, UserAddressCountry { options: Vec<String> }, UserShippingName, UserShippingAddressLine1, UserShippingAddressLine2, UserShippingAddressCity, UserShippingAddressPincode, UserShippingAddressState, UserShippingAddressCountry { options: Vec<String> }, UserSocialSecurityNumber, UserBlikCode, UserBank, UserBankOptions { options: Vec<String> }, UserBankAccountNumber, UserSourceBankAccountId, UserDestinationBankAccountId, Text, DropDown { options: Vec<String> }, UserDateOfBirth, UserVpaId, LanguagePreference { options: Vec<String> }, UserPixKey, UserCpf, UserCnpj, UserIban, UserBsbNumber, UserBankSortCode, UserBankRoutingNumber, UserBankType { options: Vec<String> }, UserBankAccountHolderName, UserMsisdn, UserClientIdentifier, OrderDetailsProductName, } impl FieldType { pub fn get_billing_variants() -> Vec<Self> { vec![ Self::UserBillingName, Self::UserAddressLine1, Self::UserAddressLine2, Self::UserAddressCity, Self::UserAddressPincode, Self::UserAddressState, Self::UserAddressCountry { options: vec![] }, ] } pub fn get_shipping_variants() -> Vec<Self> { vec![ Self::UserShippingName, Self::UserShippingAddressLine1, Self::UserShippingAddressLine2, Self::UserShippingAddressCity, Self::UserShippingAddressPincode, Self::UserShippingAddressState, Self::UserShippingAddressCountry { options: vec![] }, ] } } /// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing impl PartialEq for FieldType { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::UserCardNumber, Self::UserCardNumber) => true, (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true, (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true, (Self::UserCardCvc, Self::UserCardCvc) => true, (Self::UserFullName, Self::UserFullName) => true, (Self::UserEmailAddress, Self::UserEmailAddress) => true, (Self::UserPhoneNumber, Self::UserPhoneNumber) => true, (Self::UserPhoneNumberCountryCode, Self::UserPhoneNumberCountryCode) => true, ( Self::UserCountry { options: options_self, }, Self::UserCountry { options: options_other, }, ) => options_self.eq(options_other), ( Self::UserCurrency { options: options_self, }, Self::UserCurrency { options: options_other, }, ) => options_self.eq(options_other), (Self::UserCryptoCurrencyNetwork, Self::UserCryptoCurrencyNetwork) => true, (Self::UserBillingName, Self::UserBillingName) => true, (Self::UserAddressLine1, Self::UserAddressLine1) => true, (Self::UserAddressLine2, Self::UserAddressLine2) => true, (Self::UserAddressCity, Self::UserAddressCity) => true, (Self::UserAddressPincode, Self::UserAddressPincode) => true, (Self::UserAddressState, Self::UserAddressState) => true, (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, (Self::UserShippingName, Self::UserShippingName) => true, (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true, (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true, (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true, (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true, (Self::UserShippingAddressState, Self::UserShippingAddressState) => true, (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => { true } (Self::UserBlikCode, Self::UserBlikCode) => true, (Self::UserBank, Self::UserBank) => true, (Self::Text, Self::Text) => true, ( Self::DropDown { options: options_self, }, Self::DropDown { options: options_other, }, ) => options_self.eq(options_other), (Self::UserDateOfBirth, Self::UserDateOfBirth) => true, (Self::UserVpaId, Self::UserVpaId) => true, (Self::UserPixKey, Self::UserPixKey) => true, (Self::UserCpf, Self::UserCpf) => true, (Self::UserCnpj, Self::UserCnpj) => true, (Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true, (Self::UserMsisdn, Self::UserMsisdn) => true, (Self::UserClientIdentifier, Self::UserClientIdentifier) => true, (Self::OrderDetailsProductName, Self::OrderDetailsProductName) => true, _unused => false, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_partialeq_for_field_type() { let user_address_country_is_us = FieldType::UserAddressCountry { options: vec!["US".to_string()], }; let user_address_country_is_all = FieldType::UserAddressCountry { options: vec!["ALL".to_string()], }; assert!(user_address_country_is_us.eq(&user_address_country_is_all)) } } /// Denotes the retry action #[derive( Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, Clone, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RetryAction { /// Manual retry through request is being deprecated, now it is available through profile ManualRetry, /// Denotes that the payment is requeued Requeue, } #[derive(Clone, Copy)] pub enum LockerChoice { HyperswitchCardVault, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PmAuthConnectors { Plaid, } pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { PmAuthConnectors::from_str(connector_name).ok() } pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> { AuthenticationConnectors::from_str(connector_name).ok() } pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> { TaxConnectors::from_str(connector_name).ok() } pub fn convert_billing_connector(connector_name: &str) -> Option<BillingConnectors> { BillingConnectors::from_str(connector_name).ok() } #[cfg(feature = "frm")] pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() } pub fn convert_vault_connector(connector_name: &str) -> Option<VaultConnectors> { VaultConnectors::from_str(connector_name).ok() } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] pub enum ReconPermissionScope { #[serde(rename = "R")] Read = 0, #[serde(rename = "RW")] Write = 1, } impl From<PermissionScope> for ReconPermissionScope { fn from(scope: PermissionScope) -> Self { match scope { PermissionScope::Read => Self::Read, PermissionScope::Write => Self::Write, } } } #[cfg(feature = "v2")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, ToSchema, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumIter, strum::EnumString, )] #[serde(rename_all = "UPPERCASE")] #[strum(serialize_all = "UPPERCASE")] pub enum TokenStatus { /// Indicates that the token is active and can be used for payments Active, /// Indicates that the token is suspended from network's end for some reason and can't be used for payments until it is re-activated Suspended, /// Indicates that the token is deactivated and further can't be used for payments Deactivated, }
{ "crate": "api_models", "file": "crates/api_models/src/enums.rs", "file_size": 15856, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-4865616609014060893
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/open_router.rs // File size: 13490 bytes use std::{collections::HashMap, fmt::Debug}; use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{Currency, PaymentMethod}, payment_methods, }; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, pub filter_wise_gateways: Option<serde_json::Value>, pub priority_logic_tag: Option<String>, pub routing_approach: Option<String>, pub gateway_before_evaluation: Option<String>, pub priority_logic_output: Option<PriorityLogicOutput>, pub reset_approach: Option<String>, pub routing_dimension: Option<String>, pub routing_dimension_level: Option<String>, pub is_scheduled_outage: Option<bool>, pub is_dynamic_mga_enabled: Option<bool>, pub gateway_mga_id_map: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PriorityLogicOutput { pub is_enforcement: Option<bool>, pub gws: Option<Vec<String>>, pub priority_logic_tag: Option<String>, pub gateway_reference_ids: Option<HashMap<String, String>>, pub primary_logic: Option<PriorityLogicData>, pub fallback_logic: Option<PriorityLogicData>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PriorityLogicData { pub name: Option<String>, pub status: Option<String>, pub failure_reason: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PaymentInfo { #[schema(value_type = String)] pub payment_id: id_type::PaymentId, pub amount: MinorUnit, pub currency: Currency, // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, // emiTenure: Option<i32>, pub payment_method_type: String, pub payment_method: PaymentMethod, // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DebitRoutingOutput { pub co_badged_card_networks_info: CoBadgedCardNetworks, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworksInfo { pub network: common_enums::CardNetwork, pub saving_percentage: f64, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>); impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { self.0.iter().map(|info| info.network.clone()).collect() } pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { self.0 .iter() .find(|info| info.network.is_signature_network()) .map(|info| info.network.clone()) } } impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { fn from(output: &DebitRoutingOutput) -> Self { Self { co_badged_card_networks_info: output.co_badged_card_networks_info.clone(), issuer_country_code: output.issuer_country, is_regulated: output.is_regulated, regulated_name: output.regulated_name.clone(), } } } impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { type Error = error_stack::Report<errors::ParsingError>; fn try_from( (output, card_type): (payment_methods::CoBadgedCardData, String), ) -> Result<Self, Self::Error> { let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) })?; Ok(Self { co_badged_card_networks_info: output.co_badged_card_networks_info.get_card_networks(), issuer_country: output.issuer_country_code, is_regulated: output.is_regulated, regulated_name: output.regulated_name, card_type: parsed_card_type, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode, pub acquirer_country: common_enums::CountryAlpha2, pub co_badged_card_data: Option<DebitRoutingRequestData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DebitRoutingRequestData { pub co_badged_card_networks_info: Vec<common_enums::CardNetwork>, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ErrorResponse { pub status: String, pub error_code: String, pub error_message: String, pub priority_logic_tag: Option<String>, pub filter_wise_gateways: Option<serde_json::Value>, pub error_info: UnifiedError, pub is_dynamic_mga_enabled: bool, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct UnifiedError { pub code: String, pub user_message: String, pub developer_message: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub gateway: String, pub status: TxnStatus, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] pub struct UpdateScoreResponse { pub message: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CODInitiated, Voided, VoidedPostCharge, VoidInitiated, Nop, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, ToBeCharged, Pending, Failure, Declined, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DecisionEngineConfigSetupRequest { pub merchant_id: String, pub config: DecisionEngineConfigVariant, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetDecisionEngineConfigRequest { pub merchant_id: String, pub algorithm: DecisionEngineDynamicAlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub enum DecisionEngineDynamicAlgorithmType { SuccessRate, Elimination, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type", content = "data")] #[serde(rename_all = "camelCase")] pub enum DecisionEngineConfigVariant { SuccessRate(DecisionEngineSuccessRateData), Elimination(DecisionEngineEliminationData), } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSuccessRateData { pub default_latency_threshold: Option<f64>, pub default_bucket_size: Option<i32>, pub default_hedging_percent: Option<f64>, pub default_lower_reset_factor: Option<f64>, pub default_upper_reset_factor: Option<f64>, pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>, } impl DecisionEngineSuccessRateData { pub fn update(&mut self, new_config: Self) { if let Some(threshold) = new_config.default_latency_threshold { self.default_latency_threshold = Some(threshold); } if let Some(bucket_size) = new_config.default_bucket_size { self.default_bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.default_hedging_percent { self.default_hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.default_lower_reset_factor { self.default_lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.default_upper_reset_factor { self.default_upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.default_gateway_extra_score { self.default_gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } if let Some(sub_level_input_config) = new_config.sub_level_input_config { self.sub_level_input_config.as_mut().map(|config| { config.extend(sub_level_input_config); }); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSRSubLevelInputConfig { pub payment_method_type: Option<String>, pub payment_method: Option<String>, pub latency_threshold: Option<f64>, pub bucket_size: Option<i32>, pub hedging_percent: Option<f64>, pub lower_reset_factor: Option<f64>, pub upper_reset_factor: Option<f64>, pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, } impl DecisionEngineSRSubLevelInputConfig { pub fn update(&mut self, new_config: Self) { if let Some(payment_method_type) = new_config.payment_method_type { self.payment_method_type = Some(payment_method_type); } if let Some(payment_method) = new_config.payment_method { self.payment_method = Some(payment_method); } if let Some(latency_threshold) = new_config.latency_threshold { self.latency_threshold = Some(latency_threshold); } if let Some(bucket_size) = new_config.bucket_size { self.bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.hedging_percent { self.hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.lower_reset_factor { self.lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.upper_reset_factor { self.upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.gateway_extra_score { self.gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineGatewayWiseExtraScore { pub gateway_name: String, pub gateway_sigma_factor: f64, } impl DecisionEngineGatewayWiseExtraScore { pub fn update(&mut self, new_config: Self) { self.gateway_name = new_config.gateway_name; self.gateway_sigma_factor = new_config.gateway_sigma_factor; } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineEliminationData { pub threshold: f64, } impl DecisionEngineEliminationData { pub fn update(&mut self, new_config: Self) { self.threshold = new_config.threshold; } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MerchantAccount { pub merchant_id: String, pub gateway_success_rate_based_decider_input: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct FetchRoutingConfig { pub merchant_id: String, pub algorithm: AlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum AlgorithmType { SuccessRate, Elimination, DebitRouting, }
{ "crate": "api_models", "file": "crates/api_models/src/open_router.rs", "file_size": 13490, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-2585142289153246131
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/user.rs // File size: 13099 bytes use std::fmt::Debug; use common_enums::{EntityType, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; use utoipa::ToSchema; use crate::user_role::UserStatus; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; #[cfg(feature = "control_center_theme")] pub mod theme; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpWithMerchantIdRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub company_name: String, } pub type SignUpWithMerchantIdResponse = AuthorizeResponse; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpRequest { pub email: pii::Email, pub password: Secret<String>, } pub type SignInRequest = SignUpRequest; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { pub email: pii::Email, } pub type ConnectAccountResponse = AuthorizeResponse; #[derive(serde::Serialize, Debug, Clone)] pub struct AuthorizeResponse { pub is_email_sent: bool, //this field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ChangePasswordRequest { pub new_password: Secret<String>, pub old_password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ForgotPasswordRequest { pub email: pii::Email, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ResetPasswordRequest { pub token: Secret<String>, pub password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct RotatePasswordRequest { pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct InviteUserRequest { pub email: pii::Email, pub name: Secret<String>, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub struct InviteMultipleUserResponse { pub email: pii::Email, pub is_email_sent: bool, #[serde(skip_serializing_if = "Option::is_none")] pub password: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ReInviteUserRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct AcceptInviteFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchOrganizationRequest { pub org_id: id_type::OrganizationId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantRequest { pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchProfileRequest { pub profile_id: id_type::ProfileId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorSource { pub mca_id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorDestination { pub connector_label: Option<String>, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CloneConnectorRequest { pub source: CloneConnectorSource, pub destination: CloneConnectorDestination, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateInternalUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub role_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateTenantUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct UserOrgMerchantCreateRequest { pub organization_name: Secret<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PlatformAccountCreateRequest { #[schema(max_length = 64, value_type = String, example = "organization_abc")] pub organization_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PlatformAccountCreateResponse { #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_abc")] pub org_id: id_type::OrganizationId, #[schema(value_type = Option<String>, example = "organization_abc")] pub org_name: Option<String>, #[schema(value_type = OrganizationType, example = "standard")] pub org_type: common_enums::OrganizationType, #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, #[schema(value_type = MerchantAccountType, example = "standard")] pub merchant_account_type: common_enums::MerchantAccountType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountRequestType>, } #[derive(serde::Serialize, Debug, Clone)] pub struct GetUserDetailsResponse { pub merchant_id: id_type::MerchantId, pub name: Secret<String>, pub email: pii::Email, pub verification_days_left: Option<i64>, pub role_id: String, // This field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, pub profile_id: id_type::ProfileId, pub entity_type: EntityType, pub theme_id: Option<String>, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserRoleDetailsRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct GetUserRoleDetailsResponseV2 { pub role_id: String, pub org: NameIdUnit<Option<String>, id_type::OrganizationId>, pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, pub entity_type: EntityType, pub role_name: String, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> { pub name: N, pub id: I, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserAccountDetailsRequest { pub name: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SkipTwoFactorAuthQueryParam { pub skip_two_factor_auth: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TokenResponse { pub token: Secret<String>, pub token_type: TokenPurpose, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponse { pub totp: bool, pub recovery_code: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthAttempts { pub is_completed: bool, pub remaining_attempts: u8, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponseWithAttempts { pub totp: TwoFactorAuthAttempts, pub recovery_code: TwoFactorAuthAttempts, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorStatus { pub status: Option<TwoFactorAuthStatusResponseWithAttempts>, pub is_skippable: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct BeginTotpResponse { pub secret: Option<TotpSecret>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TotpSecret { pub secret: Secret<String>, pub totp_url: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyTotpRequest { pub totp: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyRecoveryCodeRequest { pub recovery_code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] #[serde(rename_all = "snake_case")] pub enum AuthConfig { OpenIdConnect { private_config: OpenIdConnectPrivateConfig, public_config: OpenIdConnectPublicConfig, }, MagicLink, Password, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPrivateConfig { pub base_url: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } #[derive( Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { Okta, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct OpenIdConnect { pub name: OpenIdProvider, pub base_url: String, pub client_id: String, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodRequest { pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_method: AuthConfig, pub allow_signup: bool, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_type: common_enums::UserAuthType, pub email_domain: Option<String>, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum UpdateUserAuthenticationMethodRequest { AuthMethod { id: String, auth_config: AuthConfig, }, EmailDomain { owner_id: String, email_domain: String, }, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserAuthenticationMethodsRequest { pub auth_id: Option<String>, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub auth_method: AuthMethodDetails, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthMethodDetails { #[serde(rename = "type")] pub auth_type: common_enums::UserAuthType, pub name: Option<OpenIdProvider>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetSsoAuthUrlRequest { pub id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SsoSignInRequest { pub state: Secret<String>, pub code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthIdAndThemeIdQueryParam { pub auth_id: Option<String>, pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthSelectRequest { pub id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct UserKeyTransferRequest { pub from: u32, pub limit: u32, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserTransferKeyResponse { pub total_transferred: usize, } #[derive(Debug, serde::Serialize)] pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, pub org_type: common_enums::OrganizationType, } #[derive(Debug, serde::Serialize)] pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Serialize)] pub struct ListProfilesForUserInOrgAndMerchantAccountResponse { pub profile_id: id_type::ProfileId, pub profile_name: String, }
{ "crate": "api_models", "file": "crates/api_models/src/user.rs", "file_size": 13099, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-3968335228569581373
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/auth_events.rs // File size: 11013 bytes use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, Currency, DecoupledAuthenticationType, TransactionStatus, }; use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct AuthEventFilters { #[serde(default)] pub authentication_status: Vec<AuthenticationStatus>, #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] pub authentication_type: Vec<DecoupledAuthenticationType>, #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, #[serde(default)] pub platform: Vec<String>, #[serde(default)] pub acs_reference_number: Vec<String>, #[serde(default)] pub mcc: Vec<String>, #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub merchant_country: Vec<String>, #[serde(default)] pub billing_country: Vec<String>, #[serde(default)] pub shipping_country: Vec<String>, #[serde(default)] pub issuer_country: Vec<String>, #[serde(default)] pub earliest_supported_version: Vec<String>, #[serde(default)] pub latest_supported_version: Vec<String>, #[serde(default)] pub whitelist_decision: Vec<bool>, #[serde(default)] pub device_manufacturer: Vec<String>, #[serde(default)] pub device_type: Vec<String>, #[serde(default)] pub device_brand: Vec<String>, #[serde(default)] pub device_os: Vec<String>, #[serde(default)] pub device_display: Vec<String>, #[serde(default)] pub browser_name: Vec<String>, #[serde(default)] pub browser_version: Vec<String>, #[serde(default)] pub issuer_id: Vec<String>, #[serde(default)] pub scheme_name: Vec<String>, #[serde(default)] pub exemption_requested: Vec<bool>, #[serde(default)] pub exemption_accepted: Vec<bool>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthEventDimensions { AuthenticationStatus, #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, AcsReferenceNumber, Platform, Mcc, Currency, MerchantCountry, BillingCountry, ShippingCountry, IssuerCountry, EarliestSupportedVersion, LatestSupportedVersion, WhitelistDecision, DeviceManufacturer, DeviceType, DeviceBrand, DeviceOs, DeviceDisplay, BrowserName, BrowserVersion, IssuerId, SchemeName, ExemptionRequested, ExemptionAccepted, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum AuthEventMetrics { AuthenticationCount, AuthenticationAttemptCount, AuthenticationSuccessCount, ChallengeFlowCount, FrictionlessFlowCount, FrictionlessSuccessCount, ChallengeAttemptCount, ChallengeSuccessCount, AuthenticationErrorMessage, AuthenticationFunnel, AuthenticationExemptionApprovedCount, AuthenticationExemptionRequestedCount, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] pub enum AuthEventFlows { IncomingWebhookReceive, PaymentsExternalAuthentication, } pub mod metric_behaviour { pub struct AuthenticationCount; pub struct AuthenticationAttemptCount; pub struct AuthenticationSuccessCount; pub struct ChallengeFlowCount; pub struct FrictionlessFlowCount; pub struct FrictionlessSuccessCount; pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { fn from(value: AuthEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<AuthEventDimensions> for NameDescription { fn from(value: AuthEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, pub acs_reference_number: Option<String>, pub mcc: Option<String>, pub currency: Option<Currency>, pub merchant_country: Option<String>, pub billing_country: Option<String>, pub shipping_country: Option<String>, pub issuer_country: Option<String>, pub earliest_supported_version: Option<String>, pub latest_supported_version: Option<String>, pub whitelist_decision: Option<bool>, pub device_manufacturer: Option<String>, pub device_type: Option<String>, pub device_brand: Option<String>, pub device_os: Option<String>, pub device_display: Option<String>, pub browser_name: Option<String>, pub browser_version: Option<String>, pub issuer_id: Option<String>, pub scheme_name: Option<String>, pub exemption_requested: Option<bool>, pub exemption_accepted: Option<bool>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl AuthEventMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] 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>, mcc: Option<String>, currency: Option<Currency>, merchant_country: Option<String>, billing_country: Option<String>, shipping_country: Option<String>, issuer_country: Option<String>, earliest_supported_version: Option<String>, latest_supported_version: Option<String>, whitelist_decision: Option<bool>, device_manufacturer: Option<String>, device_type: Option<String>, device_brand: Option<String>, device_os: Option<String>, device_display: Option<String>, browser_name: Option<String>, browser_version: Option<String>, issuer_id: Option<String>, scheme_name: Option<String>, exemption_requested: Option<bool>, exemption_accepted: Option<bool>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for AuthEventMetricsBucketIdentifier { 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.mcc.hash(state); self.currency.hash(state); self.merchant_country.hash(state); self.billing_country.hash(state); self.shipping_country.hash(state); self.issuer_country.hash(state); self.earliest_supported_version.hash(state); self.latest_supported_version.hash(state); self.whitelist_decision.hash(state); self.device_manufacturer.hash(state); self.device_type.hash(state); self.device_brand.hash(state); self.device_os.hash(state); self.device_display.hash(state); self.browser_name.hash(state); self.browser_version.hash(state); self.issuer_id.hash(state); self.scheme_name.hash(state); self.exemption_requested.hash(state); self.exemption_accepted.hash(state); self.time_bucket.hash(state); } } impl PartialEq for AuthEventMetricsBucketIdentifier { 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() } } #[derive(Debug, serde::Serialize)] pub struct AuthEventMetricsBucketValue { pub authentication_count: Option<u64>, pub authentication_attempt_count: Option<u64>, pub authentication_success_count: Option<u64>, pub challenge_flow_count: Option<u64>, pub challenge_attempt_count: Option<u64>, pub challenge_success_count: Option<u64>, pub frictionless_flow_count: Option<u64>, pub frictionless_success_count: Option<u64>, pub error_message_count: Option<u64>, pub authentication_funnel: Option<u64>, pub authentication_exemption_approved_count: Option<u64>, pub authentication_exemption_requested_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: AuthEventMetricsBucketValue, #[serde(flatten)] pub dimensions: AuthEventMetricsBucketIdentifier, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/auth_events.rs", "file_size": 11013, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-7231369096977446896
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/api_keys.rs // File size: 10661 bytes use common_utils::custom_serde; use masking::StrongSecret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The request body for creating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct CreateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, } /// The response body for creating an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct CreateApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The plaintext API Key used for server-side API access. Ensure you store the API Key /// securely as you will not be able to see it again. #[schema(value_type = String, max_length = 128)] pub api_key: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The response body for retrieving an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RetrieveApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The first few characters of the plaintext API Key to help you identify it. #[schema(value_type = String, max_length = 64)] pub prefix: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The request body for updating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct UpdateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: Option<String>, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: Option<ApiKeyExpiration>, #[serde(skip_deserializing)] #[schema(value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, } /// The response body for revoking an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RevokeApiKeyResponse { /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// Indicates whether the API key was revoked or not. #[schema(example = "true")] pub revoked: bool, } /// The constraints that are applicable when listing API Keys associated with a merchant account. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ListApiKeyConstraints { /// The maximum number of API Keys to include in the response. pub limit: Option<i64>, /// The number of API Keys to skip when retrieving the list of API keys. pub skip: Option<i64>, } /// The expiration date and time for an API Key. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum ApiKeyExpiration { /// The API Key does not expire. #[serde(with = "never")] Never, /// The API Key expires at the specified date and time. #[serde(with = "custom_serde::iso8601")] DateTime(PrimitiveDateTime), } impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> { fn from(expiration: ApiKeyExpiration) -> Self { match expiration { ApiKeyExpiration::Never => None, ApiKeyExpiration::DateTime(date_time) => Some(date_time), } } } impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration { fn from(date_time: Option<PrimitiveDateTime>) -> Self { date_time.map_or(Self::Never, Self::DateTime) } } // This implementation is required as otherwise, `serde` would serialize and deserialize // `ApiKeyExpiration::Never` as `null`, which is not preferable. // Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291 mod never { const NEVER: &str = "never"; pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(NEVER) } pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { struct NeverVisitor; impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, r#""{NEVER}""#) } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { if value == NEVER { Ok(()) } else { Err(E::invalid_value(serde::de::Unexpected::Str(value), &self)) } } } deserializer.deserialize_str(NeverVisitor) } } impl<'a> ToSchema<'a> for ApiKeyExpiration { fn schema() -> ( &'a str, utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>, ) { use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType}; ( "ApiKeyExpiration", OneOfBuilder::new() .item( ObjectBuilder::new() .schema_type(SchemaType::String) .enum_values(Some(["never"])), ) .item( ObjectBuilder::new() .schema_type(SchemaType::String) .format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))), ) .into(), ) } } #[cfg(test)] mod api_key_expiration_tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_serialization() { assert_eq!( serde_json::to_string(&ApiKeyExpiration::Never).unwrap(), r#""never""# ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new( date, time ))) .unwrap(), r#""2022-09-10T11:12:13.000Z""# ); } #[test] fn test_deserialization() { assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(), ApiKeyExpiration::Never ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time)) ); } #[test] fn test_null() { let result = serde_json::from_str::<ApiKeyExpiration>("null"); assert!(result.is_err()); let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap(); assert_eq!(result, None); } }
{ "crate": "api_models", "file": "crates/api_models/src/api_keys.rs", "file_size": 10661, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_2556802123311209961
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/disputes.rs // File size: 10628 bytes use std::collections::HashMap; use common_utils::types::{StringMinorUnit, TimeRange}; use masking::{Deserialize, Serialize}; use serde::de::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::enums::{Currency, DisputeStage, DisputeStatus}; use crate::{admin::MerchantConnectorInfo, files}; #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponse { /// The identifier for dispute pub dispute_id: String, /// The identifier for payment_intent #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The identifier for payment_attempt pub attempt_id: String, /// The dispute amount pub amount: StringMinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: Currency, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// connector to which dispute is associated with pub connector: String, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The `profile_id` associated with the dispute #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The `merchant_connector_id` of the connector / processor through which the dispute was processed #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponsePaymentsRetrieve { /// The identifier for dispute pub dispute_id: String, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, Serialize, Deserialize, strum::Display, Clone)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, } #[derive(Clone, Debug, Serialize, ToSchema)] pub struct DisputeEvidenceBlock { /// Evidence type pub evidence_type: EvidenceType, /// File metadata pub file_metadata_response: files::FileMetadataResponse, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct DisputeListGetConstraints { /// The identifier for dispute pub dispute_id: Option<String>, /// The payment_id against which dispute is raised pub payment_id: Option<common_utils::id_type::PaymentId>, /// Limit on the number of objects to return pub limit: Option<u32>, /// The starting point within a list of object pub offset: Option<u32>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The comma separated list of status of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_status: Option<Vec<DisputeStatus>>, /// The comma separated list of stages of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_stage: Option<Vec<DisputeStage>>, /// Reason for the dispute pub reason: Option<String>, /// The comma separated list of connectors linked to disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub connector: Option<Vec<String>>, /// The comma separated list of currencies of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub currency: Option<Vec<Currency>>, /// The merchant connector id to filter the disputes list pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct DisputeListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<Currency>, /// The list of available dispute status filters pub dispute_status: Vec<DisputeStatus>, /// The list of available dispute stage filters pub dispute_stage: Vec<DisputeStage>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct SubmitEvidenceRequest { ///Dispute Id pub dispute_id: String, /// Logs showing the usage of service by customer pub access_activity_log: Option<String>, /// Billing address of the customer pub billing_address: Option<String>, /// File Id of cancellation policy pub cancellation_policy: Option<String>, /// Details of showing cancellation policy to customer before purchase pub cancellation_policy_disclosure: Option<String>, /// Details telling why customer's subscription was not cancelled pub cancellation_rebuttal: Option<String>, /// File Id of customer communication pub customer_communication: Option<String>, /// Customer email address pub customer_email_address: Option<String>, /// Customer name pub customer_name: Option<String>, /// IP address of the customer pub customer_purchase_ip: Option<String>, /// Fild Id of customer signature pub customer_signature: Option<String>, /// Product Description pub product_description: Option<String>, /// File Id of receipt pub receipt: Option<String>, /// File Id of refund policy pub refund_policy: Option<String>, /// Details of showing refund policy to customer before purchase pub refund_policy_disclosure: Option<String>, /// Details why customer is not entitled to refund pub refund_refusal_explanation: Option<String>, /// Customer service date pub service_date: Option<String>, /// File Id service documentation pub service_documentation: Option<String>, /// Shipping address of the customer pub shipping_address: Option<String>, /// Delivery service that shipped the product pub shipping_carrier: Option<String>, /// Shipping date pub shipping_date: Option<String>, /// File Id shipping documentation pub shipping_documentation: Option<String>, /// Tracking number of shipped product pub shipping_tracking_number: Option<String>, /// File Id showing two distinct transactions when customer claims a payment was charged twice pub invoice_showing_distinct_transactions: Option<String>, /// File Id of recurring transaction agreement pub recurring_transaction_agreement: Option<String>, /// Any additional supporting file pub uncategorized_file: Option<String>, /// Any additional evidence statements pub uncategorized_text: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteEvidenceRequest { /// Id of the dispute pub dispute_id: String, /// Evidence Type to be deleted pub evidence_type: EvidenceType, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveRequest { /// The identifier for dispute pub dispute_id: String, /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct DisputesAggregateResponse { /// Different status of disputes with their count pub status_with_count: HashMap<DisputeStatus, i64>, } #[derive(Debug, Deserialize, Serialize)] pub struct DisputeRetrieveBody { /// Decider to enable or disable the connector call for dispute retrieve request pub force_sync: Option<bool>, } fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let output = Option::<&str>::deserialize(v)?; output .map(|s| { s.split(",") .map(|x| x.parse::<T>().map_err(D::Error::custom)) .collect::<Result<_, _>>() }) .transpose() }
{ "crate": "api_models", "file": "crates/api_models/src/disputes.rs", "file_size": 10628, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-3685019693585364810
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/payments.rs // File size: 10374 bytes use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_utils::id_type; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, PaymentMethodType, RoutingApproach, }; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentFilters { #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub status: Vec<AttemptStatus>, #[serde(default)] pub connector: Vec<Connector>, #[serde(default)] pub auth_type: Vec<AuthenticationType>, #[serde(default)] pub payment_method: Vec<PaymentMethod>, #[serde(default)] pub payment_method_type: Vec<PaymentMethodType>, #[serde(default)] pub client_source: Vec<String>, #[serde(default)] pub client_version: Vec<String>, #[serde(default)] pub card_network: Vec<CardNetwork>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] pub merchant_id: Vec<id_type::MerchantId>, #[serde(default)] pub card_last_4: Vec<String>, #[serde(default)] pub card_issuer: Vec<String>, #[serde(default)] pub error_reason: Vec<String>, #[serde(default)] pub first_attempt: Vec<bool>, #[serde(default)] pub routing_approach: Vec<RoutingApproach>, #[serde(default)] pub signature_network: Vec<String>, #[serde(default)] pub is_issuer_regulated: Vec<bool>, #[serde(default)] pub is_debit_routed: Vec<bool>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] 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, RoutingApproach, SignatureNetwork, IsIssuerRegulated, IsDebitRouted, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMetrics { PaymentSuccessRate, PaymentCount, PaymentSuccessCount, PaymentProcessedAmount, AvgTicketSize, RetriesCount, ConnectorSuccessRate, DebitRouting, SessionizedPaymentSuccessRate, SessionizedPaymentCount, SessionizedPaymentSuccessCount, SessionizedPaymentProcessedAmount, SessionizedAvgTicketSize, SessionizedRetriesCount, SessionizedConnectorSuccessRate, SessionizedDebitRouting, PaymentsDistribution, FailureReasons, } impl ForexMetric for PaymentMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::AvgTicketSize | Self::DebitRouting | Self::SessionizedPaymentProcessedAmount | Self::SessionizedAvgTicketSize | Self::SessionizedDebitRouting, ) } } #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, pub count: i64, pub percentage: f64, } #[derive( Clone, Copy, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentDistributions { #[strum(serialize = "error_message")] PaymentErrorMessage, } pub mod metric_behaviour { pub struct PaymentSuccessRate; pub struct PaymentCount; pub struct PaymentSuccessCount; pub struct PaymentProcessedAmount; pub struct AvgTicketSize; } impl From<PaymentMetrics> for NameDescription { fn from(value: PaymentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<PaymentDimensions> for NameDescription { fn from(value: PaymentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct PaymentMetricsBucketIdentifier { pub currency: Option<Currency>, pub status: Option<AttemptStatus>, pub connector: Option<String>, #[serde(rename = "authentication_type")] pub auth_type: Option<AuthenticationType>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, pub card_network: Option<String>, pub merchant_id: Option<String>, pub card_last_4: Option<String>, pub card_issuer: Option<String>, pub error_reason: Option<String>, pub routing_approach: Option<RoutingApproach>, pub signature_network: Option<String>, pub is_issuer_regulated: Option<bool>, pub is_debit_routed: Option<bool>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, // Coz FE sucks #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl PaymentMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] 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>, routing_approach: Option<RoutingApproach>, signature_network: Option<String>, is_issuer_regulated: Option<bool>, is_debit_routed: Option<bool>, 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, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for PaymentMetricsBucketIdentifier { 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.routing_approach .clone() .map(|i| i.to_string()) .hash(state); self.signature_network.hash(state); self.is_issuer_regulated.hash(state); self.is_debit_routed.hash(state); self.time_bucket.hash(state); } } impl PartialEq for PaymentMetricsBucketIdentifier { 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() } } #[derive(Debug, serde::Serialize)] pub struct PaymentMetricsBucketValue { pub payment_success_rate: Option<f64>, pub payment_count: Option<u64>, pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, pub payment_processed_amount_without_smart_retries_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub avg_ticket_size: Option<f64>, pub payment_error_message: Option<Vec<ErrorResult>>, pub retries_count: Option<u64>, pub retries_amount_processed: Option<u64>, pub connector_success_rate: Option<f64>, pub payments_success_rate_distribution: Option<f64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, pub payments_success_rate_distribution_with_only_retries: Option<f64>, pub payments_failure_rate_distribution: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, pub payments_failure_rate_distribution_with_only_retries: Option<f64>, pub failure_reason_count: Option<u64>, pub failure_reason_count_without_smart_retries: Option<u64>, pub debit_routed_transaction_count: Option<u64>, pub debit_routing_savings: Option<u64>, pub debit_routing_savings_in_usd: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: PaymentMetricsBucketValue, #[serde(flatten)] pub dimensions: PaymentMetricsBucketIdentifier, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/payments.rs", "file_size": 10374, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-2598883250609453721
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/payments/additional_info.rs // File size: 9464 bytes use common_utils::new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; use masking::Secret; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankDebitAdditionalData { Ach(Box<AchBankDebitAdditionalData>), Bacs(Box<BacsBankDebitAdditionalData>), Becs(Box<BecsBankDebitAdditionalData>), Sepa(Box<SepaBankDebitAdditionalData>), SepaGuarenteedDebit(Box<SepaBankDebitAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBankDebitAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub routing_number: MaskedRoutingNumber, /// Card holder's name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "ach")] pub bank_name: Option<common_enums::BankNames>, /// Bank account type #[schema(value_type = Option<BankType>, example = "checking")] pub bank_type: Option<common_enums::BankType>, /// Bank holder entity type #[schema(value_type = Option<BankHolderType>, example = "personal")] pub bank_holder_type: Option<common_enums::BankHolderType>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankDebitAdditionalData { /// Partially masked account number for Bacs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BecsBankDebitAdditionalData { /// Partially masked account number for Becs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] pub bsb_number: Secret<String>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankDebitAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub enum BankRedirectDetails { BancontactCard(Box<BancontactBankRedirectAdditionalData>), Blik(Box<BlikBankRedirectAdditionalData>), Giropay(Box<GiropayBankRedirectAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BancontactBankRedirectAdditionalData { /// Last 4 digits of the card number #[schema(value_type = Option<String>, example = "4242")] pub last4: Option<String>, /// The card's expiry month #[schema(value_type = Option<String>, example = "12")] pub card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = Option<String>, example = "24")] pub card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = Option<String>, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BlikBankRedirectAdditionalData { #[schema(value_type = Option<String>, example = "3GD9MO")] pub blik_code: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GiropayBankRedirectAdditionalData { #[schema(value_type = Option<String>)] /// Masked bank account bic code pub bic: Option<MaskedSortCode>, /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = Option<String>)] pub iban: Option<MaskedIban>, /// Country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferAdditionalData { Ach {}, Sepa {}, Bacs {}, Multibanco {}, Permata {}, Bca {}, BniVa {}, BriVa {}, CimbVa {}, DanamonVa {}, MandiriVa {}, Pix(Box<PixBankTransferAdditionalData>), Pse {}, LocalBankTransfer(Box<LocalBankTransferAdditionalData>), InstantBankTransfer {}, InstantBankTransferFinland {}, InstantBankTransferPoland {}, IndonesianBankTransfer { #[schema(value_type = Option<BankNames>, example = "bri")] bank_name: Option<common_enums::BankNames>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: Option<MaskedBankAccount>, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub cpf: Option<MaskedBankAccount>, /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, /// Partially masked source bank account number #[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")] pub source_bank_account_id: Option<MaskedBankAccount>, /// Partially masked destination bank account number _Deprecated: Will be removed in next stable release._ #[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b", deprecated)] pub destination_bank_account_id: Option<MaskedBankAccount>, /// The expiration date and time for the Pix QR code in ISO 8601 format #[schema(value_type = Option<String>, example = "2025-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expiry_date: Option<time::PrimitiveDateTime>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct LocalBankTransferAdditionalData { /// Partially masked bank code #[schema(value_type = Option<String>, example = "**** OA2312")] pub bank_code: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum GiftCardAdditionalData { Givex(Box<GivexGiftCardAdditionalData>), PaySafeCard {}, BhnCardNetwork {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GivexGiftCardAdditionalData { /// Last 4 digits of the gift card number #[schema(value_type = String, example = "4242")] pub last4: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardTokenAdditionalData { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiAdditionalData { UpiCollect(Box<UpiCollectAdditionalData>), #[schema(value_type = UpiIntentData)] UpiIntent(Box<super::UpiIntentData>), #[schema(value_type = UpiQrData)] UpiQr(Box<super::UpiQrData>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiCollectAdditionalData { /// Masked VPA ID #[schema(value_type = Option<String>, example = "ab********@okhdfcbank")] pub vpa_id: Option<MaskedUpiVpaId>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WalletAdditionalDataForCard { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, }
{ "crate": "api_models", "file": "crates/api_models/src/payments/additional_info.rs", "file_size": 9464, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_5873415637691101906
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/gsm.rs // File size: 8401 bytes use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmCreateRequest { /// The connector through which payment has gone through #[schema(value_type = Connector)] pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = GsmDecision)] pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: bool, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = Option<GsmFeature>)] pub feature: Option<api_enums::GsmFeature>, /// Contains the data relevant to the specified GSM feature, if applicable. /// For example, if the `feature` is `Retry`, this will include configuration /// details specific to the retry behavior. #[schema(value_type = Option<GsmFeatureData>)] pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmRetrieveRequest { /// The connector through which payment has gone through #[schema(value_type = Connector)] pub connector: api_enums::Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmUpdateRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: Option<String>, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = Option<GsmDecision>)] pub decision: Option<api_enums::GsmDecision>, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: Option<bool>, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: Option<bool>, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = Option<GsmFeature>)] pub feature: Option<api_enums::GsmFeature>, /// Contains the data relevant to the specified GSM feature, if applicable. /// For example, if the `feature` is `Retry`, this will include configuration /// details specific to the retry behavior. #[schema(value_type = Option<GsmFeatureData>)] pub feature_data: Option<common_types::domain::GsmFeatureData>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmDeleteRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct GsmDeleteResponse { pub gsm_rule_delete: bool, /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct GsmResponse { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] #[schema(value_type = GsmDecision)] pub decision: api_enums::GsmDecision, /// indicates if step_up retry is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to #[schema(value_type = Option<ErrorCategory>)] pub error_category: Option<api_enums::ErrorCategory>, /// indicates if retry with pan is possible /// **Deprecated**: This field is now included as part of `feature_data` under the `Retry` variant. #[schema(deprecated)] pub clear_pan_possible: bool, /// Indicates the GSM feature associated with the request, /// such as retry mechanisms or other specific functionalities provided by the system. #[schema(value_type = GsmFeature)] pub feature: api_enums::GsmFeature, /// Contains the data relevant to the specified GSM feature, if applicable. /// For example, if the `feature` is `Retry`, this will include configuration /// details specific to the retry behavior. #[schema(value_type = GsmFeatureData)] pub feature_data: Option<common_types::domain::GsmFeatureData>, }
{ "crate": "api_models", "file": "crates/api_models/src/gsm.rs", "file_size": 8401, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_3929838080012975590
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/webhook_events.rs // File size: 8128 bytes use std::collections::HashSet; use common_enums::{EventClass, EventType, WebhookDeliveryAttempt}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The constraints to apply when filtering events. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct EventListConstraints { /// Filter events created after the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_after: Option<PrimitiveDateTime>, /// Filter events created before the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_before: Option<PrimitiveDateTime>, /// Include at most the specified number of events. pub limit: Option<u16>, /// Include events after the specified offset. pub offset: Option<u16>, /// Filter all events associated with the specified object identifier (Payment Intent ID, /// Refund ID, etc.) pub object_id: Option<String>, /// Filter all events associated with the specified business profile ID. #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Filter events by their class. pub event_classes: Option<HashSet<EventClass>>, /// Filter events by their type. pub event_types: Option<HashSet<EventType>>, /// Filter all events by `is_overall_delivery_successful` field of the event. pub is_delivered: Option<bool>, } #[derive(Debug)] pub enum EventListConstraintsInternal { GenericFilter { created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, limit: Option<i64>, offset: Option<i64>, event_classes: Option<HashSet<EventClass>>, event_types: Option<HashSet<EventType>>, is_delivered: Option<bool>, }, ObjectIdFilter { object_id: String, }, } /// The response body for each item when listing events. #[derive(Debug, Serialize, ToSchema)] pub struct EventListItemResponse { /// The identifier for the Event. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub event_id: String, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the Business Profile. #[schema(max_length = 64, value_type = String, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")] pub profile_id: common_utils::id_type::ProfileId, /// The identifier for the object (Payment Intent ID, Refund ID, etc.) #[schema(max_length = 64, example = "QHrfd5LUDdZaKtAjdJmMu0dMa1")] pub object_id: String, /// Specifies the type of event, which includes the object and its status. pub event_type: EventType, /// Specifies the class of event (the type of object: Payment, Refund, etc.) pub event_class: EventClass, /// Indicates whether the webhook was ultimately delivered or not. pub is_delivery_successful: Option<bool>, /// The identifier for the initial delivery attempt. This will be the same as `event_id` for /// the initial delivery attempt. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub initial_attempt_id: String, /// Time at which the event was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, } /// The response body of list initial delivery attempts api call. #[derive(Debug, Serialize, ToSchema)] pub struct TotalEventsResponse { /// The list of events pub events: Vec<EventListItemResponse>, /// Count of total events pub total_count: i64, } impl TotalEventsResponse { pub fn new(total_count: i64, events: Vec<EventListItemResponse>) -> Self { Self { events, total_count, } } } impl common_utils::events::ApiEventMetric for TotalEventsResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.events.first().map(|event| event.merchant_id.clone())?, }) } } /// The response body for retrieving an event. #[derive(Debug, Serialize, ToSchema)] pub struct EventRetrieveResponse { #[serde(flatten)] pub event_information: EventListItemResponse, /// The request information (headers and body) sent in the webhook. pub request: OutgoingWebhookRequestContent, /// The response information (headers, body and status code) received for the webhook sent. pub response: OutgoingWebhookResponseContent, /// Indicates the type of delivery attempt. pub delivery_attempt: Option<WebhookDeliveryAttempt>, } impl common_utils::events::ApiEventMetric for EventRetrieveResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.event_information.merchant_id.clone(), }) } } /// The request information (headers and body) sent in the webhook. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct OutgoingWebhookRequestContent { /// The request body sent in the webhook. #[schema(value_type = String)] #[serde(alias = "payload")] pub body: Secret<String>, /// The request headers sent in the webhook. #[schema( value_type = Vec<(String, String)>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Vec<(String, Secret<String>)>, } /// The response information (headers, body and status code) received for the webhook sent. #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OutgoingWebhookResponseContent { /// The response body received for the webhook sent. #[schema(value_type = Option<String>)] #[serde(alias = "payload")] pub body: Option<Secret<String>>, /// The response headers received for the webhook sent. #[schema( value_type = Option<Vec<(String, String)>>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Option<Vec<(String, Secret<String>)>>, /// The HTTP status code for the webhook sent. #[schema(example = 200)] pub status_code: Option<u16>, /// Error message in case any error occurred when trying to deliver the webhook. #[schema(example = 200)] pub error_message: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct EventListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub constraints: EventListConstraints, } impl common_utils::events::ApiEventMetric for EventListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryAttemptListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub initial_attempt_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryRetryRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub event_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } }
{ "crate": "api_models", "file": "crates/api_models/src/webhook_events.rs", "file_size": 8128, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_api_models_-3992067522859529480
clm
file
// Repository: hyperswitch // Crate: api_models // File: crates/api_models/src/analytics/payment_intents.rs // File size: 7978 bytes use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_utils::id_type; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, }; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { #[serde(default)] pub status: Vec<IntentStatus>, #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] pub connector: Vec<Connector>, #[serde(default)] pub auth_type: Vec<AuthenticationType>, #[serde(default)] pub payment_method: Vec<PaymentMethod>, #[serde(default)] pub payment_method_type: Vec<PaymentMethodType>, #[serde(default)] pub card_network: Vec<String>, #[serde(default)] pub merchant_id: Vec<id_type::MerchantId>, #[serde(default)] pub card_last_4: Vec<String>, #[serde(default)] pub card_issuer: Vec<String>, #[serde(default)] pub error_reason: Vec<String>, #[serde(default)] pub customer_id: Vec<id_type::CustomerId>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] 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, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentIntentMetrics { SuccessfulSmartRetries, TotalSmartRetries, SmartRetriedAmount, PaymentIntentCount, PaymentsSuccessRate, PaymentProcessedAmount, SessionizedSuccessfulSmartRetries, SessionizedTotalSmartRetries, SessionizedSmartRetriedAmount, SessionizedPaymentIntentCount, SessionizedPaymentsSuccessRate, SessionizedPaymentProcessedAmount, SessionizedPaymentsDistribution, } impl ForexMetric for PaymentIntentMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::SmartRetriedAmount | Self::SessionizedPaymentProcessedAmount | Self::SessionizedSmartRetriedAmount ) } } #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, pub count: i64, pub percentage: f64, } pub mod metric_behaviour { pub struct SuccessfulSmartRetries; pub struct TotalSmartRetries; pub struct SmartRetriedAmount; pub struct PaymentIntentCount; pub struct PaymentsSuccessRate; } impl From<PaymentIntentMetrics> for NameDescription { fn from(value: PaymentIntentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<PaymentIntentDimensions> for NameDescription { fn from(value: PaymentIntentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, pub connector: Option<String>, pub auth_type: Option<AuthenticationType>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub card_network: Option<String>, pub merchant_id: Option<String>, pub card_last_4: Option<String>, pub card_issuer: Option<String>, pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl PaymentIntentMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] 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, } } } impl Hash for PaymentIntentMetricsBucketIdentifier { 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); } } impl PartialEq for PaymentIntentMetricsBucketIdentifier { 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() } } #[derive(Debug, serde::Serialize)] pub struct PaymentIntentMetricsBucketValue { pub successful_smart_retries: Option<u64>, pub total_smart_retries: Option<u64>, pub smart_retried_amount: Option<u64>, pub smart_retried_amount_in_usd: Option<u64>, pub smart_retried_amount_without_smart_retries: Option<u64>, pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub payment_intent_count: Option<u64>, pub successful_payments: Option<u32>, pub successful_payments_without_smart_retries: Option<u32>, pub total_payments: Option<u32>, pub payments_success_rate: Option<f64>, pub payments_success_rate_without_smart_retries: Option<f64>, pub payment_processed_amount: Option<u64>, pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, pub payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: PaymentIntentMetricsBucketValue, #[serde(flatten)] pub dimensions: PaymentIntentMetricsBucketIdentifier, }
{ "crate": "api_models", "file": "crates/api_models/src/analytics/payment_intents.rs", "file_size": 7978, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-1895365943880965730
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_intent.rs // File size: 85357 bytes use common_enums::{PaymentMethodType, RequestIncrementalAuthorization}; use common_types::primitive_wrappers::{ EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool, }; use common_utils::{encryption::Encryption, pii, types::MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::payment_intent; #[cfg(feature = "v2")] use crate::schema_v2::payment_intent; #[cfg(feature = "v2")] use crate::types::{FeatureMetadata, OrderDetailsWithAmount}; #[cfg(feature = "v2")] use crate::RequiredFromNullable; use crate::{business_profile::PaymentLinkBackgroundImageConfig, enums as storage_enums}; #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, #[diesel(deserialize_as = RequiredFromNullable<storage_enums::Currency>)] pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, #[diesel(deserialize_as = RequiredFromNullable<common_utils::id_type::ProfileId>)] pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[diesel(deserialize_as = RequiredFromNullable<PrimitiveDateTime>)] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub customer_present: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub id: common_utils::id_type::GlobalPaymentId, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub active_attempts_group_id: Option<String>, pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentLinkConfigRequestForPayments { /// custom theme for the payment link pub theme: Option<String>, /// merchant display logo pub logo: Option<String>, /// Custom merchant name for payment link pub seller_name: Option<String>, /// Custom layout for sdk pub sdk_layout: Option<String>, /// Display only the sdk for payment link pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<std::collections::HashMap<String, std::collections::HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, /// Optional header for the SDK's payment form pub payment_form_header_text: Option<String>, /// Label type in the SDK's payment form pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, /// Hex color for the CVC icon during error state pub color_icon_card_cvc_error: Option<String>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkConfigRequestForPayments); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details pub key: String, /// Value for the transaction details pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } common_utils::impl_to_sql_from_sql_json!(PaymentLinkTransactionDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI pub position: Option<i8>, /// Whether the key should be bold pub is_key_bold: Option<bool>, /// Whether the value should be bold pub is_value_bold: Option<bool>, } common_utils::impl_to_sql_from_sql_json!(TransactionDetailsUiConfiguration); #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct TaxDetails { /// This is the tax related information that is calculated irrespective of any payment method. /// This is calculated when the order is created with shipping details pub default: Option<DefaultTax>, /// This is the tax related information that is calculated based on the payment method /// This is calculated when calling the /calculate_tax API pub payment_method_type: Option<PaymentMethodTypeTax>, } impl TaxDetails { /// Get the tax amount /// If default tax is present, return the default tax amount /// If default tax is not present, return the tax amount based on the payment method if it matches the provided payment method type pub fn get_tax_amount(&self, payment_method: Option<PaymentMethodType>) -> Option<MinorUnit> { self.payment_method_type .as_ref() .zip(payment_method) .filter(|(payment_method_type_tax, payment_method)| { payment_method_type_tax.pmt == *payment_method }) .map(|(payment_method_type_tax, _)| payment_method_type_tax.order_tax_amount) .or_else(|| self.get_default_tax_amount()) } /// Get the default tax amount pub fn get_default_tax_amount(&self) -> Option<MinorUnit> { self.default .as_ref() .map(|default_tax_details| default_tax_details.order_tax_amount) } } common_utils::impl_to_sql_from_sql_json!(TaxDetails); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentMethodTypeTax { pub order_tax_amount: MinorUnit, pub pmt: PaymentMethodType, } #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultTax { pub order_tax_amount: MinorUnit, } #[cfg(feature = "v2")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::GlobalCustomerId>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub metadata: Option<pii::SecretSerdeValue>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>, #[diesel(deserialize_as = super::OptionalDieselArray<masking::Secret<OrderDetailsWithAmount>>)] pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub attempt_count: i16, pub profile_id: common_utils::id_type::ProfileId, pub payment_link_id: Option<String>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub capture_method: Option<storage_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<serde_json::Value>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub mit_category: Option<storage_enums::MitCategory>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_intent)] pub struct PaymentIntentNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<serde_json::Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<serde_json::Value>, pub connector_metadata: Option<serde_json::Value>, pub feature_metadata: Option<serde_json::Value>, pub attempt_count: i16, pub profile_id: Option<common_utils::id_type::ProfileId>, pub merchant_decision: Option<String>, pub payment_link_id: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub charges: Option<pii::SecretSerdeValue>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub shipping_cost: Option<MinorUnit>, pub organization_id: common_utils::id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub mit_category: Option<storage_enums::MitCategory>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { /// Update the payment intent details on payment intent confirmation, before calling the connector ConfirmIntent { status: storage_enums::IntentStatus, active_attempt_id: common_utils::id_type::GlobalAttemptId, updated_by: String, }, /// Update the payment intent details on payment intent confirmation, after calling the connector ConfirmIntentPostUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PaymentIntentUpdate { ResponseUpdate { status: storage_enums::IntentStatus, amount_captured: Option<MinorUnit>, fingerprint_id: Option<String>, updated_by: String, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<masking::Secret<serde_json::Value>>, }, MetadataUpdate { metadata: serde_json::Value, updated_by: String, }, Update(Box<PaymentIntentUpdateFields>), PaymentCreateUpdate { return_url: Option<String>, status: Option<storage_enums::IntentStatus>, customer_id: Option<common_utils::id_type::CustomerId>, shipping_address_id: Option<String>, billing_address_id: Option<String>, customer_details: Option<Encryption>, updated_by: String, }, MerchantStatusUpdate { status: storage_enums::IntentStatus, shipping_address_id: Option<String>, billing_address_id: Option<String>, updated_by: String, }, PGStatusUpdate { status: storage_enums::IntentStatus, updated_by: String, incremental_authorization_allowed: Option<bool>, feature_metadata: Option<masking::Secret<serde_json::Value>>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, attempt_count: i16, updated_by: String, }, StatusAndAttemptUpdate { status: storage_enums::IntentStatus, active_attempt_id: String, attempt_count: i16, updated_by: String, }, ApproveUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, RejectUpdate { status: storage_enums::IntentStatus, merchant_decision: Option<String>, updated_by: String, }, SurchargeApplicableUpdate { surcharge_applicable: Option<bool>, updated_by: String, }, IncrementalAuthorizationAmountUpdate { amount: MinorUnit, }, AuthorizationCountUpdate { authorization_count: i32, }, CompleteAuthorizeUpdate { shipping_address_id: Option<String>, }, ManualUpdate { status: Option<storage_enums::IntentStatus>, updated_by: String, }, SessionResponseUpdate { tax_details: TaxDetails, shipping_address_id: Option<String>, updated_by: String, shipping_details: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address: Option<Encryption>, pub billing_address: Option<Encryption>, pub return_url: Option<String>, pub description: Option<String>, pub statement_descriptor: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub is_payment_processor_token_flow: Option<bool>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<Option<common_enums::PaymentChannel>>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaymentIntentUpdateFields { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub status: storage_enums::IntentStatus, pub customer_id: Option<common_utils::id_type::CustomerId>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub return_url: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<serde_json::Value>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub status: Option<storage_enums::IntentStatus>, pub prerouting_algorithm: Option<serde_json::Value>, pub amount_captured: Option<MinorUnit>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<Option<common_utils::id_type::GlobalAttemptId>>, pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub shipping_cost: Option<MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub surcharge_applicable: Option<bool>, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub capture_method: Option<common_enums::CaptureMethod>, pub authentication_type: Option<common_enums::AuthenticationType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub customer_present: Option<bool>, pub description: Option<common_utils::types::Description>, pub return_url: Option<common_utils::types::Url>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub apply_mit_exemption: Option<bool>, pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_metadata: Option<pii::SecretSerdeValue>, pub feature_metadata: Option<FeatureMetadata>, pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>, pub request_incremental_authorization: Option<RequestIncrementalAuthorization>, pub session_expiry: Option<PrimitiveDateTime>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub request_external_three_ds_authentication: Option<bool>, pub updated_by: String, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentIntentUpdateInternal { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let Self { status, prerouting_algorithm, amount_captured, modified_at: _, // This will be ignored from self active_attempt_id, amount, currency, shipping_cost, tax_details, skip_external_tax_calculation, surcharge_applicable, surcharge_amount, tax_on_surcharge, routing_algorithm_id, capture_method, authentication_type, billing_address, shipping_address, customer_present, description, return_url, setup_future_usage, apply_mit_exemption, statement_descriptor, order_details, allowed_payment_method_types, metadata, connector_metadata, feature_metadata, payment_link_config, request_incremental_authorization, session_expiry, frm_metadata, request_external_three_ds_authentication, updated_by, force_3ds_challenge, is_iframe_redirection_enabled, enable_partial_authorization, } = self; PaymentIntent { status: status.unwrap_or(source.status), prerouting_algorithm: prerouting_algorithm.or(source.prerouting_algorithm), amount_captured: amount_captured.or(source.amount_captured), modified_at: common_utils::date_time::now(), active_attempt_id: match active_attempt_id { Some(v_option) => v_option, None => source.active_attempt_id, }, amount: amount.unwrap_or(source.amount), currency: currency.unwrap_or(source.currency), shipping_cost: shipping_cost.or(source.shipping_cost), tax_details: tax_details.or(source.tax_details), skip_external_tax_calculation: skip_external_tax_calculation .or(source.skip_external_tax_calculation), surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), surcharge_amount: surcharge_amount.or(source.surcharge_amount), tax_on_surcharge: tax_on_surcharge.or(source.tax_on_surcharge), routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), capture_method: capture_method.or(source.capture_method), authentication_type: authentication_type.or(source.authentication_type), billing_address: billing_address.or(source.billing_address), shipping_address: shipping_address.or(source.shipping_address), customer_present: customer_present.or(source.customer_present), description: description.or(source.description), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), apply_mit_exemption: apply_mit_exemption.or(source.apply_mit_exemption), statement_descriptor: statement_descriptor.or(source.statement_descriptor), order_details: order_details.or(source.order_details), allowed_payment_method_types: allowed_payment_method_types .or(source.allowed_payment_method_types), metadata: metadata.or(source.metadata), connector_metadata: connector_metadata.or(source.connector_metadata), feature_metadata: feature_metadata.or(source.feature_metadata), payment_link_config: payment_link_config.or(source.payment_link_config), request_incremental_authorization: request_incremental_authorization .or(source.request_incremental_authorization), session_expiry: session_expiry.unwrap_or(source.session_expiry), frm_metadata: frm_metadata.or(source.frm_metadata), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), updated_by, force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), // Fields from source merchant_id: source.merchant_id, customer_id: source.customer_id, created_at: source.created_at, last_synced: source.last_synced, attempt_count: source.attempt_count, profile_id: source.profile_id, payment_link_id: source.payment_link_id, authorization_count: source.authorization_count, customer_details: source.customer_details, organization_id: source.organization_id, request_extended_authorization: source.request_extended_authorization, psd2_sca_exemption_type: source.psd2_sca_exemption_type, split_payments: source.split_payments, platform_merchant_id: source.platform_merchant_id, force_3ds_challenge_trigger: source.force_3ds_challenge_trigger, processor_merchant_id: source.processor_merchant_id, created_by: source.created_by, merchant_reference_id: source.merchant_reference_id, frm_merchant_decision: source.frm_merchant_decision, enable_payment_link: source.enable_payment_link, id: source.id, is_payment_id_from_merchant: source.is_payment_id_from_merchant, payment_channel: source.payment_channel, tax_status: source.tax_status, discount_amount: source.discount_amount, shipping_amount_tax: source.shipping_amount_tax, duty_amount: source.duty_amount, order_date: source.order_date, enable_partial_authorization: source.enable_partial_authorization, split_txns_enabled: source.split_txns_enabled, enable_overcapture: None, active_attempt_id_type: source.active_attempt_id_type, active_attempts_group_id: source.active_attempts_group_id, mit_category: None, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payment_intent)] pub struct PaymentIntentUpdateInternal { pub amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::IntentStatus>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub return_url: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub metadata: Option<serde_json::Value>, pub billing_address_id: Option<String>, pub shipping_address_id: Option<String>, pub modified_at: PrimitiveDateTime, pub active_attempt_id: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub description: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub attempt_count: Option<i16>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, pub fingerprint_id: Option<String>, pub request_external_three_ds_authentication: Option<bool>, pub frm_metadata: Option<pii::SecretSerdeValue>, pub customer_details: Option<Encryption>, pub billing_details: Option<Encryption>, pub merchant_order_reference_id: Option<String>, pub shipping_details: Option<Encryption>, pub is_payment_processor_token_flow: Option<bool>, pub tax_details: Option<TaxDetails>, pub force_3ds_challenge: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub extended_return_url: Option<String>, pub payment_channel: Option<common_enums::PaymentChannel>, pub feature_metadata: Option<masking::Secret<serde_json::Value>>, pub tax_status: Option<common_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, } #[cfg(feature = "v1")] impl PaymentIntentUpdate { pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent { let PaymentIntentUpdateInternal { amount, currency, status, amount_captured, customer_id, return_url, setup_future_usage, off_session, metadata, billing_address_id, shipping_address_id, modified_at: _, active_attempt_id, business_country, business_label, description, statement_descriptor_name, statement_descriptor_suffix, order_details, attempt_count, merchant_decision, payment_confirm_source, updated_by, surcharge_applicable, incremental_authorization_allowed, authorization_count, session_expiry, fingerprint_id, request_external_three_ds_authentication, frm_metadata, customer_details, billing_details, merchant_order_reference_id, shipping_details, is_payment_processor_token_flow, tax_details, force_3ds_challenge, is_iframe_redirection_enabled, extended_return_url, payment_channel, feature_metadata, tax_status, discount_amount, order_date, shipping_amount_tax, duty_amount, enable_partial_authorization, enable_overcapture, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), currency: currency.or(source.currency), status: status.unwrap_or(source.status), amount_captured: amount_captured.or(source.amount_captured), customer_id: customer_id.or(source.customer_id), return_url: return_url.or(source.return_url), setup_future_usage: setup_future_usage.or(source.setup_future_usage), off_session: off_session.or(source.off_session), metadata: metadata.or(source.metadata), billing_address_id: billing_address_id.or(source.billing_address_id), shipping_address_id: shipping_address_id.or(source.shipping_address_id), modified_at: common_utils::date_time::now(), active_attempt_id: active_attempt_id.unwrap_or(source.active_attempt_id), business_country: business_country.or(source.business_country), business_label: business_label.or(source.business_label), description: description.or(source.description), statement_descriptor_name: statement_descriptor_name .or(source.statement_descriptor_name), statement_descriptor_suffix: statement_descriptor_suffix .or(source.statement_descriptor_suffix), order_details: order_details.or(source.order_details), attempt_count: attempt_count.unwrap_or(source.attempt_count), merchant_decision: merchant_decision.or(source.merchant_decision), payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), request_external_three_ds_authentication: request_external_three_ds_authentication .or(source.request_external_three_ds_authentication), frm_metadata: frm_metadata.or(source.frm_metadata), customer_details: customer_details.or(source.customer_details), billing_details: billing_details.or(source.billing_details), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), shipping_details: shipping_details.or(source.shipping_details), is_payment_processor_token_flow: is_payment_processor_token_flow .or(source.is_payment_processor_token_flow), tax_details: tax_details.or(source.tax_details), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), extended_return_url: extended_return_url.or(source.extended_return_url), payment_channel: payment_channel.or(source.payment_channel), feature_metadata: feature_metadata .map(|value| value.expose()) .or(source.feature_metadata), tax_status: tax_status.or(source.tax_status), discount_amount: discount_amount.or(source.discount_amount), order_date: order_date.or(source.order_date), shipping_amount_tax: shipping_amount_tax.or(source.shipping_amount_tax), duty_amount: duty_amount.or(source.duty_amount), enable_partial_authorization: enable_partial_authorization .or(source.enable_partial_authorization), enable_overcapture: enable_overcapture.or(source.enable_overcapture), ..source } } } #[cfg(feature = "v1")] impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { fn from(payment_intent_update: PaymentIntentUpdate) -> Self { match payment_intent_update { PaymentIntentUpdate::MetadataUpdate { metadata, updated_by, } => Self { metadata: Some(metadata), modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::Update(value) => Self { amount: Some(value.amount), currency: Some(value.currency), setup_future_usage: value.setup_future_usage, status: Some(value.status), customer_id: value.customer_id, shipping_address_id: value.shipping_address_id, billing_address_id: value.billing_address_id, return_url: None, // deprecated business_country: value.business_country, business_label: value.business_label, description: value.description, statement_descriptor_name: value.statement_descriptor_name, statement_descriptor_suffix: value.statement_descriptor_suffix, order_details: value.order_details, metadata: value.metadata, payment_confirm_source: value.payment_confirm_source, updated_by: value.updated_by, session_expiry: value.session_expiry, fingerprint_id: value.fingerprint_id, request_external_three_ds_authentication: value .request_external_three_ds_authentication, frm_metadata: value.frm_metadata, customer_details: value.customer_details, billing_details: value.billing_details, merchant_order_reference_id: value.merchant_order_reference_id, shipping_details: value.shipping_details, amount_captured: None, off_session: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, attempt_count: None, merchant_decision: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, is_payment_processor_token_flow: value.is_payment_processor_token_flow, tax_details: None, force_3ds_challenge: value.force_3ds_challenge, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, extended_return_url: value.return_url, payment_channel: value.payment_channel, feature_metadata: value.feature_metadata, tax_status: value.tax_status, discount_amount: value.discount_amount, order_date: value.order_date, shipping_amount_tax: value.shipping_amount_tax, duty_amount: value.duty_amount, enable_partial_authorization: value.enable_partial_authorization, enable_overcapture: value.enable_overcapture, }, PaymentIntentUpdate::PaymentCreateUpdate { return_url, status, customer_id, shipping_address_id, billing_address_id, customer_details, updated_by, } => Self { return_url: None, // deprecated status, customer_id, shipping_address_id, billing_address_id, customer_details, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: return_url, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::PGStatusUpdate { status, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { status: Some(status), modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::MerchantStatusUpdate { status, shipping_address_id, billing_address_id, updated_by, } => Self { status: Some(status), shipping_address_id, billing_address_id, modified_at: common_utils::date_time::now(), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ResponseUpdate { // amount, // currency, status, amount_captured, fingerprint_id, // customer_id, updated_by, incremental_authorization_allowed, feature_metadata, } => Self { // amount, // currency: Some(currency), status: Some(status), amount_captured, fingerprint_id, // customer_id, return_url: None, modified_at: common_utils::date_time::now(), updated_by, incremental_authorization_allowed, amount: None, currency: None, customer_id: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, authorization_count: None, session_expiry: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate { active_attempt_id, attempt_count, updated_by, } => Self { active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::StatusAndAttemptUpdate { status, active_attempt_id, attempt_count, updated_by, } => Self { status: Some(status), active_attempt_id: Some(active_attempt_id), attempt_count: Some(attempt_count), updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ApproveUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::RejectUpdate { status, merchant_decision, updated_by, } => Self { status: Some(status), merchant_decision, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::SurchargeApplicableUpdate { surcharge_applicable, updated_by, } => Self { surcharge_applicable, updated_by, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self { amount: Some(amount), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::AuthorizationCountUpdate { authorization_count, } => Self { authorization_count: Some(authorization_count), amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id, } => Self { shipping_address_id, amount: None, currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by: String::default(), surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self { status, updated_by, amount: None, currency: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, shipping_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details: None, is_payment_processor_token_flow: None, tax_details: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, PaymentIntentUpdate::SessionResponseUpdate { tax_details, shipping_address_id, updated_by, shipping_details, } => Self { shipping_address_id, amount: None, tax_details: Some(tax_details), currency: None, status: None, amount_captured: None, customer_id: None, return_url: None, setup_future_usage: None, off_session: None, metadata: None, billing_address_id: None, modified_at: common_utils::date_time::now(), active_attempt_id: None, business_country: None, business_label: None, description: None, statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: None, attempt_count: None, merchant_decision: None, payment_confirm_source: None, updated_by, surcharge_applicable: None, incremental_authorization_allowed: None, authorization_count: None, session_expiry: None, fingerprint_id: None, request_external_three_ds_authentication: None, frm_metadata: None, customer_details: None, billing_details: None, merchant_order_reference_id: None, shipping_details, is_payment_processor_token_flow: None, force_3ds_challenge: None, is_iframe_redirection_enabled: None, extended_return_url: None, payment_channel: None, feature_metadata: None, tax_status: None, discount_amount: None, order_date: None, shipping_amount_tax: None, duty_amount: None, enable_partial_authorization: None, enable_overcapture: None, }, } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", "amount": 10000, "currency": "USD", "amount_captured": null, "customer_id": "cust_123456", "description": "Test Payment", "return_url": "https://example.com/return", "metadata": null, "connector_id": "connector_001", "shipping_address_id": null, "billing_address_id": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "created_at": "2024-02-01T12:00:00Z", "modified_at": "2024-02-01T12:00:00Z", "last_synced": null, "setup_future_usage": null, "off_session": null, "client_secret": "sec_abcdef1234567890", "active_attempt_id": "attempt_123", "business_country": "US", "business_label": null, "order_details": null, "allowed_payment_method_types": "credit", "connector_metadata": null, "feature_metadata": null, "attempt_count": 1, "profile_id": null, "merchant_decision": null, "payment_link_id": null, "payment_confirm_source": null, "updated_by": "admin", "surcharge_applicable": null, "request_incremental_authorization": null, "incremental_authorization_allowed": null, "authorization_count": null, "session_expiry": null, "fingerprint_id": null, "frm_metadata": null }"#; let deserialized_payment_intent = serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent); assert!(deserialized_payment_intent.is_ok()); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_intent.rs", "file_size": 85357, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_6082001395469778501
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/schema.rs // File size: 57674 bytes // @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, origin_zip -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 128] authentication_client_secret -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, #[max_length = 2048] return_url -> Nullable<Varchar>, amount -> Nullable<Int8>, currency -> Nullable<Currency>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, browser_info -> Nullable<Jsonb>, email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, challenge_code -> Nullable<Varchar>, challenge_cancel -> Nullable<Varchar>, challenge_code_reason -> Nullable<Varchar>, message_extension -> Nullable<Jsonb>, #[max_length = 255] challenge_request_key -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (merchant_id, fingerprint) { #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (profile_id) { #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, routing_algorithm -> Nullable<Json>, intent_fulfillment_time -> Nullable<Int8>, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, is_pre_network_tokenization_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, #[max_length = 16] merchant_category_code -> Nullable<Varchar>, #[max_length = 32] merchant_country_code -> Nullable<Varchar>, dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, #[max_length = 64] billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, is_l2_l3_enabled -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, #[max_length = 512] connector_capture_data -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (customer_id, merchant_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, tax_registration_id -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, feature_data -> Nullable<Jsonb>, #[max_length = 64] feature -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction_default (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; invoice (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] subscription_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] payment_intent_id -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, #[max_length = 64] customer_id -> Varchar, amount -> Int8, #[max_length = 3] currency -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 128] provider_name -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] connector_invoice_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (card_id) { #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, #[max_length = 2048] customer_user_agent_extended -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (merchant_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 255] return_url -> Nullable<Varchar>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, webhook_details -> Nullable<Json>, sub_merchants_enabled -> Nullable<Bool>, #[max_length = 64] parent_merchant_id -> Nullable<Varchar>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, #[max_length = 64] locker_id -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, routing_algorithm -> Nullable<Json>, primary_business_details -> Json, intent_fulfillment_time -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, frm_routing_algorithm -> Nullable<Jsonb>, payout_routing_algorithm -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, is_recon_enabled -> Bool, #[max_length = 64] default_profile -> Nullable<Varchar>, recon_status -> ReconStatus, payment_link_config -> Nullable<Jsonb>, pm_collect_link_config -> Nullable<Jsonb>, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Nullable<Varchar>, #[max_length = 64] product_type -> Nullable<Varchar>, #[max_length = 64] merchant_account_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (merchant_connector_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, test_mode -> Nullable<Bool>, disabled -> Nullable<Bool>, #[max_length = 128] merchant_connector_id -> Varchar, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 255] business_label -> Nullable<Varchar>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, frm_configs -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (org_id) { #[max_length = 32] org_id -> Varchar, org_name -> Nullable<Text>, organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Nullable<Varchar>, organization_name -> Nullable<Text>, version -> ApiVersion, #[max_length = 64] organization_type -> Nullable<Varchar>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, status -> AttemptStatus, amount -> Int8, currency -> Nullable<Currency>, save_to_locker -> Nullable<Bool>, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, offer_amount -> Nullable<Int8>, surcharge_amount -> Nullable<Int8>, tax_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, payment_method -> Nullable<Varchar>, #[max_length = 128] connector_transaction_id -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, capture_on -> Nullable<Timestamp>, confirm -> Bool, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, #[max_length = 64] mandate_id -> Nullable<Varchar>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, #[max_length = 64] business_sub_label -> Nullable<Varchar>, straight_through_algorithm -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, mandate_details -> Nullable<Jsonb>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, authentication_data -> Nullable<Json>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, mandate_data -> Nullable<Jsonb>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_billing_address_id -> Nullable<Varchar>, #[max_length = 64] charge_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, connector_mandate_detail -> Nullable<Jsonb>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, setup_future_usage_applied -> Nullable<FutureUsage>, routing_approach -> Nullable<RoutingApproach>, #[max_length = 255] connector_request_reference_id -> Nullable<Varchar>, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, is_stored_credential -> Nullable<Bool>, authorized_amount -> Nullable<Int8>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (payment_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, #[max_length = 64] connector_id -> Nullable<Varchar>, #[max_length = 64] shipping_address_id -> Nullable<Varchar>, #[max_length = 64] billing_address_id -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_name -> Nullable<Varchar>, #[max_length = 255] statement_descriptor_suffix -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, off_session -> Nullable<Bool>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 64] active_attempt_id -> Varchar, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] merchant_decision -> Nullable<Varchar>, #[max_length = 255] payment_link_id -> Nullable<Varchar>, payment_confirm_source -> Nullable<PaymentSource>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, incremental_authorization_allowed -> Nullable<Bool>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, request_external_three_ds_authentication -> Nullable<Bool>, charges -> Nullable<Jsonb>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, billing_details -> Nullable<Bytea>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, shipping_details -> Nullable<Bytea>, is_payment_processor_token_flow -> Nullable<Bool>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, #[max_length = 2048] extended_return_url -> Nullable<Varchar>, is_payment_id_from_merchant -> Nullable<Bool>, #[max_length = 64] payment_channel -> Nullable<Varchar>, tax_status -> Nullable<Varchar>, discount_amount -> Nullable<Int8>, shipping_amount_tax -> Nullable<Int8>, duty_amount -> Nullable<Int8>, order_date -> Nullable<Timestamp>, enable_partial_authorization -> Nullable<Bool>, enable_overcapture -> Nullable<Bool>, #[max_length = 64] mit_category -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (payment_method_id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, accepted_currency -> Nullable<Array<Nullable<Currency>>>, #[max_length = 32] scheme -> Nullable<Varchar>, #[max_length = 128] token -> Nullable<Varchar>, #[max_length = 255] cardholder_name -> Nullable<Varchar>, #[max_length = 64] issuer_name -> Nullable<Varchar>, #[max_length = 64] issuer_country -> Nullable<Varchar>, payer_country -> Nullable<Array<Nullable<Text>>>, is_stored -> Nullable<Bool>, #[max_length = 32] swift_code -> Nullable<Varchar>, #[max_length = 128] direct_debit_token -> Nullable<Varchar>, created_at -> Timestamp, last_modified -> Timestamp, payment_method -> Nullable<Varchar>, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 128] payment_method_issuer -> Nullable<Varchar>, payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>, metadata -> Nullable<Json>, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] external_vault_source -> Nullable<Varchar>, #[max_length = 64] vault_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (merchant_id, payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, payout_connector_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (merchant_id, payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (merchant_id, refund_id) { #[max_length = 64] internal_reference_id -> Varchar, #[max_length = 64] refund_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 512] connector_refund_data -> Nullable<Varchar>, #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] issuer_error_code -> Nullable<Varchar>, issuer_error_message -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, #[max_length = 64] decision_engine_routing_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; subscription (id) { #[max_length = 128] id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] billing_processor -> Nullable<Varchar>, #[max_length = 128] payment_method_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 128] connector_subscription_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_reference_id -> Nullable<Varchar>, #[max_length = 128] plan_id -> Nullable<Varchar>, #[max_length = 128] item_price_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, lineage_context -> Nullable<Jsonb>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, invoice, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, subscription, themes, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
{ "crate": "diesel_models", "file": "crates/diesel_models/src/schema.rs", "file_size": 57674, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-8785310203052131258
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/schema_v2.rs // File size: 55547 bytes // @generated automatically by Diesel CLI. diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; address (address_id) { #[max_length = 64] address_id -> Varchar, #[max_length = 128] city -> Nullable<Varchar>, country -> Nullable<CountryAlpha2>, line1 -> Nullable<Bytea>, line2 -> Nullable<Bytea>, line3 -> Nullable<Bytea>, state -> Nullable<Bytea>, zip -> Nullable<Bytea>, first_name -> Nullable<Bytea>, last_name -> Nullable<Bytea>, phone_number -> Nullable<Bytea>, #[max_length = 8] country_code -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, email -> Nullable<Bytea>, origin_zip -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; api_keys (key_id) { #[max_length = 64] key_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, #[max_length = 128] hashed_api_key -> Varchar, #[max_length = 16] prefix -> Varchar, created_at -> Timestamp, expires_at -> Nullable<Timestamp>, last_used -> Nullable<Timestamp>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; authentication (authentication_id) { #[max_length = 64] authentication_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] connector_authentication_id -> Nullable<Varchar>, authentication_data -> Nullable<Jsonb>, #[max_length = 64] payment_method_id -> Varchar, #[max_length = 64] authentication_type -> Nullable<Varchar>, #[max_length = 64] authentication_status -> Varchar, #[max_length = 64] authentication_lifecycle_status -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, maximum_supported_version -> Nullable<Jsonb>, #[max_length = 64] threeds_server_transaction_id -> Nullable<Varchar>, #[max_length = 64] cavv -> Nullable<Varchar>, #[max_length = 64] authentication_flow_type -> Nullable<Varchar>, message_version -> Nullable<Jsonb>, #[max_length = 64] eci -> Nullable<Varchar>, #[max_length = 64] trans_status -> Nullable<Varchar>, #[max_length = 64] acquirer_bin -> Nullable<Varchar>, #[max_length = 64] acquirer_merchant_id -> Nullable<Varchar>, three_ds_method_data -> Nullable<Varchar>, three_ds_method_url -> Nullable<Varchar>, acs_url -> Nullable<Varchar>, challenge_request -> Nullable<Varchar>, acs_reference_number -> Nullable<Varchar>, acs_trans_id -> Nullable<Varchar>, acs_signed_content -> Nullable<Varchar>, #[max_length = 64] profile_id -> Varchar, #[max_length = 255] payment_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] ds_trans_id -> Nullable<Varchar>, #[max_length = 128] directory_server_id -> Nullable<Varchar>, #[max_length = 64] acquirer_country_code -> Nullable<Varchar>, service_details -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, #[max_length = 128] authentication_client_secret -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, #[max_length = 2048] return_url -> Nullable<Varchar>, amount -> Nullable<Int8>, currency -> Nullable<Currency>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, browser_info -> Nullable<Jsonb>, email -> Nullable<Bytea>, #[max_length = 128] profile_acquirer_id -> Nullable<Varchar>, challenge_code -> Nullable<Varchar>, challenge_cancel -> Nullable<Varchar>, challenge_code_reason -> Nullable<Varchar>, message_extension -> Nullable<Jsonb>, #[max_length = 255] challenge_request_key -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, metadata -> Nullable<Jsonb>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_fingerprint (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] fingerprint_id -> Varchar, data_kind -> BlocklistDataKind, encrypted_fingerprint -> Text, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; blocklist_lookup (id) { id -> Int4, #[max_length = 64] merchant_id -> Varchar, fingerprint -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; business_profile (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_name -> Varchar, created_at -> Timestamp, modified_at -> Timestamp, return_url -> Nullable<Text>, enable_payment_response_hash -> Bool, #[max_length = 255] payment_response_hash_key -> Nullable<Varchar>, redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, session_expiry -> Nullable<Int8>, authentication_connector_details -> Nullable<Jsonb>, payout_link_config -> Nullable<Jsonb>, is_extended_card_info_enabled -> Nullable<Bool>, extended_card_info_config -> Nullable<Jsonb>, is_connector_agnostic_mit_enabled -> Nullable<Bool>, use_billing_as_payment_method_billing -> Nullable<Bool>, collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, always_collect_billing_details_from_wallet_connector -> Nullable<Bool>, always_collect_shipping_details_from_wallet_connector -> Nullable<Bool>, #[max_length = 64] tax_connector_id -> Nullable<Varchar>, is_tax_connector_enabled -> Nullable<Bool>, version -> ApiVersion, dynamic_routing_algorithm -> Nullable<Json>, is_network_tokenization_enabled -> Bool, is_auto_retries_enabled -> Nullable<Bool>, max_auto_retries_enabled -> Nullable<Int2>, always_request_extended_authorization -> Nullable<Bool>, is_click_to_pay_enabled -> Bool, authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, is_clear_pan_retries_enabled -> Bool, force_3ds_challenge -> Nullable<Bool>, is_debit_routing_enabled -> Bool, merchant_business_country -> Nullable<CountryAlpha2>, #[max_length = 64] id -> Varchar, is_iframe_redirection_enabled -> Nullable<Bool>, three_ds_decision_rule_algorithm -> Nullable<Jsonb>, acquirer_config_map -> Nullable<Jsonb>, #[max_length = 16] merchant_category_code -> Nullable<Varchar>, #[max_length = 32] merchant_country_code -> Nullable<Varchar>, dispute_polling_interval -> Nullable<Int4>, is_manual_retry_enabled -> Nullable<Bool>, always_enable_overcapture -> Nullable<Bool>, #[max_length = 64] billing_processor_id -> Nullable<Varchar>, is_external_vault_enabled -> Nullable<Bool>, external_vault_connector_details -> Nullable<Jsonb>, is_l2_l3_enabled -> Nullable<Bool>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>, #[max_length = 64] frm_routing_algorithm_id -> Nullable<Varchar>, #[max_length = 64] payout_routing_algorithm_id -> Nullable<Varchar>, default_fallback_routing -> Nullable<Jsonb>, three_ds_decision_manager_config -> Nullable<Jsonb>, should_collect_cvv_during_payment -> Nullable<Bool>, revenue_recovery_retry_algorithm_type -> Nullable<RevenueRecoveryAlgorithmType>, revenue_recovery_retry_algorithm_data -> Nullable<Jsonb>, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; callback_mapper (id, type_) { #[max_length = 128] id -> Varchar, #[sql_name = "type"] #[max_length = 64] type_ -> Varchar, data -> Jsonb, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; captures (capture_id) { #[max_length = 64] capture_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> CaptureStatus, amount -> Int8, currency -> Nullable<Currency>, #[max_length = 255] connector -> Varchar, #[max_length = 255] error_message -> Nullable<Varchar>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 255] error_reason -> Nullable<Varchar>, tax_amount -> Nullable<Int8>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] authorized_attempt_id -> Varchar, #[max_length = 128] connector_capture_id -> Nullable<Varchar>, capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, processor_capture_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; cards_info (card_iin) { #[max_length = 16] card_iin -> Varchar, card_issuer -> Nullable<Text>, card_network -> Nullable<Text>, card_type -> Nullable<Text>, card_subtype -> Nullable<Text>, card_issuing_country -> Nullable<Text>, #[max_length = 32] bank_code_id -> Nullable<Varchar>, #[max_length = 32] bank_code -> Nullable<Varchar>, #[max_length = 32] country_code -> Nullable<Varchar>, date_created -> Timestamp, last_updated -> Nullable<Timestamp>, last_updated_provider -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; configs (key) { id -> Int4, #[max_length = 255] key -> Varchar, config -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; customers (id) { #[max_length = 64] merchant_id -> Varchar, name -> Nullable<Bytea>, email -> Nullable<Bytea>, phone -> Nullable<Bytea>, #[max_length = 8] phone_country_code -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, created_at -> Timestamp, metadata -> Nullable<Json>, connector_customer -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] default_payment_method_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, tax_registration_id -> Nullable<Bytea>, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, default_billing_address -> Nullable<Bytea>, default_shipping_address -> Nullable<Bytea>, status -> Nullable<DeleteStatus>, #[max_length = 64] id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dashboard_metadata (id) { id -> Int4, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] org_id -> Varchar, data_key -> DashboardMetadata, data_value -> Json, #[max_length = 64] created_by -> Varchar, created_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dispute (dispute_id) { #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] amount -> Varchar, #[max_length = 255] currency -> Varchar, dispute_stage -> DisputeStage, dispute_status -> DisputeStatus, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] connector_status -> Varchar, #[max_length = 255] connector_dispute_id -> Varchar, #[max_length = 255] connector_reason -> Nullable<Varchar>, #[max_length = 255] connector_reason_code -> Nullable<Varchar>, challenge_required_by -> Nullable<Timestamp>, connector_created_at -> Nullable<Timestamp>, connector_updated_at -> Nullable<Timestamp>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] connector -> Varchar, evidence -> Jsonb, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, dispute_amount -> Int8, #[max_length = 32] organization_id -> Varchar, dispute_currency -> Nullable<Currency>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; dynamic_routing_stats (attempt_id, merchant_id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, amount -> Int8, #[max_length = 64] success_based_routing_connector -> Varchar, #[max_length = 64] payment_connector -> Varchar, currency -> Nullable<Currency>, #[max_length = 64] payment_method -> Nullable<Varchar>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, #[max_length = 64] global_success_based_connector -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; events (event_id) { #[max_length = 64] event_id -> Varchar, event_type -> EventType, event_class -> EventClass, is_webhook_notified -> Bool, #[max_length = 64] primary_object_id -> Varchar, primary_object_type -> EventObjectType, created_at -> Timestamp, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] business_profile_id -> Nullable<Varchar>, primary_object_created_at -> Nullable<Timestamp>, #[max_length = 64] idempotent_event_id -> Nullable<Varchar>, #[max_length = 64] initial_attempt_id -> Nullable<Varchar>, request -> Nullable<Bytea>, response -> Nullable<Bytea>, delivery_attempt -> Nullable<WebhookDeliveryAttempt>, metadata -> Nullable<Jsonb>, is_overall_delivery_successful -> Nullable<Bool>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; file_metadata (file_id, merchant_id) { #[max_length = 64] file_id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] file_name -> Nullable<Varchar>, file_size -> Int4, #[max_length = 255] file_type -> Varchar, #[max_length = 255] provider_file_id -> Nullable<Varchar>, #[max_length = 255] file_upload_provider -> Nullable<Varchar>, available -> Bool, created_at -> Timestamp, #[max_length = 255] connector_label -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; fraud_check (frm_id, attempt_id, payment_id, merchant_id) { #[max_length = 64] frm_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] attempt_id -> Varchar, created_at -> Timestamp, #[max_length = 255] frm_name -> Varchar, #[max_length = 255] frm_transaction_id -> Nullable<Varchar>, frm_transaction_type -> FraudCheckType, frm_status -> FraudCheckStatus, frm_score -> Nullable<Int4>, frm_reason -> Nullable<Jsonb>, #[max_length = 255] frm_error -> Nullable<Varchar>, payment_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, modified_at -> Timestamp, #[max_length = 64] last_step -> Varchar, payment_capture_method -> Nullable<CaptureMethod>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; gateway_status_map (connector, flow, sub_flow, code, message) { #[max_length = 64] connector -> Varchar, #[max_length = 64] flow -> Varchar, #[max_length = 64] sub_flow -> Varchar, #[max_length = 255] code -> Varchar, #[max_length = 1024] message -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 64] router_error -> Nullable<Varchar>, #[max_length = 64] decision -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, step_up_possible -> Bool, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, clear_pan_possible -> Bool, feature_data -> Nullable<Jsonb>, #[max_length = 64] feature -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; generic_link (link_id) { #[max_length = 64] link_id -> Varchar, #[max_length = 64] primary_reference -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, expiry -> Timestamp, link_data -> Jsonb, link_status -> Jsonb, link_type -> GenericLinkType, url -> Text, return_url -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; hyperswitch_ai_interaction_default (id, created_at) { #[max_length = 64] id -> Varchar, #[max_length = 64] session_id -> Nullable<Varchar>, #[max_length = 64] user_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Nullable<Varchar>, user_query -> Nullable<Bytea>, response -> Nullable<Bytea>, database_query -> Nullable<Text>, #[max_length = 64] interaction_status -> Nullable<Varchar>, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; incremental_authorization (authorization_id, merchant_id) { #[max_length = 64] authorization_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_id -> Varchar, amount -> Int8, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] status -> Varchar, #[max_length = 255] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, #[max_length = 64] connector_authorization_id -> Nullable<Varchar>, previously_authorized_amount -> Int8, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; invoice (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] subscription_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_connector_id -> Varchar, #[max_length = 64] payment_intent_id -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, #[max_length = 64] customer_id -> Varchar, amount -> Int8, #[max_length = 3] currency -> Varchar, #[max_length = 64] status -> Varchar, #[max_length = 128] provider_name -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] connector_invoice_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; locker_mock_up (id) { id -> Int4, #[max_length = 255] card_id -> Varchar, #[max_length = 255] external_id -> Varchar, #[max_length = 255] card_fingerprint -> Varchar, #[max_length = 255] card_global_fingerprint -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 255] card_number -> Varchar, #[max_length = 255] card_exp_year -> Varchar, #[max_length = 255] card_exp_month -> Varchar, #[max_length = 255] name_on_card -> Nullable<Varchar>, #[max_length = 255] nickname -> Nullable<Varchar>, #[max_length = 255] customer_id -> Nullable<Varchar>, duplicate -> Nullable<Bool>, #[max_length = 8] card_cvc -> Nullable<Varchar>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, enc_card_data -> Nullable<Text>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; mandate (mandate_id) { #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] payment_method_id -> Varchar, mandate_status -> MandateStatus, mandate_type -> MandateType, customer_accepted_at -> Nullable<Timestamp>, #[max_length = 64] customer_ip_address -> Nullable<Varchar>, #[max_length = 255] customer_user_agent -> Nullable<Varchar>, #[max_length = 128] network_transaction_id -> Nullable<Varchar>, #[max_length = 64] previous_attempt_id -> Nullable<Varchar>, created_at -> Timestamp, mandate_amount -> Nullable<Int8>, mandate_currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_mandate_id -> Nullable<Varchar>, start_date -> Nullable<Timestamp>, end_date -> Nullable<Timestamp>, metadata -> Nullable<Jsonb>, connector_mandate_ids -> Nullable<Jsonb>, #[max_length = 64] original_payment_id -> Nullable<Varchar>, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, #[max_length = 64] updated_by -> Nullable<Varchar>, #[max_length = 2048] customer_user_agent_extended -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_account (id) { merchant_name -> Nullable<Bytea>, merchant_details -> Nullable<Bytea>, #[max_length = 128] publishable_key -> Nullable<Varchar>, storage_scheme -> MerchantStorageScheme, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] organization_id -> Varchar, recon_status -> ReconStatus, version -> ApiVersion, is_platform_account -> Bool, #[max_length = 64] id -> Varchar, #[max_length = 64] product_type -> Nullable<Varchar>, #[max_length = 64] merchant_account_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_connector_account (id) { #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] connector_name -> Varchar, connector_account_details -> Bytea, disabled -> Nullable<Bool>, payment_methods_enabled -> Nullable<Array<Nullable<Json>>>, connector_type -> ConnectorType, metadata -> Nullable<Jsonb>, #[max_length = 255] connector_label -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, connector_webhook_details -> Nullable<Jsonb>, frm_config -> Nullable<Array<Nullable<Jsonb>>>, #[max_length = 64] profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, status -> ConnectorStatus, additional_merchant_data -> Nullable<Bytea>, connector_wallets_details -> Nullable<Bytea>, version -> ApiVersion, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; merchant_key_store (merchant_id) { #[max_length = 64] merchant_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; organization (id) { organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 32] id -> Varchar, organization_name -> Nullable<Text>, version -> ApiVersion, #[max_length = 64] organization_type -> Nullable<Varchar>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_attempt (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, status -> AttemptStatus, #[max_length = 64] connector -> Nullable<Varchar>, error_message -> Nullable<Text>, surcharge_amount -> Nullable<Int8>, #[max_length = 64] payment_method_id -> Nullable<Varchar>, authentication_type -> Nullable<AuthenticationType>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, #[max_length = 255] cancellation_reason -> Nullable<Varchar>, amount_to_capture -> Nullable<Int8>, browser_info -> Nullable<Jsonb>, #[max_length = 255] error_code -> Nullable<Varchar>, #[max_length = 128] payment_token -> Nullable<Varchar>, connector_metadata -> Nullable<Jsonb>, #[max_length = 50] payment_experience -> Nullable<Varchar>, payment_method_data -> Nullable<Jsonb>, preprocessing_step_id -> Nullable<Varchar>, error_reason -> Nullable<Text>, multiple_capture_count -> Nullable<Int2>, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, amount_capturable -> Int8, #[max_length = 32] updated_by -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, encoded_data -> Nullable<Text>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, net_amount -> Nullable<Int8>, external_three_ds_authentication_attempted -> Nullable<Bool>, #[max_length = 64] authentication_connector -> Nullable<Varchar>, #[max_length = 64] authentication_id -> Nullable<Varchar>, #[max_length = 64] fingerprint_id -> Nullable<Varchar>, #[max_length = 64] client_source -> Nullable<Varchar>, #[max_length = 64] client_version -> Nullable<Varchar>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] organization_id -> Varchar, #[max_length = 32] card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, request_extended_authorization -> Nullable<Bool>, extended_authorization_applied -> Nullable<Bool>, capture_before -> Nullable<Timestamp>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, #[max_length = 255] connector_request_reference_id -> Nullable<Varchar>, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, is_overcapture_enabled -> Nullable<Bool>, network_details -> Nullable<Jsonb>, is_stored_credential -> Nullable<Bool>, authorized_amount -> Nullable<Int8>, payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 128] connector_payment_id -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Varchar, routing_result -> Nullable<Jsonb>, authentication_applied -> Nullable<AuthenticationType>, #[max_length = 128] external_reference_id -> Nullable<Varchar>, tax_on_surcharge -> Nullable<Int8>, payment_method_billing_address -> Nullable<Bytea>, redirection_data -> Nullable<Jsonb>, connector_payment_data -> Nullable<Text>, connector_token_details -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, feature_metadata -> Nullable<Jsonb>, #[max_length = 32] network_advice_code -> Nullable<Varchar>, #[max_length = 32] network_decline_code -> Nullable<Varchar>, network_error_message -> Nullable<Text>, #[max_length = 64] attempts_group_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_intent (id) { #[max_length = 64] merchant_id -> Varchar, status -> IntentStatus, amount -> Int8, currency -> Nullable<Currency>, amount_captured -> Nullable<Int8>, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 255] return_url -> Nullable<Varchar>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, last_synced -> Nullable<Timestamp>, setup_future_usage -> Nullable<FutureUsage>, #[max_length = 64] active_attempt_id -> Nullable<Varchar>, order_details -> Nullable<Array<Nullable<Jsonb>>>, allowed_payment_method_types -> Nullable<Json>, connector_metadata -> Nullable<Json>, feature_metadata -> Nullable<Json>, attempt_count -> Int2, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] payment_link_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, surcharge_applicable -> Nullable<Bool>, request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, request_external_three_ds_authentication -> Nullable<Bool>, frm_metadata -> Nullable<Jsonb>, customer_details -> Nullable<Bytea>, shipping_cost -> Nullable<Int8>, #[max_length = 32] organization_id -> Varchar, tax_details -> Nullable<Jsonb>, skip_external_tax_calculation -> Nullable<Bool>, request_extended_authorization -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, #[max_length = 64] platform_merchant_id -> Nullable<Varchar>, force_3ds_challenge -> Nullable<Bool>, force_3ds_challenge_trigger -> Nullable<Bool>, #[max_length = 64] processor_merchant_id -> Nullable<Varchar>, #[max_length = 255] created_by -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, is_payment_id_from_merchant -> Nullable<Bool>, #[max_length = 64] payment_channel -> Nullable<Varchar>, tax_status -> Nullable<Varchar>, discount_amount -> Nullable<Int8>, shipping_amount_tax -> Nullable<Int8>, duty_amount -> Nullable<Int8>, order_date -> Nullable<Timestamp>, enable_partial_authorization -> Nullable<Bool>, enable_overcapture -> Nullable<Bool>, #[max_length = 64] mit_category -> Nullable<Varchar>, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, billing_address -> Nullable<Bytea>, shipping_address -> Nullable<Bytea>, capture_method -> Nullable<CaptureMethod>, authentication_type -> Nullable<AuthenticationType>, prerouting_algorithm -> Nullable<Jsonb>, surcharge_amount -> Nullable<Int8>, tax_on_surcharge -> Nullable<Int8>, #[max_length = 64] frm_merchant_decision -> Nullable<Varchar>, #[max_length = 255] statement_descriptor -> Nullable<Varchar>, enable_payment_link -> Nullable<Bool>, apply_mit_exemption -> Nullable<Bool>, customer_present -> Nullable<Bool>, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, #[max_length = 16] split_txns_enabled -> Nullable<Varchar>, #[max_length = 64] active_attempts_group_id -> Nullable<Varchar>, #[max_length = 16] active_attempt_id_type -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_link (payment_link_id) { #[max_length = 255] payment_link_id -> Varchar, #[max_length = 64] payment_id -> Varchar, #[max_length = 255] link_to_pay -> Varchar, #[max_length = 64] merchant_id -> Varchar, amount -> Int8, currency -> Nullable<Currency>, created_at -> Timestamp, last_modified_at -> Timestamp, fulfilment_time -> Nullable<Timestamp>, #[max_length = 64] custom_merchant_name -> Nullable<Varchar>, payment_link_config -> Nullable<Jsonb>, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 255] secure_link -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payment_methods (id) { #[max_length = 64] customer_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, payment_method_data -> Nullable<Bytea>, #[max_length = 64] locker_id -> Nullable<Varchar>, last_used_at -> Timestamp, connector_mandate_details -> Nullable<Jsonb>, customer_acceptance -> Nullable<Jsonb>, #[max_length = 64] status -> Varchar, #[max_length = 255] network_transaction_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, payment_method_billing_address -> Nullable<Bytea>, #[max_length = 64] updated_by -> Nullable<Varchar>, version -> ApiVersion, #[max_length = 128] network_token_requestor_reference_id -> Nullable<Varchar>, #[max_length = 64] network_token_locker_id -> Nullable<Varchar>, network_token_payment_method_data -> Nullable<Bytea>, #[max_length = 64] external_vault_source -> Nullable<Varchar>, #[max_length = 64] vault_type -> Nullable<Varchar>, #[max_length = 64] locker_fingerprint_id -> Nullable<Varchar>, #[max_length = 64] payment_method_type_v2 -> Nullable<Varchar>, #[max_length = 64] payment_method_subtype -> Nullable<Varchar>, #[max_length = 64] id -> Varchar, external_vault_token_data -> Nullable<Bytea>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payout_attempt (merchant_id, payout_attempt_id) { #[max_length = 64] payout_attempt_id -> Varchar, #[max_length = 64] payout_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] address_id -> Nullable<Varchar>, #[max_length = 64] connector -> Nullable<Varchar>, #[max_length = 128] connector_payout_id -> Nullable<Varchar>, #[max_length = 64] payout_token -> Nullable<Varchar>, status -> PayoutStatus, is_eligible -> Nullable<Bool>, error_message -> Nullable<Text>, #[max_length = 64] error_code -> Nullable<Varchar>, business_country -> Nullable<CountryAlpha2>, #[max_length = 64] business_label -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, additional_payout_method_data -> Nullable<Jsonb>, #[max_length = 255] merchant_order_reference_id -> Nullable<Varchar>, payout_connector_metadata -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; payouts (merchant_id, payout_id) { #[max_length = 64] payout_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Nullable<Varchar>, #[max_length = 64] address_id -> Nullable<Varchar>, payout_type -> Nullable<PayoutType>, #[max_length = 64] payout_method_id -> Nullable<Varchar>, amount -> Int8, destination_currency -> Currency, source_currency -> Currency, #[max_length = 255] description -> Nullable<Varchar>, recurring -> Bool, auto_fulfill -> Bool, #[max_length = 255] return_url -> Nullable<Varchar>, #[max_length = 64] entity_type -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, last_modified_at -> Timestamp, attempt_count -> Int2, #[max_length = 64] profile_id -> Varchar, status -> PayoutStatus, confirm -> Nullable<Bool>, #[max_length = 255] payout_link_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 32] priority -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; process_tracker (id) { #[max_length = 127] id -> Varchar, #[max_length = 64] name -> Nullable<Varchar>, tag -> Array<Nullable<Text>>, #[max_length = 64] runner -> Nullable<Varchar>, retry_count -> Int4, schedule_time -> Nullable<Timestamp>, #[max_length = 255] rule -> Varchar, tracking_data -> Json, #[max_length = 255] business_status -> Varchar, status -> ProcessTrackerStatus, event -> Array<Nullable<Text>>, created_at -> Timestamp, updated_at -> Timestamp, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; refund (id) { #[max_length = 64] payment_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 128] connector_transaction_id -> Varchar, #[max_length = 64] connector -> Varchar, #[max_length = 128] connector_refund_id -> Nullable<Varchar>, #[max_length = 64] external_reference_id -> Nullable<Varchar>, refund_type -> RefundType, total_amount -> Int8, currency -> Currency, refund_amount -> Int8, refund_status -> RefundStatus, sent_to_gateway -> Bool, refund_error_message -> Nullable<Text>, metadata -> Nullable<Json>, #[max_length = 128] refund_arn -> Nullable<Varchar>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 255] description -> Nullable<Varchar>, #[max_length = 64] attempt_id -> Varchar, #[max_length = 255] refund_reason -> Nullable<Varchar>, refund_error_code -> Nullable<Text>, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 32] updated_by -> Varchar, charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, processor_refund_data -> Nullable<Text>, processor_transaction_data -> Nullable<Text>, #[max_length = 64] id -> Varchar, #[max_length = 64] merchant_reference_id -> Nullable<Varchar>, #[max_length = 64] connector_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; relay (id) { #[max_length = 64] id -> Varchar, #[max_length = 128] connector_resource_id -> Varchar, #[max_length = 64] connector_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, relay_type -> RelayType, request_data -> Nullable<Jsonb>, status -> RelayStatus, #[max_length = 128] connector_reference_id -> Nullable<Varchar>, #[max_length = 64] error_code -> Nullable<Varchar>, error_message -> Nullable<Text>, created_at -> Timestamp, modified_at -> Timestamp, response_data -> Nullable<Jsonb>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; reverse_lookup (lookup_id) { #[max_length = 128] lookup_id -> Varchar, #[max_length = 128] sk_id -> Varchar, #[max_length = 128] pk_id -> Varchar, #[max_length = 128] source -> Varchar, #[max_length = 32] updated_by -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; roles (role_id) { #[max_length = 64] role_name -> Varchar, #[max_length = 64] role_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] org_id -> Varchar, groups -> Array<Nullable<Text>>, scope -> RoleScope, created_at -> Timestamp, #[max_length = 64] created_by -> Varchar, last_modified_at -> Timestamp, #[max_length = 64] last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; routing_algorithm (algorithm_id) { #[max_length = 64] algorithm_id -> Varchar, #[max_length = 64] profile_id -> Varchar, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] name -> Varchar, #[max_length = 256] description -> Nullable<Varchar>, kind -> RoutingAlgorithmKind, algorithm_data -> Jsonb, created_at -> Timestamp, modified_at -> Timestamp, algorithm_for -> TransactionType, #[max_length = 64] decision_engine_routing_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; subscription (id) { #[max_length = 128] id -> Varchar, #[max_length = 128] status -> Varchar, #[max_length = 128] billing_processor -> Nullable<Varchar>, #[max_length = 128] payment_method_id -> Nullable<Varchar>, #[max_length = 128] merchant_connector_id -> Nullable<Varchar>, #[max_length = 128] client_secret -> Nullable<Varchar>, #[max_length = 128] connector_subscription_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, #[max_length = 64] profile_id -> Varchar, #[max_length = 128] merchant_reference_id -> Nullable<Varchar>, #[max_length = 128] plan_id -> Nullable<Varchar>, #[max_length = 128] item_price_id -> Nullable<Varchar>, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; themes (theme_id) { #[max_length = 64] theme_id -> Varchar, #[max_length = 64] tenant_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, #[max_length = 64] email_primary_color -> Varchar, #[max_length = 64] email_foreground_color -> Varchar, #[max_length = 64] email_background_color -> Varchar, #[max_length = 64] email_entity_name -> Varchar, email_entity_logo_url -> Text, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; tokenization (id) { #[max_length = 64] id -> Varchar, #[max_length = 255] merchant_id -> Varchar, #[max_length = 64] customer_id -> Varchar, created_at -> Timestamp, updated_at -> Timestamp, #[max_length = 255] locker_id -> Varchar, flag -> TokenizationFlag, version -> ApiVersion, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; unified_translations (unified_code, unified_message, locale) { #[max_length = 255] unified_code -> Varchar, #[max_length = 1024] unified_message -> Varchar, #[max_length = 255] locale -> Varchar, #[max_length = 1024] translation -> Varchar, created_at -> Timestamp, last_modified_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_authentication_methods (id) { #[max_length = 64] id -> Varchar, #[max_length = 64] auth_id -> Varchar, #[max_length = 64] owner_id -> Varchar, #[max_length = 64] owner_type -> Varchar, #[max_length = 64] auth_type -> Varchar, private_config -> Nullable<Bytea>, public_config -> Nullable<Jsonb>, allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, #[max_length = 64] email_domain -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_key_store (user_id) { #[max_length = 64] user_id -> Varchar, key -> Bytea, created_at -> Timestamp, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; user_roles (id) { id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 64] merchant_id -> Nullable<Varchar>, #[max_length = 64] role_id -> Varchar, #[max_length = 64] org_id -> Nullable<Varchar>, status -> UserStatus, #[max_length = 64] created_by -> Varchar, #[max_length = 64] last_modified_by -> Varchar, created_at -> Timestamp, last_modified -> Timestamp, #[max_length = 64] profile_id -> Nullable<Varchar>, #[max_length = 64] entity_id -> Nullable<Varchar>, #[max_length = 64] entity_type -> Nullable<Varchar>, version -> UserRoleVersion, #[max_length = 64] tenant_id -> Varchar, } } diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; users (user_id) { #[max_length = 64] user_id -> Varchar, #[max_length = 255] email -> Varchar, #[max_length = 255] name -> Varchar, #[max_length = 255] password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, totp_status -> TotpStatus, totp_secret -> Nullable<Bytea>, totp_recovery_codes -> Nullable<Array<Nullable<Text>>>, last_password_modified_at -> Nullable<Timestamp>, lineage_context -> Nullable<Jsonb>, } } diesel::allow_tables_to_appear_in_same_query!( address, api_keys, authentication, blocklist, blocklist_fingerprint, blocklist_lookup, business_profile, callback_mapper, captures, cards_info, configs, customers, dashboard_metadata, dispute, dynamic_routing_stats, events, file_metadata, fraud_check, gateway_status_map, generic_link, hyperswitch_ai_interaction, hyperswitch_ai_interaction_default, incremental_authorization, invoice, locker_mock_up, mandate, merchant_account, merchant_connector_account, merchant_key_store, organization, payment_attempt, payment_intent, payment_link, payment_methods, payout_attempt, payouts, process_tracker, refund, relay, reverse_lookup, roles, routing_algorithm, subscription, themes, tokenization, unified_translations, user_authentication_methods, user_key_store, user_roles, users, );
{ "crate": "diesel_models", "file": "crates/diesel_models/src/schema_v2.rs", "file_size": 55547, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_700700902727061395
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payment_method.rs // File size: 51339 bytes use std::collections::HashMap; use common_enums::MerchantStorageScheme; use common_utils::{ encryption::Encryption, errors::{CustomResult, ParsingError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{enums as storage_enums, schema::payment_methods}; #[cfg(feature = "v2")] use crate::{enums as storage_enums, schema_v2::payment_methods}; #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, #[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)] pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, Serialize, Deserialize)] #[diesel(table_name = payment_methods, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub external_vault_token_data: Option<Encryption>, } impl PaymentMethod { #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, pub vault_type: Option<storage_enums::VaultType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodNew { pub customer_id: common_utils::id_type::GlobalCustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_data: Option<Encryption>, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: Option<Encryption>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: Option<Encryption>, pub external_vault_token_data: Option<Encryption>, pub locker_fingerprint_id: Option<String>, pub payment_method_type_v2: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, pub id: common_utils::id_type::GlobalPaymentMethodId, pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethodNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } } #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct TokenizeCoreWorkflow { pub lookup_key: String, pub pm: storage_enums::PaymentMethod, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { MetadataUpdateAndLastUsed { metadata: Option<serde_json::Value>, last_used_at: PrimitiveDateTime, }, UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, AdditionalDataUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<serde_json::Value>, }, NetworkTokenDataUpdate { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, }, ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<Secret<String>>, }, PaymentMethodBatchUpdate { connector_mandate_details: Option<pii::SecretSerdeValue>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, payment_method_data: Option<Encryption>, }, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub enum PaymentMethodUpdate { UpdatePaymentMethodDataAndLastUsed { payment_method_data: Option<Encryption>, scheme: Option<String>, last_used_at: PrimitiveDateTime, }, PaymentMethodDataUpdate { payment_method_data: Option<Encryption>, }, LastUsedUpdate { last_used_at: PrimitiveDateTime, }, NetworkTransactionIdAndStatusUpdate { network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, }, StatusUpdate { status: Option<storage_enums::PaymentMethodStatus>, }, GenericUpdate { payment_method_data: Option<Encryption>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, connector_mandate_details: Option<CommonMandateReference>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<CommonMandateReference>, }, } impl PaymentMethodUpdate { pub fn convert_to_payment_method_update( self, storage_scheme: MerchantStorageScheme, ) -> PaymentMethodUpdateInternal { let mut update_internal: PaymentMethodUpdateInternal = self.into(); update_internal.updated_by = Some(storage_scheme.to_string()); update_internal } } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, payment_method_type_v2: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<CommonMandateReference>, updated_by: Option<String>, payment_method_subtype: Option<storage_enums::PaymentMethodType>, last_modified: PrimitiveDateTime, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, locker_fingerprint_id: Option<String>, external_vault_source: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { payment_method_data, last_used_at, network_transaction_id, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by, payment_method_subtype, last_modified, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, created_at: source.created_at, last_modified, payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id), payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2), payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype), id: source.id, version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: external_vault_source.or(source.external_vault_source), external_vault_token_data: source.external_vault_token_data, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)] #[diesel(table_name = payment_methods)] pub struct PaymentMethodUpdateInternal { metadata: Option<serde_json::Value>, payment_method_data: Option<Encryption>, last_used_at: Option<PrimitiveDateTime>, network_transaction_id: Option<String>, status: Option<storage_enums::PaymentMethodStatus>, locker_id: Option<String>, network_token_requestor_reference_id: Option<String>, payment_method: Option<storage_enums::PaymentMethod>, connector_mandate_details: Option<serde_json::Value>, updated_by: Option<String>, payment_method_type: Option<storage_enums::PaymentMethodType>, payment_method_issuer: Option<String>, last_modified: PrimitiveDateTime, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, scheme: Option<String>, } #[cfg(feature = "v1")] impl PaymentMethodUpdateInternal { pub fn apply_changeset(self, source: PaymentMethod) -> PaymentMethod { let Self { metadata, payment_method_data, last_used_at, network_transaction_id, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details, updated_by, payment_method_type, payment_method_issuer, last_modified, network_token_locker_id, network_token_payment_method_data, scheme, } = self; PaymentMethod { customer_id: source.customer_id, merchant_id: source.merchant_id, payment_method_id: source.payment_method_id, accepted_currency: source.accepted_currency, scheme: scheme.or(source.scheme), token: source.token, cardholder_name: source.cardholder_name, issuer_name: source.issuer_name, issuer_country: source.issuer_country, payer_country: source.payer_country, is_stored: source.is_stored, swift_code: source.swift_code, direct_debit_token: source.direct_debit_token, created_at: source.created_at, last_modified, payment_method: payment_method.or(source.payment_method), payment_method_type: payment_method_type.or(source.payment_method_type), payment_method_issuer: payment_method_issuer.or(source.payment_method_issuer), payment_method_issuer_code: source.payment_method_issuer_code, metadata: metadata.map_or(source.metadata, |v| Some(v.into())), payment_method_data: payment_method_data.or(source.payment_method_data), locker_id: locker_id.or(source.locker_id), last_used_at: last_used_at.unwrap_or(source.last_used_at), connector_mandate_details: connector_mandate_details .or(source.connector_mandate_details), customer_acceptance: source.customer_acceptance, status: status.unwrap_or(source.status), network_transaction_id: network_transaction_id.or(source.network_transaction_id), client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), version: source.version, network_token_requestor_reference_id: network_token_requestor_reference_id .or(source.network_token_requestor_reference_id), network_token_locker_id: network_token_locker_id.or(source.network_token_locker_id), network_token_payment_method_data: network_token_payment_method_data .or(source.network_token_payment_method_data), external_vault_source: source.external_vault_source, vault_type: source.vault_type, } } } #[cfg(feature = "v1")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::MetadataUpdateAndLastUsed { metadata, last_used_at, } => Self { metadata, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { metadata: None, payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, scheme, last_used_at, } => Self { metadata: None, payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { metadata: None, payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::AdditionalDataUpdate { payment_method_data, status, locker_id, network_token_requestor_reference_id, payment_method, payment_method_type, payment_method_issuer, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, network_token_requestor_reference_id, payment_method, connector_mandate_details: None, updated_by: None, payment_method_issuer, payment_method_type, last_modified: common_utils::date_time::now(), network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::NetworkTokenDataUpdate { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, } => Self { metadata: None, payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method: None, connector_mandate_details: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_transaction_id: None, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, scheme: None, }, PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate { connector_mandate_details, network_transaction_id, } => Self { connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id: network_transaction_id.map(|txn_id| txn_id.expose()), last_modified: common_utils::date_time::now(), status: None, metadata: None, payment_method_data: None, last_used_at: None, locker_id: None, payment_method: None, updated_by: None, payment_method_issuer: None, payment_method_type: None, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, }, PaymentMethodUpdate::PaymentMethodBatchUpdate { connector_mandate_details, network_transaction_id, status, payment_method_data, } => Self { metadata: None, last_used_at: None, status, locker_id: None, network_token_requestor_reference_id: None, payment_method: None, connector_mandate_details: connector_mandate_details .map(|mandate_details| mandate_details.expose()), network_transaction_id, updated_by: None, payment_method_issuer: None, payment_method_type: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_payment_method_data: None, scheme: None, payment_method_data, }, } } } #[cfg(feature = "v2")] impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { fn from(payment_method_update: PaymentMethodUpdate) -> Self { match payment_method_update { PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { payment_method_data: None, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, last_used_at, .. } => Self { payment_method_data, last_used_at: Some(last_used_at), network_transaction_id: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, status, } => Self { payment_method_data: None, last_used_at: None, network_transaction_id, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { payment_method_data: None, last_used_at: None, network_transaction_id: None, status, locker_id: None, payment_method_type_v2: None, connector_mandate_details: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, PaymentMethodUpdate::GenericUpdate { payment_method_data, status, locker_id, payment_method_type_v2, payment_method_subtype, network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, connector_mandate_details, external_vault_source, } => Self { payment_method_data, last_used_at: None, network_transaction_id: None, status, locker_id, payment_method_type_v2, connector_mandate_details, updated_by: None, payment_method_subtype, last_modified: common_utils::date_time::now(), network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, locker_fingerprint_id, external_vault_source, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, } => Self { payment_method_data: None, last_used_at: None, status: None, locker_id: None, payment_method_type_v2: None, connector_mandate_details, network_transaction_id: None, updated_by: None, payment_method_subtype: None, last_modified: common_utils::date_time::now(), network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, locker_fingerprint_id: None, external_vault_source: None, }, } } } #[cfg(feature = "v1")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), payment_method_id: payment_method_new.payment_method_id.clone(), locker_id: payment_method_new.locker_id.clone(), network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), accepted_currency: payment_method_new.accepted_currency.clone(), scheme: payment_method_new.scheme.clone(), token: payment_method_new.token.clone(), cardholder_name: payment_method_new.cardholder_name.clone(), issuer_name: payment_method_new.issuer_name.clone(), issuer_country: payment_method_new.issuer_country.clone(), payer_country: payment_method_new.payer_country.clone(), is_stored: payment_method_new.is_stored, swift_code: payment_method_new.swift_code.clone(), direct_debit_token: payment_method_new.direct_debit_token.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method: payment_method_new.payment_method, payment_method_type: payment_method_new.payment_method_type, payment_method_issuer: payment_method_new.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_new.payment_method_issuer_code, metadata: payment_method_new.metadata.clone(), payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), version: payment_method_new.version, network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: payment_method_new.external_vault_source.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v2")] impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), locker_id: payment_method_new.locker_id.clone(), created_at: payment_method_new.created_at, last_modified: payment_method_new.last_modified, payment_method_data: payment_method_new.payment_method_data.clone(), last_used_at: payment_method_new.last_used_at, connector_mandate_details: payment_method_new.connector_mandate_details.clone(), customer_acceptance: payment_method_new.customer_acceptance.clone(), status: payment_method_new.status, network_transaction_id: payment_method_new.network_transaction_id.clone(), client_secret: payment_method_new.client_secret.clone(), updated_by: payment_method_new.updated_by.clone(), payment_method_billing_address: payment_method_new .payment_method_billing_address .clone(), locker_fingerprint_id: payment_method_new.locker_fingerprint_id.clone(), payment_method_type_v2: payment_method_new.payment_method_type_v2, payment_method_subtype: payment_method_new.payment_method_subtype, id: payment_method_new.id.clone(), version: payment_method_new.version, network_token_requestor_reference_id: payment_method_new .network_token_requestor_reference_id .clone(), network_token_locker_id: payment_method_new.network_token_locker_id.clone(), network_token_payment_method_data: payment_method_new .network_token_payment_method_data .clone(), external_vault_source: None, external_vault_token_data: payment_method_new.external_vault_token_data.clone(), vault_type: payment_method_new.vault_type, } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, pub connector_mandate_request_reference_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorTokenReferenceRecord { pub connector_token: String, pub payment_method_subtype: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<common_utils::types::MinorUnit>, pub original_payment_authorized_currency: Option<common_enums::Currency>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_token_status: common_enums::ConnectorTokenStatus, pub connector_token_request_reference_id: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[cfg(feature = "v1")] impl std::ops::Deref for PaymentsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v1")] impl std::ops::DerefMut for PaymentsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PaymentsTokenReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>, ); #[cfg(feature = "v2")] impl std::ops::Deref for PaymentsTokenReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v2")] impl std::ops::DerefMut for PaymentsTokenReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] common_utils::impl_to_sql_from_sql_json!(PaymentsMandateReference); #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(PaymentsTokenReference); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct PayoutsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); impl std::ops::Deref for PayoutsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for PayoutsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CommonMandateReference { pub payments: Option<PaymentsTokenReference>, pub payouts: Option<PayoutsMandateReference>, } impl CommonMandateReference { 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) } #[cfg(feature = "v2")] /// Insert a new payment token reference for the given connector_id 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)); } } } } impl diesel::serialize::ToSql<diesel::sql_types::Jsonb, diesel::pg::Pg> for CommonMandateReference { 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()) } } #[cfg(feature = "v1")] impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB> for CommonMandateReference where serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>, { 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, }) } } #[cfg(feature = "v2")] impl<DB: diesel::backend::Backend> diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB> for CommonMandateReference where serde_json::Value: diesel::deserialize::FromSql<diesel::sql_types::Jsonb, DB>, { 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, }) } } #[cfg(feature = "v1")] impl From<PaymentsMandateReference> for CommonMandateReference { fn from(payment_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payment_reference), payouts: None, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payment_method.rs", "file_size": 51339, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-4045560811561951506
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/business_profile.rs // File size: 48839 bytes use std::collections::{HashMap, HashSet}; use common_enums::{AuthenticationConnectors, UIWidgetFormLayout, VaultSdk}; use common_types::primitive_wrappers; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::Duration; #[cfg(feature = "v1")] use crate::schema::business_profile; #[cfg(feature = "v2")] use crate::schema_v2::business_profile; /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will /// not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the /// fields read / written will be interchanged #[cfg(feature = "v1")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))] 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>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id))] pub struct ProfileNew { 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 is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, 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>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile)] pub struct ProfileUpdateInternal { pub profile_name: Option<String>, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<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: Option<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 is_l2_l3_enabled: Option<bool>, pub dynamic_routing_algorithm: Option<serde_json::Value>, pub is_network_tokenization_enabled: Option<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: Option<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: Option<bool>, pub force_3ds_challenge: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, pub is_pre_network_tokenization_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, } #[cfg(feature = "v1")] impl ProfileUpdateInternal { pub fn apply_changeset(self, source: Profile) -> Profile { let Self { profile_name, modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, routing_algorithm, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, is_recon_enabled, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, is_l2_l3_enabled, dynamic_routing_algorithm, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, always_request_extended_authorization, is_click_to_pay_enabled, authentication_product_ids, card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled, force_3ds_challenge, is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, is_pre_network_tokenization_enabled, three_ds_decision_rule_algorithm, acquirer_config_map, merchant_category_code, merchant_country_code, dispute_polling_interval, is_manual_retry_enabled, always_enable_overcapture, is_external_vault_enabled, external_vault_connector_details, billing_processor_id, } = self; Profile { profile_id: source.profile_id, merchant_id: source.merchant_id, profile_name: profile_name.unwrap_or(source.profile_name), created_at: source.created_at, modified_at, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(source.webhook_details), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), applepay_verified_domains: applepay_verified_domains .or(source.applepay_verified_domains), payment_link_config: payment_link_config.or(source.payment_link_config), session_expiry: session_expiry.or(source.session_expiry), authentication_connector_details: authentication_connector_details .or(source.authentication_connector_details), payout_link_config: payout_link_config.or(source.payout_link_config), is_extended_card_info_enabled: is_extended_card_info_enabled .or(source.is_extended_card_info_enabled), is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled .or(source.is_connector_agnostic_mit_enabled), extended_card_info_config: extended_card_info_config .or(source.extended_card_info_config), use_billing_as_payment_method_billing: use_billing_as_payment_method_billing .or(source.use_billing_as_payment_method_billing), collect_shipping_details_from_wallet_connector: collect_shipping_details_from_wallet_connector .or(source.collect_shipping_details_from_wallet_connector), collect_billing_details_from_wallet_connector: collect_billing_details_from_wallet_connector .or(source.collect_billing_details_from_wallet_connector), outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .or(source.outgoing_webhook_custom_http_headers), always_collect_billing_details_from_wallet_connector: always_collect_billing_details_from_wallet_connector .or(source.always_collect_billing_details_from_wallet_connector), always_collect_shipping_details_from_wallet_connector: always_collect_shipping_details_from_wallet_connector .or(source.always_collect_shipping_details_from_wallet_connector), tax_connector_id: tax_connector_id.or(source.tax_connector_id), is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled), is_l2_l3_enabled: is_l2_l3_enabled.or(source.is_l2_l3_enabled), version: source.version, dynamic_routing_algorithm: dynamic_routing_algorithm .or(source.dynamic_routing_algorithm), is_network_tokenization_enabled: is_network_tokenization_enabled .unwrap_or(source.is_network_tokenization_enabled), is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled), max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled), always_request_extended_authorization: always_request_extended_authorization .or(source.always_request_extended_authorization), is_click_to_pay_enabled: is_click_to_pay_enabled .unwrap_or(source.is_click_to_pay_enabled), authentication_product_ids: authentication_product_ids .or(source.authentication_product_ids), card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key, is_clear_pan_retries_enabled: is_clear_pan_retries_enabled .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge, id: source.id, is_debit_routing_enabled: is_debit_routing_enabled .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), is_pre_network_tokenization_enabled: is_pre_network_tokenization_enabled .or(source.is_pre_network_tokenization_enabled), three_ds_decision_rule_algorithm: three_ds_decision_rule_algorithm .or(source.three_ds_decision_rule_algorithm), acquirer_config_map: acquirer_config_map.or(source.acquirer_config_map), merchant_category_code: merchant_category_code.or(source.merchant_category_code), merchant_country_code: merchant_country_code.or(source.merchant_country_code), dispute_polling_interval: dispute_polling_interval.or(source.dispute_polling_interval), is_manual_retry_enabled: is_manual_retry_enabled.or(source.is_manual_retry_enabled), always_enable_overcapture: always_enable_overcapture .or(source.always_enable_overcapture), is_external_vault_enabled: is_external_vault_enabled .or(source.is_external_vault_enabled), external_vault_connector_details: external_vault_connector_details .or(source.external_vault_connector_details), billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will /// not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the /// fields read / written will be interchanged #[cfg(feature = "v2")] #[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Profile { 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<common_utils::types::Url>, 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 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: common_utils::id_type::ProfileId, pub is_iframe_redirection_enabled: Option<bool>, pub three_ds_decision_rule_algorithm: Option<serde_json::Value>, pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, pub is_manual_retry_enabled: Option<bool>, pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } impl Profile { #[cfg(feature = "v1")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.profile_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::ProfileId { &self.id } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id))] pub struct ProfileNew { 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<common_utils::types::Url>, 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 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 is_network_tokenization_enabled: bool, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, 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: Option<bool>, pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub id: common_utils::id_type::ProfileId, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile)] pub struct ProfileUpdateInternal { pub profile_name: Option<String>, pub modified_at: time::PrimitiveDateTime, pub return_url: Option<common_utils::types::Url>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub webhook_details: Option<WebhookDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub is_recon_enabled: Option<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 is_network_tokenization_enabled: Option<bool>, pub is_auto_retries_enabled: Option<bool>, pub max_auto_retries_enabled: Option<i16>, pub is_click_to_pay_enabled: Option<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: Option<bool>, pub is_debit_routing_enabled: Option<bool>, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub merchant_category_code: Option<common_enums::MerchantCategoryCode>, pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, pub frm_routing_algorithm_id: Option<String>, pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub default_fallback_routing: Option<pii::SecretSerdeValue>, pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>, pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>, pub is_iframe_redirection_enabled: Option<bool>, pub is_external_vault_enabled: Option<bool>, pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, pub is_l2_l3_enabled: Option<bool>, pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, } #[cfg(feature = "v2")] impl ProfileUpdateInternal { pub fn apply_changeset(self, source: Profile) -> Profile { let Self { profile_name, modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, webhook_details, metadata, is_recon_enabled, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled, extended_card_info_config, is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector, tax_connector_id, is_tax_connector_enabled, billing_processor_id, routing_algorithm_id, order_fulfillment_time, order_fulfillment_time_origin, frm_routing_algorithm_id, payout_routing_algorithm_id, default_fallback_routing, should_collect_cvv_during_payment, is_network_tokenization_enabled, is_auto_retries_enabled, max_auto_retries_enabled, is_click_to_pay_enabled, authentication_product_ids, three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key, is_clear_pan_retries_enabled, is_debit_routing_enabled, merchant_business_country, revenue_recovery_retry_algorithm_type, revenue_recovery_retry_algorithm_data, is_iframe_redirection_enabled, is_external_vault_enabled, external_vault_connector_details, merchant_category_code, merchant_country_code, split_txns_enabled, is_l2_l3_enabled, } = self; Profile { id: source.id, merchant_id: source.merchant_id, profile_name: profile_name.unwrap_or(source.profile_name), created_at: source.created_at, modified_at, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(source.webhook_details), metadata: metadata.or(source.metadata), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), applepay_verified_domains: applepay_verified_domains .or(source.applepay_verified_domains), payment_link_config: payment_link_config.or(source.payment_link_config), session_expiry: session_expiry.or(source.session_expiry), authentication_connector_details: authentication_connector_details .or(source.authentication_connector_details), payout_link_config: payout_link_config.or(source.payout_link_config), is_extended_card_info_enabled: is_extended_card_info_enabled .or(source.is_extended_card_info_enabled), is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled .or(source.is_connector_agnostic_mit_enabled), extended_card_info_config: extended_card_info_config .or(source.extended_card_info_config), use_billing_as_payment_method_billing: use_billing_as_payment_method_billing .or(source.use_billing_as_payment_method_billing), collect_shipping_details_from_wallet_connector: collect_shipping_details_from_wallet_connector .or(source.collect_shipping_details_from_wallet_connector), collect_billing_details_from_wallet_connector: collect_billing_details_from_wallet_connector .or(source.collect_billing_details_from_wallet_connector), outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers .or(source.outgoing_webhook_custom_http_headers), always_collect_billing_details_from_wallet_connector: always_collect_billing_details_from_wallet_connector .or(always_collect_billing_details_from_wallet_connector), always_collect_shipping_details_from_wallet_connector: always_collect_shipping_details_from_wallet_connector .or(always_collect_shipping_details_from_wallet_connector), tax_connector_id: tax_connector_id.or(source.tax_connector_id), is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled), routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time), order_fulfillment_time_origin: order_fulfillment_time_origin .or(source.order_fulfillment_time_origin), frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id), payout_routing_algorithm_id: payout_routing_algorithm_id .or(source.payout_routing_algorithm_id), default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing), should_collect_cvv_during_payment: should_collect_cvv_during_payment .or(source.should_collect_cvv_during_payment), version: source.version, dynamic_routing_algorithm: None, is_network_tokenization_enabled: is_network_tokenization_enabled .unwrap_or(source.is_network_tokenization_enabled), is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled), max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled), always_request_extended_authorization: None, is_click_to_pay_enabled: is_click_to_pay_enabled .unwrap_or(source.is_click_to_pay_enabled), authentication_product_ids: authentication_product_ids .or(source.authentication_product_ids), three_ds_decision_manager_config: three_ds_decision_manager_config .or(source.three_ds_decision_manager_config), card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key: card_testing_secret_key.or(source.card_testing_secret_key), is_clear_pan_retries_enabled: is_clear_pan_retries_enabled .unwrap_or(source.is_clear_pan_retries_enabled), force_3ds_challenge: None, is_debit_routing_enabled: is_debit_routing_enabled .unwrap_or(source.is_debit_routing_enabled), merchant_business_country: merchant_business_country .or(source.merchant_business_country), revenue_recovery_retry_algorithm_type: revenue_recovery_retry_algorithm_type .or(source.revenue_recovery_retry_algorithm_type), revenue_recovery_retry_algorithm_data: revenue_recovery_retry_algorithm_data .or(source.revenue_recovery_retry_algorithm_data), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), is_external_vault_enabled: is_external_vault_enabled .or(source.is_external_vault_enabled), external_vault_connector_details: external_vault_connector_details .or(source.external_vault_connector_details), three_ds_decision_rule_algorithm: None, acquirer_config_map: None, merchant_category_code: merchant_category_code.or(source.merchant_category_code), merchant_country_code: merchant_country_code.or(source.merchant_country_code), dispute_polling_interval: None, split_txns_enabled: split_txns_enabled.or(source.split_txns_enabled), is_manual_retry_enabled: None, always_enable_overcapture: None, is_l2_l3_enabled: None, billing_processor_id: billing_processor_id.or(source.billing_processor_id), } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct AuthenticationConnectorDetails { pub authentication_connectors: Vec<AuthenticationConnectors>, pub three_ds_requestor_url: String, pub three_ds_requestor_app_url: Option<String>, } common_utils::impl_to_sql_from_sql_json!(AuthenticationConnectorDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct ExternalVaultConnectorDetails { pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub vault_sdk: Option<VaultSdk>, } common_utils::impl_to_sql_from_sql_json!(ExternalVaultConnectorDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct CardTestingGuardConfig { pub is_card_ip_blocking_enabled: bool, pub card_ip_blocking_threshold: i32, pub is_guest_user_card_blocking_enabled: bool, pub guest_user_card_blocking_threshold: i32, pub is_customer_id_blocking_enabled: bool, pub customer_id_blocking_threshold: i32, pub card_testing_guard_expiry: i32, } common_utils::impl_to_sql_from_sql_json!(CardTestingGuardConfig); impl Default for CardTestingGuardConfig { fn default() -> Self { Self { is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, is_guest_user_card_blocking_enabled: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, guest_user_card_blocking_threshold: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, is_customer_id_blocking_enabled: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, customer_id_blocking_threshold: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, card_testing_guard_expiry: common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct MultipleWebhookDetail { pub webhook_endpoint_id: common_utils::id_type::WebhookEndpointId, pub webhook_url: Secret<String>, pub events: HashSet<common_enums::EventType>, pub status: common_enums::OutgoingWebhookEndpointStatus, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Json)] pub struct WebhookDetails { pub webhook_version: Option<String>, pub webhook_username: Option<String>, pub webhook_password: Option<Secret<String>>, pub webhook_url: Option<Secret<String>>, pub payment_created_enabled: Option<bool>, pub payment_succeeded_enabled: Option<bool>, pub payment_failed_enabled: Option<bool>, pub payment_statuses_enabled: Option<Vec<common_enums::IntentStatus>>, pub refund_statuses_enabled: Option<Vec<common_enums::RefundStatus>>, pub payout_statuses_enabled: Option<Vec<common_enums::PayoutStatus>>, pub multiple_webhooks_list: Option<Vec<MultipleWebhookDetail>>, } common_utils::impl_to_sql_from_sql_json!(WebhookDetails); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct BusinessPaymentLinkConfig { pub domain_name: Option<String>, #[serde(flatten)] pub default_config: Option<PaymentLinkConfigRequest>, pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, pub allowed_domains: Option<HashSet<String>>, pub branding_visibility: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentLinkConfigRequest { pub theme: Option<String>, pub logo: Option<String>, pub seller_name: Option<String>, pub sdk_layout: Option<String>, pub display_sdk_only: Option<bool>, pub enabled_saved_payment_method: Option<bool>, pub hide_card_nickname_field: Option<bool>, pub show_card_form_by_default: Option<bool>, pub background_image: Option<PaymentLinkBackgroundImageConfig>, pub details_layout: Option<common_enums::PaymentLinkDetailsLayout>, pub payment_button_text: Option<String>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub skip_status_screen: Option<bool>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: Option<bool>, pub payment_form_header_text: Option<String>, pub payment_form_label_type: Option<common_enums::PaymentLinkSdkLabelType>, pub show_card_terms: Option<common_enums::PaymentLinkShowSdkTerms>, pub is_setup_mandate_flow: Option<bool>, pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)] pub struct PaymentLinkBackgroundImageConfig { pub url: common_utils::types::Url, pub position: Option<common_enums::ElementPosition>, pub size: Option<common_enums::ElementSize>, } common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, pub form_layout: Option<UIWidgetFormLayout>, pub payout_test_mode: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct BusinessGenericLinkConfig { pub domain_name: Option<String>, pub allowed_domains: HashSet<String>, #[serde(flatten)] pub ui_config: common_utils::link_utils::GenericLinkUiConfig, } common_utils::impl_to_sql_from_sql_json!(BusinessPayoutLinkConfig); #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)] #[diesel(sql_type = diesel::sql_types::Jsonb)] pub struct RevenueRecoveryAlgorithmData { pub monitoring_configured_timestamp: time::PrimitiveDateTime, } impl RevenueRecoveryAlgorithmData { pub fn has_exceeded_monitoring_threshold(&self, monitoring_threshold_in_seconds: i64) -> bool { let total_threshold_time = self.monitoring_configured_timestamp + Duration::seconds(monitoring_threshold_in_seconds); common_utils::date_time::now() >= total_threshold_time } } common_utils::impl_to_sql_from_sql_json!(RevenueRecoveryAlgorithmData);
{ "crate": "diesel_models", "file": "crates/diesel_models/src/business_profile.rs", "file_size": 48839, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-1529040184704540211
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/refund.rs // File size: 32166 bytes use common_utils::{ id_type, pii, types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::refund; #[cfg(feature = "v2")] use crate::{schema_v2::refund, RequiredFromNullable}; #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub internal_reference_id: String, pub refund_id: String, //merchant_reference id pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, /// INFO: This field is deprecated and replaced by processor_refund_data pub connector_refund_data: Option<String>, /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub issuer_error_code: Option<String>, pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, Identifiable, Queryable, Selectable, PartialEq, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct Refund { pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub refund_error_message: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub refund_error_code: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, pub id: id_type::GlobalRefundId, #[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)] pub merchant_reference_id: id_type::RefundReferenceId, pub connector_id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub refund_id: String, pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub internal_reference_id: String, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: String, pub refund_reason: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, router_derive::Setter, )] #[diesel(table_name = refund)] pub struct RefundNew { pub merchant_reference_id: id_type::RefundReferenceId, pub payment_id: id_type::GlobalPaymentId, pub merchant_id: id_type::MerchantId, pub id: id_type::GlobalRefundId, pub external_reference_id: Option<String>, pub connector_transaction_id: ConnectorTransactionId, pub connector: String, pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, pub refund_amount: MinorUnit, pub refund_status: storage_enums::RefundStatus, pub sent_to_gateway: bool, pub metadata: Option<pii::SecretSerdeValue>, pub refund_arn: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub description: Option<String>, pub attempt_id: id_type::GlobalAttemptId, pub refund_reason: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub updated_by: String, pub connector_id: Option<id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: id_type::OrganizationId, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub processor_refund_data: Option<String>, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, reason: Option<String>, updated_by: String, }, StatusUpdate { connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, }, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, issuer_error_code: Option<String>, issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, refund_arn: Option<String>, metadata: Option<pii::SecretSerdeValue>, refund_reason: Option<String>, refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, } #[cfg(feature = "v1")] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(feature = "v2")] impl RefundUpdateInternal { pub fn create_refund(self, source: Refund) -> Refund { Refund { connector_refund_id: self.connector_refund_id, refund_status: self.refund_status.unwrap_or_default(), sent_to_gateway: self.sent_to_gateway.unwrap_or_default(), refund_error_message: self.refund_error_message, refund_arn: self.refund_arn, metadata: self.metadata, refund_reason: self.refund_reason, refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source } } } #[cfg(feature = "v1")] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, issuer_error_code, issuer_error_message, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, issuer_error_code, issuer_error_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }, } } } #[cfg(feature = "v2")] impl From<RefundUpdate> for RefundUpdateInternal { fn from(refund_update: RefundUpdate) -> Self { match refund_update { RefundUpdate::Update { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, updated_by, processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), sent_to_gateway: Some(sent_to_gateway), refund_error_message, refund_arn: Some(refund_arn), updated_by, processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::MetadataAndReasonUpdate { metadata, reason, updated_by, } => Self { metadata, refund_reason: reason, updated_by, connector_refund_id: None, refund_status: None, sent_to_gateway: None, refund_error_message: None, refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, refund_reason: None, refund_error_code: None, modified_at: common_utils::date_time::now(), unified_code: None, unified_message: None, }, RefundUpdate::ErrorUpdate { refund_status, refund_error_message, refund_error_code, unified_code, unified_message, updated_by, connector_refund_id, processor_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), unified_code, unified_message, }, RefundUpdate::ManualUpdate { refund_status, refund_error_message, refund_error_code, updated_by, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id: None, sent_to_gateway: None, refund_arn: None, metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), processor_refund_data: None, unified_code: None, unified_message: None, }, } } } #[cfg(feature = "v1")] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, issuer_error_code, issuer_error_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), issuer_error_code: issuer_error_code.or(source.issuer_error_code), issuer_error_message: issuer_error_message.or(source.issuer_error_message), ..source } } } #[cfg(feature = "v2")] impl RefundUpdate { pub fn apply_changeset(self, source: Refund) -> Refund { let RefundUpdateInternal { connector_refund_id, refund_status, sent_to_gateway, refund_error_message, refund_arn, metadata, refund_reason, refund_error_code, updated_by, modified_at: _, processor_refund_data, unified_code, unified_message, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), refund_status: refund_status.unwrap_or(source.refund_status), sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway), refund_error_message: refund_error_message.or(source.refund_error_message), refund_error_code: refund_error_code.or(source.refund_error_code), refund_arn: refund_arn.or(source.refund_arn), metadata: metadata.or(source.metadata), refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), ..source } } pub fn build_error_update_for_unified_error_and_message( unified_error_object: (String, String), refund_error_message: Option<String>, refund_error_code: Option<String>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { let (unified_code, unified_message) = unified_error_object; Self::ErrorUpdate { refund_status: Some(storage_enums::RefundStatus::Failure), refund_error_message, refund_error_code, updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), } } pub fn build_error_update_for_integrity_check_failure( integrity_check_failed_fields: String, connector_refund_id: Option<ConnectorTransactionId>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::ErrorUpdate { refund_status: Some(storage_enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {integrity_check_failed_fields}" )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: connector_refund_id.clone(), processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()), unified_code: None, unified_message: None, } } pub fn build_refund_update( connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::Update { connector_refund_id: connector_refund_id.clone(), refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data: connector_refund_id.extract_hashed_data(), } } pub fn build_error_update_for_refund_failure( refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, storage_scheme: &storage_enums::MerchantStorageScheme, ) -> Self { Self::ErrorUpdate { refund_status, refund_error_message, refund_error_code, updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, } } } #[cfg(feature = "v1")] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: id_type::MerchantId, pub payment_id: id_type::PaymentId, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_id: id_type::GlobalRefundId, pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: id_type::MerchantId, pub payment_id: id_type::GlobalPaymentId, pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for Refund { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.id.clone(), }) } } impl ConnectorTransactionIdTrait for Refund { fn get_optional_connector_refund_id(&self) -> Option<&String> { match self .connector_refund_id .as_ref() .map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref())) .transpose() { Ok(refund_id) => refund_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self .connector_refund_id .as_ref() .map(|txn_id| txn_id.get_id()), } } fn get_connector_transaction_id(&self) -> &String { match self .connector_transaction_id .get_txn_id(self.processor_transaction_data.as_ref()) { Ok(txn_id) => txn_id, // In case hashed data is missing from DB, use the hashed ID as connector transaction ID Err(_) => self.connector_transaction_id.get_id(), } } } mod tests { #[test] fn test_backwards_compatibility() { let serialized_refund = r#"{ "internal_reference_id": "internal_ref_123", "refund_id": "refund_456", "payment_id": "payment_789", "merchant_id": "merchant_123", "connector_transaction_id": "connector_txn_789", "connector": "stripe", "connector_refund_id": null, "external_reference_id": null, "refund_type": "instant_refund", "total_amount": 10000, "currency": "USD", "refund_amount": 9500, "refund_status": "Success", "sent_to_gateway": true, "refund_error_message": null, "metadata": null, "refund_arn": null, "created_at": "2024-02-26T12:00:00Z", "updated_at": "2024-02-26T12:00:00Z", "description": null, "attempt_id": "attempt_123", "refund_reason": null, "refund_error_code": null, "profile_id": null, "updated_by": "admin", "merchant_connector_id": null, "charges": null, "connector_transaction_data": null "unified_code": null, "unified_message": null, "processor_transaction_data": null, }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); assert!(deserialized.is_ok()); } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/refund.rs", "file_size": 32166, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-3395068887327304885
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/authentication.rs // File size: 25383 bytes use std::str::FromStr; use common_utils::{ encryption::Encryption, errors::{CustomResult, ValidationError}, pii, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{self, Deserialize, Serialize}; use serde_json; use crate::schema::authentication; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))] pub struct Authentication { pub authentication_id: common_utils::id_type::AuthenticationId, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: Option<String>, pub connector_authentication_id: Option<String>, pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub authentication_client_secret: Option<String>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub return_url: Option<String>, pub amount: Option<common_utils::types::MinorUnit>, pub currency: Option<common_enums::Currency>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } impl Authentication { pub fn is_separate_authn_required(&self) -> bool { self.maximum_supported_version .as_ref() .is_some_and(|version| version.get_major() == 2) } // get authentication_connector from authentication record and check if it is jwt flow pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> { Ok(self .authentication_connector .clone() .map(|connector| { common_enums::AuthenticationConnectors::from_str(&connector) .change_context(ValidationError::InvalidValue { message: "failed to parse authentication_connector".to_string(), }) .map(|connector_enum| connector_enum.is_jwt_flow()) }) .transpose()? .unwrap_or(false)) } } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)] #[diesel(table_name = authentication)] pub struct AuthenticationNew { pub authentication_id: common_utils::id_type::AuthenticationId, pub merchant_id: common_utils::id_type::MerchantId, pub authentication_connector: Option<String>, pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: String, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: common_enums::AuthenticationStatus, pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub cavv: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub profile_id: common_utils::id_type::ProfileId, pub payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub authentication_client_secret: Option<String>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub return_url: Option<String>, pub amount: Option<common_utils::types::MinorUnit>, pub currency: Option<common_enums::Currency>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } #[derive(Debug)] pub enum AuthenticationUpdate { PreAuthenticationVersionCallUpdate { maximum_supported_3ds_version: common_utils::types::SemanticVersion, message_version: common_utils::types::SemanticVersion, }, PreAuthenticationThreeDsMethodCall { threeds_server_transaction_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, connector_metadata: Option<serde_json::Value>, }, PreAuthenticationUpdate { threeds_server_transaction_id: String, maximum_supported_3ds_version: common_utils::types::SemanticVersion, connector_authentication_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, message_version: common_utils::types::SemanticVersion, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, directory_server_id: Option<String>, acquirer_country_code: Option<String>, billing_address: Option<Encryption>, shipping_address: Option<Encryption>, browser_info: Box<Option<serde_json::Value>>, email: Option<Encryption>, }, AuthenticationUpdate { trans_status: common_enums::TransactionStatus, authentication_type: common_enums::DecoupledAuthenticationType, acs_url: Option<String>, challenge_request: Option<String>, acs_reference_number: Option<String>, acs_trans_id: Option<String>, acs_signed_content: Option<String>, connector_metadata: Option<serde_json::Value>, authentication_status: common_enums::AuthenticationStatus, ds_trans_id: Option<String>, eci: Option<String>, challenge_code: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, message_extension: Option<pii::SecretSerdeValue>, challenge_request_key: Option<String>, }, PostAuthenticationUpdate { trans_status: common_enums::TransactionStatus, eci: Option<String>, authentication_status: common_enums::AuthenticationStatus, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, }, ErrorUpdate { error_message: Option<String>, error_code: Option<String>, authentication_status: common_enums::AuthenticationStatus, connector_authentication_id: Option<String>, }, PostAuthorizationUpdate { authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus, }, AuthenticationStatusUpdate { trans_status: common_enums::TransactionStatus, authentication_status: common_enums::AuthenticationStatus, }, } #[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)] #[diesel(table_name = authentication)] pub struct AuthenticationUpdateInternal { pub connector_authentication_id: Option<String>, // pub authentication_data: Option<serde_json::Value>, pub payment_method_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, pub authentication_status: Option<common_enums::AuthenticationStatus>, pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>, pub modified_at: time::PrimitiveDateTime, pub error_message: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub maximum_supported_version: Option<common_utils::types::SemanticVersion>, pub threeds_server_transaction_id: Option<String>, pub authentication_flow_type: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub eci: Option<String>, pub trans_status: Option<common_enums::TransactionStatus>, pub acquirer_bin: Option<String>, pub acquirer_merchant_id: Option<String>, pub three_ds_method_data: Option<String>, pub three_ds_method_url: Option<String>, pub acs_url: Option<String>, pub challenge_request: Option<String>, pub acs_reference_number: Option<String>, pub acs_trans_id: Option<String>, pub acs_signed_content: Option<String>, pub ds_trans_id: Option<String>, pub directory_server_id: Option<String>, pub acquirer_country_code: Option<String>, pub service_details: Option<serde_json::Value>, pub force_3ds_challenge: Option<bool>, pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, pub billing_address: Option<Encryption>, pub shipping_address: Option<Encryption>, pub browser_info: Option<serde_json::Value>, pub email: Option<Encryption>, pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub challenge_request_key: Option<String>, } impl Default for AuthenticationUpdateInternal { 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(), 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(), force_3ds_challenge: Default::default(), psd2_sca_exemption_type: Default::default(), billing_address: Default::default(), shipping_address: Default::default(), browser_info: Default::default(), email: Default::default(), profile_acquirer_id: Default::default(), challenge_code: Default::default(), challenge_cancel: Default::default(), challenge_code_reason: Default::default(), message_extension: Default::default(), challenge_request_key: Default::default(), } } } impl AuthenticationUpdateInternal { 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, 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, force_3ds_challenge, psd2_sca_exemption_type, billing_address, shipping_address, browser_info, email, profile_acquirer_id, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, } = 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), 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), force_3ds_challenge: force_3ds_challenge.or(source.force_3ds_challenge), psd2_sca_exemption_type: psd2_sca_exemption_type.or(source.psd2_sca_exemption_type), billing_address: billing_address.or(source.billing_address), shipping_address: shipping_address.or(source.shipping_address), browser_info: browser_info.or(source.browser_info), email: email.or(source.email), profile_acquirer_id: profile_acquirer_id.or(source.profile_acquirer_id), challenge_code: challenge_code.or(source.challenge_code), challenge_cancel: challenge_cancel.or(source.challenge_cancel), challenge_code_reason: challenge_code_reason.or(source.challenge_code_reason), message_extension: message_extension.or(source.message_extension), challenge_request_key: challenge_request_key.or(source.challenge_request_key), ..source } } } impl From<AuthenticationUpdate> for AuthenticationUpdateInternal { 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, billing_address, shipping_address, browser_info, email, } => 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, billing_address, shipping_address, browser_info: *browser_info, email, ..Default::default() }, AuthenticationUpdate::AuthenticationUpdate { trans_status, authentication_type, acs_url, challenge_request, acs_reference_number, acs_trans_id, acs_signed_content, connector_metadata, authentication_status, ds_trans_id, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, } => Self { 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, eci, challenge_code, challenge_cancel, challenge_code_reason, message_extension, challenge_request_key, ..Default::default() }, AuthenticationUpdate::PostAuthenticationUpdate { trans_status, eci, authentication_status, challenge_cancel, challenge_code_reason, } => Self { trans_status: Some(trans_status), eci, authentication_status: Some(authentication_status), challenge_cancel, challenge_code_reason, ..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() }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/authentication.rs", "file_size": 25383, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-9020189748595322194
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/query/payment_attempt.rs // File size: 20278 bytes #[cfg(feature = "v1")] use std::collections::HashSet; use async_bb8_diesel::AsyncRunQueryDsl; #[cfg(feature = "v1")] use diesel::Table; use diesel::{ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; use super::generics; #[cfg(feature = "v1")] use crate::schema::payment_attempt::dsl; #[cfg(feature = "v2")] use crate::schema_v2::payment_attempt::dsl; #[cfg(feature = "v1")] use crate::{enums::IntentStatus, payment_attempt::PaymentAttemptUpdate, PaymentIntent}; use crate::{ enums::{self}, errors::DatabaseError, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdateInternal}, query::generics::db_metrics, PgPooledConn, StorageResult, }; impl PaymentAttemptNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentAttempt> { generics::generic_insert(conn, self).await } } impl PaymentAttempt { #[cfg(feature = "v1")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdate, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >( conn, dsl::attempt_id .eq(self.attempt_id.to_owned()) .and(dsl::merchant_id.eq(self.merchant_id.to_owned())), PaymentAttemptUpdateInternal::from(payment_attempt).populate_derived_fields(&self), ) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v2")] pub async fn update_with_attempt_id( self, conn: &PgPooledConn, payment_attempt: PaymentAttemptUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_with_unique_predicate_get_result::< <Self as HasTable>::Table, _, _, _, >(conn, dsl::id.eq(self.id.to_owned()), payment_attempt) .await { Err(error) => match error.current_context() { DatabaseError::NoFieldsToUpdate => Ok(self), _ => Err(error), }, result => result, } } #[cfg(feature = "v1")] pub async fn find_optional_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_connector_transaction_id_payment_id_merchant_id( conn: &PgPooledConn, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::connector_transaction_id .eq(connector_transaction_id.get_id().to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_last_successful_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::status.eq(enums::AttemptStatus::Charged)), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id .eq(payment_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v2")] pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Self> { // perform ordering on the application level instead of database level generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::status .eq(enums::AttemptStatus::Charged) .or(dsl::status.eq(enums::AttemptStatus::PartialCharged)), ), Some(1), None, Some(dsl::modified_at.desc()), ) .await? .into_iter() .nth(0) .ok_or(report!(DatabaseError::NotFound)) } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_connector_txn_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_profile_id_connector_transaction_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, connector_txn_id: &str, ) -> StorageResult<Self> { let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data( connector_txn_id.to_string(), ); let connector_transaction_id = txn_id .get_txn_id(txn_data.as_ref()) .change_context(DatabaseError::Others) .attach_printable_lazy(|| { format!("Failed to retrieve txn_id for ({txn_id:?}, {txn_data:?})") })?; generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::profile_id .eq(profile_id.to_owned()) .and(dsl::connector_payment_id.eq(connector_transaction_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_id( conn: &PgPooledConn, id: &common_utils::id_type::GlobalAttemptId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::id.eq(id.to_owned()), ) .await } #[cfg(feature = "v2")] pub async fn find_by_payment_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::GlobalPaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()), None, None, Some(dsl::created_at.asc()), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_preprocessing_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, preprocessing_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::preprocessing_step_id.eq(preprocessing_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_payment_id_merchant_id_attempt_id( conn: &PgPooledConn, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, attempt_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::payment_id.eq(payment_id.to_owned()).and( dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::attempt_id.eq(attempt_id.to_owned())), ), ) .await } #[cfg(feature = "v1")] pub async fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as Table>::PrimaryKey, _, >( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::payment_id.eq(payment_id.to_owned())), None, None, None, ) .await } #[cfg(feature = "v1")] pub async fn get_filters_for_payments( conn: &PgPooledConn, pi: &[PaymentIntent], merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<( Vec<String>, Vec<enums::Currency>, Vec<IntentStatus>, Vec<enums::PaymentMethod>, Vec<enums::PaymentMethodType>, Vec<enums::AuthenticationType>, )> { let active_attempts: Vec<String> = pi .iter() .map(|payment_intent| payment_intent.clone().active_attempt_id) .collect(); let filter = <Self as HasTable>::table() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempts)); let intent_status: Vec<IntentStatus> = pi .iter() .map(|payment_intent| payment_intent.status) .collect::<HashSet<IntentStatus>>() .into_iter() .collect(); let filter_connector = filter .clone() .select(dsl::connector) .distinct() .get_results_async::<Option<String>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by connector")? .into_iter() .flatten() .collect::<Vec<String>>(); let filter_currency = filter .clone() .select(dsl::currency) .distinct() .get_results_async::<Option<enums::Currency>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by currency")? .into_iter() .flatten() .collect::<Vec<enums::Currency>>(); let filter_payment_method = filter .clone() .select(dsl::payment_method) .distinct() .get_results_async::<Option<enums::PaymentMethod>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethod>>(); let filter_payment_method_type = filter .clone() .select(dsl::payment_method_type) .distinct() .get_results_async::<Option<enums::PaymentMethodType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by payment method type")? .into_iter() .flatten() .collect::<Vec<enums::PaymentMethodType>>(); let filter_authentication_type = filter .clone() .select(dsl::authentication_type) .distinct() .get_results_async::<Option<enums::AuthenticationType>>(conn) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering records by authentication type")? .into_iter() .flatten() .collect::<Vec<enums::AuthenticationType>>(); Ok(( filter_connector, filter_currency, intent_status, filter_payment_method, filter_payment_method_type, filter_authentication_type, )) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method_type: Option<Vec<enums::PaymentMethod>>, payment_method_subtype: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connectors) = connector { filter = filter.filter(dsl::connector.eq_any(connectors)); } if let Some(payment_method_types) = payment_method_type { filter = filter.filter(dsl::payment_method_type_v2.eq_any(payment_method_types)); } if let Some(payment_method_subtypes) = payment_method_subtype { filter = filter.filter(dsl::payment_method_subtype.eq_any(payment_method_subtypes)); } if let Some(authentication_types) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_types)); } if let Some(merchant_connector_ids) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_ids)); } if let Some(card_networks) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_networks)); } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_total_count_of_attempts( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<String>>, payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<enums::CardNetwork>>, card_discovery: Option<Vec<enums::CardDiscovery>>, ) -> StorageResult<i64> { let mut filter = <Self as HasTable>::table() .count() .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } if let Some(payment_method) = payment_method { filter = filter.filter(dsl::payment_method.eq_any(payment_method)); } if let Some(payment_method_type) = payment_method_type { filter = filter.filter(dsl::payment_method_type.eq_any(payment_method_type)); } if let Some(authentication_type) = authentication_type { filter = filter.filter(dsl::authentication_type.eq_any(authentication_type)); } if let Some(merchant_connector_id) = merchant_connector_id { filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id)) } if let Some(card_network) = card_network { filter = filter.filter(dsl::card_network.eq_any(card_network)) } if let Some(card_discovery) = card_discovery { filter = filter.filter(dsl::card_discovery.eq_any(card_discovery)) } router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string()); // TODO: Remove these logs after debugging the issue for delay in count query let start_time = std::time::Instant::now(); router_env::logger::debug!("Executing count query start_time: {:?}", start_time); let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( filter.get_result_async::<i64>(conn), db_metrics::DatabaseOperation::Filter, ) .await .change_context(DatabaseError::Others) .attach_printable("Error filtering count of payments"); let duration = start_time.elapsed(); router_env::logger::debug!("Completed count query in {:?}", duration); result } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/query/payment_attempt.rs", "file_size": 20278, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-649364747495017461
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/merchant_account.rs // File size: 19256 bytes use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_account; #[cfg(feature = "v2")] use crate::schema_v2::merchant_account; /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v1")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { merchant_id: common_utils::id_type::MerchantId, 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 merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v1")] pub struct MerchantAccountSetter { pub merchant_id: common_utils::id_type::MerchantId, 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 merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: Some(item.merchant_id.clone()), merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, primary_business_details: item.primary_business_details, intent_fulfillment_time: item.intent_fulfillment_time, created_at: item.created_at, modified_at: item.modified_at, frm_routing_algorithm: item.frm_routing_algorithm, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: Some(item.merchant_account_type), } } } /// Note: The order of fields in the struct is important. /// This should be in the same order as the fields in the schema.rs file, otherwise the code will not compile /// If two adjacent columns have the same type, then the compiler will not throw any error, but the fields read / written will be interchanged #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Deserialize, Identifiable, serde::Serialize, Queryable, router_derive::DebugAsDisplay, Selectable, )] #[diesel(table_name = merchant_account, primary_key(id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: common_utils::id_type::MerchantId, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: Option<common_enums::MerchantAccountType>, } #[cfg(feature = "v2")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { id: item.id, merchant_name: item.merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, metadata: item.metadata, created_at: item.created_at, modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: Some(item.merchant_account_type), } } } #[cfg(feature = "v2")] pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: storage_enums::MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { #[cfg(feature = "v1")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.id } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_id: common_utils::id_type::MerchantId, pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub intent_fulfillment_time: Option<i64>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: storage_enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub id: Option<common_utils::id_type::MerchantId>, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountNew { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub id: common_utils::id_type::MerchantId, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub recon_status: Option<storage_enums::ReconStatus>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, publishable_key, storage_scheme, metadata, modified_at, organization_id, recon_status, is_platform_account, product_type, } = self; MerchantAccount { merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), metadata: metadata.or(source.metadata), created_at: source.created_at, modified_at, organization_id: organization_id.unwrap_or(source.organization_id), recon_status: recon_status.unwrap_or(source.recon_status), version: source.version, id: source.id, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), product_type: product_type.or(source.product_type), merchant_account_type: source.merchant_account_type, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_account)] pub struct MerchantAccountUpdateInternal { pub merchant_name: Option<Encryption>, pub merchant_details: Option<Encryption>, pub return_url: Option<String>, pub webhook_details: Option<crate::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, pub redirect_to_merchant_with_http_post: Option<bool>, pub publishable_key: Option<String>, pub storage_scheme: Option<storage_enums::MerchantStorageScheme>, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: Option<serde_json::Value>, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub frm_routing_algorithm: Option<serde_json::Value>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub is_recon_enabled: Option<bool>, pub default_profile: Option<Option<common_utils::id_type::ProfileId>>, pub recon_status: Option<storage_enums::ReconStatus>, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub is_platform_account: Option<bool>, pub product_type: Option<common_enums::MerchantProductType>, } #[cfg(feature = "v1")] impl MerchantAccountUpdateInternal { pub fn apply_changeset(self, source: MerchantAccount) -> MerchantAccount { let Self { merchant_name, merchant_details, return_url, webhook_details, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, storage_scheme, locker_id, metadata, routing_algorithm, primary_business_details, modified_at, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, organization_id, is_recon_enabled, default_profile, recon_status, payment_link_config, pm_collect_link_config, is_platform_account, product_type, } = self; MerchantAccount { merchant_id: source.merchant_id, return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), payment_response_hash_key: payment_response_hash_key .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), merchant_name: merchant_name.or(source.merchant_name), merchant_details: merchant_details.or(source.merchant_details), webhook_details: webhook_details.or(source.webhook_details), sub_merchants_enabled: sub_merchants_enabled.or(source.sub_merchants_enabled), parent_merchant_id: parent_merchant_id.or(source.parent_merchant_id), publishable_key: publishable_key.or(source.publishable_key), storage_scheme: storage_scheme.unwrap_or(source.storage_scheme), locker_id: locker_id.or(source.locker_id), metadata: metadata.or(source.metadata), routing_algorithm: routing_algorithm.or(source.routing_algorithm), primary_business_details: primary_business_details .unwrap_or(source.primary_business_details), intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), created_at: source.created_at, modified_at, frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), organization_id: organization_id.unwrap_or(source.organization_id), is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), default_profile: default_profile.unwrap_or(source.default_profile), recon_status: recon_status.unwrap_or(source.recon_status), payment_link_config: payment_link_config.or(source.payment_link_config), pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), version: source.version, is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), id: source.id, product_type: product_type.or(source.product_type), merchant_account_type: source.merchant_account_type, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/merchant_account.rs", "file_size": 19256, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-4832011483828889735
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/query/generics.rs // File size: 17727 bytes use std::fmt::Debug; use async_bb8_diesel::AsyncRunQueryDsl; use diesel::{ associations::HasTable, debug_query, dsl::{count_star, Find, IsNotNull, 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, SelectDsl}, LoadQuery, RunQueryDsl, }, result::Error as DieselError, Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table, }; use error_stack::{report, ResultExt}; use router_env::logger; use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult}; pub mod db_metrics { #[derive(Debug)] pub enum DatabaseOperation { FindOne, Filter, Update, Insert, Delete, DeleteWithResult, UpdateWithResults, UpdateOne, Count, } #[inline] pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U where Fut: std::future::Future<Output = U>, { let start = std::time::Instant::now(); let output = future.await; let time_elapsed = start.elapsed(); let table_name = std::any::type_name::<T>().rsplit("::").nth(1); let attributes = router_env::metric_attributes!( ("table", table_name.unwrap_or("undefined")), ("operation", format!("{:?}", operation)) ); crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes); crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes); output } } use db_metrics::*; pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R> where T: HasTable<Table = T> + Table + 'static + Debug, V: Debug + Insertable<T>, <T as QuerySource>::FromClause: QueryFragment<Pg> + Debug, <V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static, InsertStatement<T, <V as Insertable<T>>::Values>: AsQuery + LoadQuery<'static, PgConnection, R> + Send, R: Send + 'static, { let debug_values = format!("{values:?}"); let query = diesel::insert_into(<T as HasTable>::table()).values(values); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => { Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } .attach_printable_lazy(|| format!("Error while inserting {debug_values}")) } pub async fn generic_update<T, V, P>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<usize> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug, Filter<T, P>: IntoUpdateTarget, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update) .await .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")) } pub async fn generic_update_with_results<T, V, P, R>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<Vec<R>> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static, Filter<T, P>: IntoUpdateTarget + 'static, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone, R: Send + 'static, // For cloning query (UpdateStatement) <Filter<T, P> as HasTable>::Table: Clone, <Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values); match track_database_call::<T, _, _>( query.to_owned().get_results_async(conn), DatabaseOperation::UpdateWithResults, ) .await { Ok(result) => { logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); Ok(result) } Err(DieselError::QueryBuilderError(_)) => { Err(report!(errors::DatabaseError::NoFieldsToUpdate)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")) } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), Err(error) => Err(error) .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating {debug_values}")), } } pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>( conn: &PgPooledConn, predicate: P, values: V, ) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static, Filter<T, P>: IntoUpdateTarget + 'static, UpdateStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send, R: Send + 'static, // For cloning query (UpdateStatement) <Filter<T, P> as HasTable>::Table: Clone, <Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone, { generic_update_with_results::<<T as HasTable>::Table, _, _, _>(conn, predicate, values) .await .map(|mut vec_r| { if vec_r.is_empty() { Err(errors::DatabaseError::NotFound) } else if vec_r.len() != 1 { Err(errors::DatabaseError::Others) } else { vec_r.pop().ok_or(errors::DatabaseError::Others) } .attach_printable("Maybe not queried using a unique key") })? } pub async fn generic_update_by_id<T, V, Pk, R>( conn: &PgPooledConn, id: Pk, values: V, ) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug, Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, UpdateStatement< <Find<T, Pk> as HasTable>::Table, <Find<T, Pk> as IntoUpdateTarget>::WhereClause, <V as AsChangeset>::Changeset, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, Find<T, Pk>: LimitDsl, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, R: Send + 'static, Pk: Clone + Debug, // For cloning query (UpdateStatement) <Find<T, Pk> as HasTable>::Table: Clone, <Find<T, Pk> as IntoUpdateTarget>::WhereClause: Clone, <V as AsChangeset>::Changeset: Clone, <<Find<T, Pk> as HasTable>::Table as QuerySource>::FromClause: Clone, { let debug_values = format!("{values:?}"); let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values); match track_database_call::<T, _, _>( query.to_owned().get_result_async(conn), DatabaseOperation::UpdateOne, ) .await { Ok(result) => { logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); Ok(result) } Err(DieselError::QueryBuilderError(_)) => { Err(report!(errors::DatabaseError::NoFieldsToUpdate)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")) } Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound)) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), Err(error) => Err(error) .change_context(errors::DatabaseError::Others) .attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")), } } pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: IntoUpdateTarget, DeleteStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, >: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static, { let query = diesel::delete(<T as HasTable>::table().filter(predicate)); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting") .and_then(|result| match result { n if n > 0 => { logger::debug!("{n} records deleted"); Ok(true) } 0 => { Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted")) } _ => Ok(true), // n is usize, rustc requires this for exhaustive check }) } pub async fn generic_delete_one_with_result<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, Filter<T, P>: IntoUpdateTarget, DeleteStatement< <Filter<T, P> as HasTable>::Table, <Filter<T, P> as IntoUpdateTarget>::WhereClause, >: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static, R: Send + Clone + 'static, { let query = diesel::delete(<T as HasTable>::table().filter(predicate)); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); track_database_call::<T, _, _>( query.get_results_async(conn), DatabaseOperation::DeleteWithResult, ) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error while deleting") .and_then(|result| { result.first().cloned().ok_or_else(|| { report!(errors::DatabaseError::NotFound) .attach_printable("Object to be deleted does not exist") }) }) } async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { let query = <T as HasTable>::table().find(id.to_owned()); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } .attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}")) } pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>, Pk: Clone + Debug, R: Send + 'static, { generic_find_by_id_core::<T, _, _>(conn, id).await } 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) } 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") } 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 } 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) } pub(super) 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> + GetPrimaryKey + 'static, IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>> + FilterDsl<IsNotNull<T::PK>, 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) .filter(T::table().get_primary_key().is_not_null()); 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::Others) .attach_printable("Error filtering records by predicate") } pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize> where T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static, Filter<T, P>: SelectDsl<count_star>, diesel::dsl::Select<Filter<T, P>, count_star>: LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static, { let query = <T as HasTable>::table() .filter(predicate) .select(count_star()); logger::debug!(query = %debug_query::<Pg, _>(&query).to_string()); let count_i64: i64 = track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count) .await .change_context(errors::DatabaseError::Others) .attach_printable("Error counting records by predicate")?; let count_usize = usize::try_from(count_i64).map_err(|_| { report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize") })?; Ok(count_usize) } 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), }, } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/query/generics.rs", "file_size": 17727, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-2772300347371185767
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/user/sample_data.rs // File size: 15204 bytes #[cfg(feature = "v1")] use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; #[cfg(feature = "v1")] use common_utils::types::{ConnectorTransactionId, MinorUnit}; #[cfg(feature = "v1")] use serde::{Deserialize, Serialize}; #[cfg(feature = "v1")] use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::{ enums::{MandateDataType, MandateDetails}, schema::payment_attempt, ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptNew, }; // #[cfg(feature = "v2")] // #[derive( // Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, // )] // #[diesel(table_name = payment_attempt)] // pub struct PaymentAttemptBatchNew { // pub payment_id: common_utils::id_type::PaymentId, // pub merchant_id: common_utils::id_type::MerchantId, // pub status: AttemptStatus, // pub error_message: Option<String>, // pub surcharge_amount: Option<i64>, // pub tax_on_surcharge: Option<i64>, // pub payment_method_id: Option<String>, // pub authentication_type: Option<AuthenticationType>, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub created_at: PrimitiveDateTime, // #[serde(with = "common_utils::custom_serde::iso8601")] // pub modified_at: PrimitiveDateTime, // #[serde(default, with = "common_utils::custom_serde::iso8601::option")] // pub last_synced: Option<PrimitiveDateTime>, // pub cancellation_reason: Option<String>, // pub browser_info: Option<serde_json::Value>, // pub payment_token: Option<String>, // pub error_code: Option<String>, // pub connector_metadata: Option<serde_json::Value>, // pub payment_experience: Option<PaymentExperience>, // pub payment_method_data: Option<serde_json::Value>, // pub preprocessing_step_id: Option<String>, // pub error_reason: Option<String>, // pub connector_response_reference_id: Option<String>, // pub multiple_capture_count: Option<i16>, // pub amount_capturable: i64, // pub updated_by: String, // pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, // pub authentication_data: Option<serde_json::Value>, // pub encoded_data: Option<String>, // pub unified_code: Option<String>, // pub unified_message: Option<String>, // pub net_amount: Option<i64>, // pub external_three_ds_authentication_attempted: Option<bool>, // pub authentication_connector: Option<String>, // pub authentication_id: Option<String>, // pub fingerprint_id: Option<String>, // pub charge_id: Option<String>, // pub client_source: Option<String>, // pub client_version: Option<String>, // pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, // pub profile_id: common_utils::id_type::ProfileId, // pub organization_id: common_utils::id_type::OrganizationId, // } // #[cfg(feature = "v2")] // #[allow(dead_code)] // impl PaymentAttemptBatchNew { // // Used to verify compatibility with PaymentAttemptTable // fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { // // PaymentAttemptNew { // // payment_id: self.payment_id, // // merchant_id: self.merchant_id, // // status: self.status, // // error_message: self.error_message, // // surcharge_amount: self.surcharge_amount, // // tax_amount: self.tax_amount, // // payment_method_id: self.payment_method_id, // // confirm: self.confirm, // // authentication_type: self.authentication_type, // // created_at: self.created_at, // // modified_at: self.modified_at, // // last_synced: self.last_synced, // // cancellation_reason: self.cancellation_reason, // // browser_info: self.browser_info, // // payment_token: self.payment_token, // // error_code: self.error_code, // // connector_metadata: self.connector_metadata, // // payment_experience: self.payment_experience, // // card_network: self // // .payment_method_data // // .as_ref() // // .and_then(|data| data.as_object()) // // .and_then(|card| card.get("card")) // // .and_then(|v| v.as_object()) // // .and_then(|v| v.get("card_network")) // // .and_then(|network| network.as_str()) // // .map(|network| network.to_string()), // // payment_method_data: self.payment_method_data, // // straight_through_algorithm: self.straight_through_algorithm, // // preprocessing_step_id: self.preprocessing_step_id, // // error_reason: self.error_reason, // // multiple_capture_count: self.multiple_capture_count, // // connector_response_reference_id: self.connector_response_reference_id, // // amount_capturable: self.amount_capturable, // // updated_by: self.updated_by, // // merchant_connector_id: self.merchant_connector_id, // // authentication_data: self.authentication_data, // // encoded_data: self.encoded_data, // // unified_code: self.unified_code, // // unified_message: self.unified_message, // // net_amount: self.net_amount, // // external_three_ds_authentication_attempted: self // // .external_three_ds_authentication_attempted, // // authentication_connector: self.authentication_connector, // // authentication_id: self.authentication_id, // // payment_method_billing_address_id: self.payment_method_billing_address_id, // // fingerprint_id: self.fingerprint_id, // // charge_id: self.charge_id, // // client_source: self.client_source, // // client_version: self.client_version, // // customer_acceptance: self.customer_acceptance, // // profile_id: self.profile_id, // // organization_id: self.organization_id, // // } // todo!() // } // } #[cfg(feature = "v1")] #[derive( Clone, Debug, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, )] #[diesel(table_name = payment_attempt)] pub struct PaymentAttemptBatchNew { pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, pub status: AttemptStatus, pub amount: MinorUnit, pub currency: Option<Currency>, pub save_to_locker: Option<bool>, pub connector: Option<String>, pub error_message: Option<String>, pub offer_amount: Option<MinorUnit>, pub surcharge_amount: Option<MinorUnit>, pub tax_amount: Option<MinorUnit>, pub payment_method_id: Option<String>, pub payment_method: Option<PaymentMethod>, pub capture_method: Option<CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub confirm: bool, pub authentication_type: Option<AuthenticationType>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub cancellation_reason: Option<String>, pub amount_to_capture: Option<MinorUnit>, pub mandate_id: Option<String>, pub browser_info: Option<serde_json::Value>, pub payment_token: Option<String>, pub error_code: Option<String>, pub connector_metadata: Option<serde_json::Value>, pub payment_experience: Option<PaymentExperience>, pub payment_method_type: Option<PaymentMethodType>, pub payment_method_data: Option<serde_json::Value>, pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<ConnectorTransactionId>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub authentication_data: Option<serde_json::Value>, pub encoded_data: Option<String>, pub unified_code: Option<String>, pub unified_message: Option<String>, pub net_amount: Option<MinorUnit>, pub external_three_ds_authentication_attempted: Option<bool>, pub authentication_connector: Option<String>, pub authentication_id: Option<common_utils::id_type::AuthenticationId>, pub mandate_data: Option<MandateDetails>, pub payment_method_billing_address_id: Option<String>, pub fingerprint_id: Option<String>, pub charge_id: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, pub profile_id: common_utils::id_type::ProfileId, pub organization_id: common_utils::id_type::OrganizationId, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub processor_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, pub capture_before: Option<PrimitiveDateTime>, pub card_discovery: Option<common_enums::CardDiscovery>, pub processor_merchant_id: Option<common_utils::id_type::MerchantId>, pub created_by: Option<String>, pub setup_future_usage_applied: Option<common_enums::FutureUsage>, pub routing_approach: Option<common_enums::RoutingApproach>, pub connector_request_reference_id: Option<String>, pub network_transaction_id: Option<String>, pub network_details: Option<NetworkDetails>, pub is_stored_credential: Option<bool>, pub authorized_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[allow(dead_code)] impl PaymentAttemptBatchNew { // Used to verify compatibility with PaymentAttemptTable fn convert_into_normal_attempt_insert(self) -> PaymentAttemptNew { PaymentAttemptNew { payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, status: self.status, amount: self.amount, currency: self.currency, save_to_locker: self.save_to_locker, connector: self.connector, error_message: self.error_message, offer_amount: self.offer_amount, surcharge_amount: self.surcharge_amount, tax_amount: self.tax_amount, payment_method_id: self.payment_method_id, payment_method: self.payment_method, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, authentication_type: self.authentication_type, created_at: self.created_at, modified_at: self.modified_at, last_synced: self.last_synced, cancellation_reason: self.cancellation_reason, amount_to_capture: self.amount_to_capture, mandate_id: self.mandate_id, browser_info: self.browser_info, payment_token: self.payment_token, error_code: self.error_code, connector_metadata: self.connector_metadata, payment_experience: self.payment_experience, payment_method_type: self.payment_method_type, card_network: self .payment_method_data .as_ref() .and_then(|data| data.as_object()) .and_then(|card| card.get("card")) .and_then(|v| v.as_object()) .and_then(|v| v.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()), payment_method_data: self.payment_method_data, business_sub_label: self.business_sub_label, straight_through_algorithm: self.straight_through_algorithm, preprocessing_step_id: self.preprocessing_step_id, mandate_details: self.mandate_details, error_reason: self.error_reason, multiple_capture_count: self.multiple_capture_count, connector_response_reference_id: self.connector_response_reference_id, amount_capturable: self.amount_capturable, updated_by: self.updated_by, merchant_connector_id: self.merchant_connector_id, authentication_data: self.authentication_data, encoded_data: self.encoded_data, unified_code: self.unified_code, unified_message: self.unified_message, net_amount: self.net_amount, external_three_ds_authentication_attempted: self .external_three_ds_authentication_attempted, authentication_connector: self.authentication_connector, authentication_id: self.authentication_id, mandate_data: self.mandate_data, payment_method_billing_address_id: self.payment_method_billing_address_id, fingerprint_id: self.fingerprint_id, client_source: self.client_source, client_version: self.client_version, customer_acceptance: self.customer_acceptance, profile_id: self.profile_id, organization_id: self.organization_id, shipping_cost: self.shipping_cost, order_tax_amount: self.order_tax_amount, connector_mandate_detail: self.connector_mandate_detail, request_extended_authorization: self.request_extended_authorization, extended_authorization_applied: self.extended_authorization_applied, capture_before: self.capture_before, card_discovery: self.card_discovery, processor_merchant_id: self.processor_merchant_id, created_by: self.created_by, setup_future_usage_applied: self.setup_future_usage_applied, routing_approach: self.routing_approach, connector_request_reference_id: self.connector_request_reference_id, network_transaction_id: self.network_transaction_id, network_details: self.network_details, is_stored_credential: self.is_stored_credential, authorized_amount: self.authorized_amount, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/user/sample_data.rs", "file_size": 15204, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_1835119994305443024
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/merchant_connector_account.rs // File size: 13677 bytes #[cfg(feature = "v2")] use std::collections::HashMap; use std::fmt::Debug; use common_utils::{encryption::Encryption, id_type, pii}; #[cfg(feature = "v2")] use diesel::{sql_types::Jsonb, AsExpression}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::merchant_connector_account; #[cfg(feature = "v2")] use crate::schema_v2::merchant_connector_account; #[cfg(feature = "v1")] #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: String, pub connector_account_details: Encryption, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub connector_type: storage_enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub frm_configs: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: Option<id_type::ProfileId>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.merchant_connector_id.clone() } } #[cfg(feature = "v2")] use crate::RequiredFromNullable; #[cfg(feature = "v2")] #[derive( Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay, )] #[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: common_enums::connector_enums::Connector, pub connector_account_details: Encryption, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub connector_type: storage_enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = RequiredFromNullable<id_type::ProfileId>)] pub profile_id: id_type::ProfileId, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: id_type::MerchantConnectorAccountId, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.id.clone() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountNew { pub merchant_id: Option<id_type::MerchantId>, pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<String>, pub connector_account_details: Option<Encryption>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub frm_configs: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: Option<id_type::ProfileId>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: Option<id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountNew { pub merchant_id: Option<id_type::MerchantId>, pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<common_enums::connector_enums::Connector>, pub connector_account_details: Option<Encryption>, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, pub profile_id: id_type::ProfileId, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: storage_enums::ConnectorStatus, pub additional_merchant_data: Option<Encryption>, pub connector_wallets_details: Option<Encryption>, pub version: common_enums::ApiVersion, pub id: id_type::MerchantConnectorAccountId, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountUpdateInternal { pub connector_type: Option<storage_enums::ConnectorType>, pub connector_name: Option<String>, pub connector_account_details: Option<Encryption>, pub connector_label: Option<String>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub frm_configs: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: Option<time::PrimitiveDateTime>, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: Option<storage_enums::ConnectorStatus>, pub connector_wallets_details: Option<Encryption>, pub additional_merchant_data: Option<Encryption>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = merchant_connector_account)] pub struct MerchantConnectorAccountUpdateInternal { pub connector_type: Option<storage_enums::ConnectorType>, pub connector_account_details: Option<Encryption>, pub connector_label: Option<String>, pub disabled: Option<bool>, #[diesel(deserialize_as = super::OptionalDieselArray<common_types::payment_methods::PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: Option<time::PrimitiveDateTime>, pub connector_webhook_details: Option<pii::SecretSerdeValue>, #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)] pub frm_config: Option<Vec<pii::SecretSerdeValue>>, #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: Option<storage_enums::ConnectorStatus>, pub connector_wallets_details: Option<Encryption>, pub additional_merchant_data: Option<Encryption>, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v1")] impl MerchantConnectorAccountUpdateInternal { pub fn create_merchant_connector_account( self, source: MerchantConnectorAccount, ) -> MerchantConnectorAccount { MerchantConnectorAccount { merchant_id: source.merchant_id, connector_type: self.connector_type.unwrap_or(source.connector_type), connector_account_details: self .connector_account_details .unwrap_or(source.connector_account_details), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self .merchant_connector_id .unwrap_or(source.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, status: self.status.unwrap_or(source.status), ..source } } } #[cfg(feature = "v2")] impl MerchantConnectorAccountUpdateInternal { pub fn create_merchant_connector_account( self, source: MerchantConnectorAccount, ) -> MerchantConnectorAccount { MerchantConnectorAccount { connector_type: self.connector_type.unwrap_or(source.connector_type), connector_account_details: self .connector_account_details .unwrap_or(source.connector_account_details), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, status: self.status.unwrap_or(source.status), feature_metadata: self.feature_metadata, ..source } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression)] #[diesel(sql_type = Jsonb)] pub struct MerchantConnectorAccountFeatureMetadata { pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[cfg(feature = "v2")] common_utils::impl_to_sql_from_sql_json!(MerchantConnectorAccountFeatureMetadata); #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct RevenueRecoveryMetadata { /// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`.Once this limit is reached, no further retries will be attempted. pub max_retry_count: u16, /// Maximum number of `billing connector` retries before revenue recovery can start executing retries. pub billing_connector_retry_threshold: u16, /// Billing account reference id is payment gateway id at billing connector end. /// Merchants need to provide a mapping between these merchant connector account and the corresponding /// account reference IDs for each `billing connector`. pub billing_account_reference: BillingAccountReference, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct BillingAccountReference(pub HashMap<id_type::MerchantConnectorAccountId, String>);
{ "crate": "diesel_models", "file": "crates/diesel_models/src/merchant_connector_account.rs", "file_size": 13677, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-3812854741722855774
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/query/events.rs // File size: 11782 bytes use std::collections::HashSet; use diesel::{ associations::HasTable, BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, }; use super::generics; use crate::{ events::{Event, EventNew, EventUpdateInternal}, schema::events::dsl, PgPooledConn, StorageResult, }; impl EventNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Event> { generics::generic_insert(conn, self).await } } impl Event { pub async fn find_by_merchant_id_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::event_id.eq(event_id.to_owned())), ) .await } pub async fn find_by_merchant_id_idempotent_event_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::idempotent_event_id.eq(idempotent_event_id.to_owned())), ) .await } pub async fn list_initial_attempts_by_merchant_id_primary_object_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::merchant_id.eq(merchant_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } #[allow(clippy::too_many_arguments)] 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>, event_types: HashSet<common_enums::EventType>, 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, event_types, 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") } pub async fn list_by_merchant_id_initial_attempt_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::initial_attempt_id.eq(initial_attempt_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } pub async fn list_initial_attempts_by_profile_id_primary_object_id( conn: &PgPooledConn, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, ) -> StorageResult<Vec<Self>> { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, dsl::event_id .nullable() .eq(dsl::initial_attempt_id) // Filter initial attempts only .and(dsl::business_profile_id.eq(profile_id.to_owned())) .and(dsl::primary_object_id.eq(primary_object_id.to_owned())), None, None, Some(dsl::created_at.desc()), ) .await } #[allow(clippy::too_many_arguments)] 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>, event_types: HashSet<common_enums::EventType>, 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, event_types, 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") } 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 } 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 } 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>, event_types: HashSet<common_enums::EventType>, 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::EqAny<dsl::event_type, HashSet<common_enums::EventType>>, 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 !event_types.is_empty() { query = query.filter(dsl::event_type.eq_any(event_types)); } if let Some(is_delivered) = is_delivered { query = query.filter(dsl::is_overall_delivery_successful.eq(is_delivered)); } query } 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, event_types: HashSet<common_enums::EventType>, 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, event_types, 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") } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/query/events.rs", "file_size": 11782, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_-3658438736573738542
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/customers.rs // File size: 11638 bytes use common_enums::ApiVersion; use common_utils::{encryption::Encryption, pii, types::Description}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; #[cfg(feature = "v1")] use crate::schema::customers; #[cfg(feature = "v2")] use crate::{ diesel_impl::RequiredFromNullableWithDefault, enums::DeleteStatus, schema_v2::customers, }; #[cfg(feature = "v1")] #[derive( Clone, Debug, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, Insertable, )] #[diesel(table_name = customers)] pub struct CustomerNew { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v1")] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(feature = "v1")] impl From<CustomerNew> for Customer { fn from(customer_new: CustomerNew) -> Self { Self { customer_id: customer_new.customer_id, merchant_id: customer_new.merchant_id, name: customer_new.name, email: customer_new.email, phone: customer_new.phone, phone_country_code: customer_new.phone_country_code, description: customer_new.description, created_at: customer_new.created_at, metadata: customer_new.metadata, connector_customer: customer_new.connector_customer, modified_at: customer_new.modified_at, address_id: customer_new.address_id, default_payment_method_id: None, updated_by: customer_new.updated_by, version: customer_new.version, tax_registration_id: customer_new.tax_registration_id, } } } #[cfg(feature = "v2")] #[derive( Clone, Debug, Insertable, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers, primary_key(id))] pub struct CustomerNew { pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub status: DeleteStatus, pub id: common_utils::id_type::GlobalCustomerId, } #[cfg(feature = "v2")] impl CustomerNew { pub fn update_storage_scheme(&mut self, storage_scheme: common_enums::MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } } #[cfg(feature = "v2")] impl From<CustomerNew> for Customer { fn from(customer_new: CustomerNew) -> Self { Self { merchant_id: customer_new.merchant_id, name: customer_new.name, email: customer_new.email, phone: customer_new.phone, phone_country_code: customer_new.phone_country_code, description: customer_new.description, created_at: customer_new.created_at, metadata: customer_new.metadata, connector_customer: customer_new.connector_customer, modified_at: customer_new.modified_at, default_payment_method_id: None, updated_by: customer_new.updated_by, tax_registration_id: customer_new.tax_registration_id, merchant_reference_id: customer_new.merchant_reference_id, default_billing_address: customer_new.default_billing_address, default_shipping_address: customer_new.default_shipping_address, id: customer_new.id, version: customer_new.version, status: customer_new.status, } } } #[cfg(feature = "v1")] #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Customer { pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub default_payment_method_id: Option<String>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v2")] #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = customers, primary_key(id))] pub struct Customer { pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub version: ApiVersion, pub tax_registration_id: Option<Encryption>, pub merchant_reference_id: Option<common_utils::id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, #[diesel(deserialize_as = RequiredFromNullableWithDefault<DeleteStatus>)] pub status: DeleteStatus, pub id: common_utils::id_type::GlobalCustomerId, } #[cfg(feature = "v1")] #[derive( Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers)] pub struct CustomerUpdateInternal { pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<Option<String>>, pub updated_by: Option<String>, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v1")] impl CustomerUpdateInternal { pub fn apply_changeset(self, source: Customer) -> Customer { let Self { name, email, phone, description, phone_country_code, metadata, connector_customer, address_id, default_payment_method_id, tax_registration_id, .. } = self; Customer { name: name.map_or(source.name, Some), email: email.map_or(source.email, Some), phone: phone.map_or(source.phone, Some), description: description.map_or(source.description, Some), phone_country_code: phone_country_code.map_or(source.phone_country_code, Some), metadata: metadata.map_or(source.metadata, Some), modified_at: common_utils::date_time::now(), connector_customer: connector_customer.map_or(source.connector_customer, Some), address_id: address_id.map_or(source.address_id, Some), default_payment_method_id: default_payment_method_id .flatten() .map_or(source.default_payment_method_id, Some), tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some), ..source } } } #[cfg(feature = "v2")] #[derive( Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize, )] #[diesel(table_name = customers)] pub struct CustomerUpdateInternal { pub name: Option<Encryption>, pub email: Option<Encryption>, pub phone: Option<Encryption>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub default_payment_method_id: Option<Option<common_utils::id_type::GlobalPaymentMethodId>>, pub updated_by: Option<String>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub status: Option<DeleteStatus>, pub tax_registration_id: Option<Encryption>, } #[cfg(feature = "v2")] impl CustomerUpdateInternal { pub fn apply_changeset(self, source: Customer) -> Customer { let Self { name, email, phone, description, phone_country_code, metadata, connector_customer, default_payment_method_id, default_billing_address, default_shipping_address, status, tax_registration_id, .. } = self; Customer { name: name.map_or(source.name, Some), email: email.map_or(source.email, Some), phone: phone.map_or(source.phone, Some), description: description.map_or(source.description, Some), phone_country_code: phone_country_code.map_or(source.phone_country_code, Some), metadata: metadata.map_or(source.metadata, Some), modified_at: common_utils::date_time::now(), connector_customer: connector_customer.map_or(source.connector_customer, Some), default_payment_method_id: default_payment_method_id .flatten() .map_or(source.default_payment_method_id, Some), default_billing_address: default_billing_address .map_or(source.default_billing_address, Some), default_shipping_address: default_shipping_address .map_or(source.default_shipping_address, Some), status: status.unwrap_or(source.status), tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some), ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/customers.rs", "file_size": 11638, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_9176363614523537677
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/kv.rs // File size: 11479 bytes use error_stack::ResultExt; use serde::{Deserialize, Serialize}; #[cfg(feature = "v2")] use crate::payment_attempt::PaymentAttemptUpdateInternal; #[cfg(feature = "v1")] use crate::payment_intent::PaymentIntentUpdate; #[cfg(feature = "v2")] use crate::payment_intent::PaymentIntentUpdateInternal; use crate::{ address::{Address, AddressNew, AddressUpdateInternal}, customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate}, payment_intent::PaymentIntentNew, payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate}, payouts::{Payouts, PayoutsNew, PayoutsUpdate}, refund::{Refund, RefundNew, RefundUpdate}, reverse_lookup::{ReverseLookup, ReverseLookupNew}, Mandate, MandateNew, MandateUpdateInternal, PaymentIntent, PaymentMethod, PaymentMethodNew, PaymentMethodUpdateInternal, PgPooledConn, }; #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "db_op", content = "data")] pub enum DBOperation { Insert { insertable: Box<Insertable> }, Update { updatable: Box<Updateable> }, } impl DBOperation { pub fn operation<'a>(&self) -> &'a str { match self { Self::Insert { .. } => "insert", Self::Update { .. } => "update", } } pub fn table<'a>(&self) -> &'a str { match self { Self::Insert { insertable } => match **insertable { Insertable::PaymentIntent(_) => "payment_intent", Insertable::PaymentAttempt(_) => "payment_attempt", Insertable::Refund(_) => "refund", Insertable::Address(_) => "address", Insertable::Payouts(_) => "payouts", Insertable::PayoutAttempt(_) => "payout_attempt", Insertable::Customer(_) => "customer", Insertable::ReverseLookUp(_) => "reverse_lookup", Insertable::PaymentMethod(_) => "payment_method", Insertable::Mandate(_) => "mandate", }, Self::Update { updatable } => match **updatable { Updateable::PaymentIntentUpdate(_) => "payment_intent", Updateable::PaymentAttemptUpdate(_) => "payment_attempt", Updateable::RefundUpdate(_) => "refund", Updateable::CustomerUpdate(_) => "customer", Updateable::AddressUpdate(_) => "address", Updateable::PayoutsUpdate(_) => "payouts", Updateable::PayoutAttemptUpdate(_) => "payout_attempt", Updateable::PaymentMethodUpdate(_) => "payment_method", Updateable::MandateUpdate(_) => " mandate", }, } } } #[derive(Debug)] pub enum DBResult { PaymentIntent(Box<PaymentIntent>), PaymentAttempt(Box<PaymentAttempt>), Refund(Box<Refund>), Address(Box<Address>), Customer(Box<Customer>), ReverseLookUp(Box<ReverseLookup>), Payouts(Box<Payouts>), PayoutAttempt(Box<PayoutAttempt>), PaymentMethod(Box<PaymentMethod>), Mandate(Box<Mandate>), } #[derive(Debug, Serialize, Deserialize)] pub struct TypedSql { #[serde(flatten)] pub op: DBOperation, } impl DBOperation { pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> { Ok(match self { Self::Insert { insertable } => match *insertable { Insertable::PaymentIntent(a) => { DBResult::PaymentIntent(Box::new(a.insert(conn).await?)) } Insertable::PaymentAttempt(a) => { DBResult::PaymentAttempt(Box::new(a.insert(conn).await?)) } Insertable::Refund(a) => DBResult::Refund(Box::new(a.insert(conn).await?)), Insertable::Address(addr) => DBResult::Address(Box::new(addr.insert(conn).await?)), Insertable::Customer(cust) => { DBResult::Customer(Box::new(cust.insert(conn).await?)) } Insertable::ReverseLookUp(rev) => { DBResult::ReverseLookUp(Box::new(rev.insert(conn).await?)) } Insertable::Payouts(rev) => DBResult::Payouts(Box::new(rev.insert(conn).await?)), Insertable::PayoutAttempt(rev) => { DBResult::PayoutAttempt(Box::new(rev.insert(conn).await?)) } Insertable::PaymentMethod(rev) => { DBResult::PaymentMethod(Box::new(rev.insert(conn).await?)) } Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)), }, Self::Update { updatable } => match *updatable { #[cfg(feature = "v1")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] Updateable::PaymentIntentUpdate(a) => { DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v1")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v2")] Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v1")] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update(conn, a.update_data).await?)) } #[cfg(feature = "v2")] Updateable::RefundUpdate(a) => { DBResult::Refund(Box::new(a.orig.update_with_id(conn, a.update_data).await?)) } Updateable::AddressUpdate(a) => { DBResult::Address(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutsUpdate(a) => { DBResult::Payouts(Box::new(a.orig.update(conn, a.update_data).await?)) } Updateable::PayoutAttemptUpdate(a) => DBResult::PayoutAttempt(Box::new( a.orig.update_with_attempt_id(conn, a.update_data).await?, )), #[cfg(feature = "v1")] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig .update_with_payment_method_id(conn, v.update_data) .await?, )), #[cfg(feature = "v2")] Updateable::PaymentMethodUpdate(v) => DBResult::PaymentMethod(Box::new( v.orig.update_with_id(conn, v.update_data).await?, )), Updateable::MandateUpdate(m) => DBResult::Mandate(Box::new( Mandate::update_by_merchant_id_mandate_id( conn, &m.orig.merchant_id, &m.orig.mandate_id, m.update_data, ) .await?, )), #[cfg(feature = "v1")] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_customer_id_merchant_id( conn, cust.orig.customer_id.clone(), cust.orig.merchant_id.clone(), cust.update_data, ) .await?, )), #[cfg(feature = "v2")] Updateable::CustomerUpdate(cust) => DBResult::Customer(Box::new( Customer::update_by_id(conn, cust.orig.id, cust.update_data).await?, )), }, }) } } impl TypedSql { pub fn to_field_value_pairs( &self, request_id: String, global_id: String, ) -> crate::StorageResult<Vec<(&str, String)>> { let pushed_at = common_utils::date_time::now_unix_timestamp(); Ok(vec![ ( "typed_sql", serde_json::to_string(self) .change_context(errors::DatabaseError::QueryGenerationFailed)?, ), ("global_id", global_id), ("request_id", request_id), ("pushed_at", pushed_at.to_string()), ]) } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Insertable { PaymentIntent(Box<PaymentIntentNew>), PaymentAttempt(Box<PaymentAttemptNew>), Refund(RefundNew), Address(Box<AddressNew>), Customer(CustomerNew), ReverseLookUp(ReverseLookupNew), Payouts(PayoutsNew), PayoutAttempt(PayoutAttemptNew), PaymentMethod(PaymentMethodNew), Mandate(MandateNew), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "table", content = "data")] pub enum Updateable { PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), RefundUpdate(Box<RefundUpdateMems>), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), PayoutAttemptUpdate(PayoutAttemptUpdateMems), PaymentMethodUpdate(Box<PaymentMethodUpdateMems>), MandateUpdate(MandateUpdateMems), } #[derive(Debug, Serialize, Deserialize)] pub struct CustomerUpdateMems { pub orig: Customer, pub update_data: CustomerUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct AddressUpdateMems { pub orig: Address, pub update_data: AddressUpdateInternal, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentIntentUpdateMems { pub orig: PaymentIntent, pub update_data: PaymentIntentUpdateInternal, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Serialize, Deserialize)] pub struct PaymentAttemptUpdateMems { pub orig: PaymentAttempt, pub update_data: PaymentAttemptUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct RefundUpdateMems { pub orig: Refund, pub update_data: RefundUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutsUpdateMems { pub orig: Payouts, pub update_data: PayoutsUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PayoutAttemptUpdateMems { pub orig: PayoutAttempt, pub update_data: PayoutAttemptUpdate, } #[derive(Debug, Serialize, Deserialize)] pub struct PaymentMethodUpdateMems { pub orig: PaymentMethod, pub update_data: PaymentMethodUpdateInternal, } #[derive(Debug, Serialize, Deserialize)] pub struct MandateUpdateMems { pub orig: Mandate, pub update_data: MandateUpdateInternal, }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/kv.rs", "file_size": 11479, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_5340258921857602876
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/query/user_role.rs // File size: 11320 bytes use async_bb8_diesel::AsyncRunQueryDsl; 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 error_stack::{report, ResultExt}; use crate::{ enums::{UserRoleVersion, UserStatus}, errors, query::generics, schema::user_roles::dsl, user_role::*, PgPooledConn, StorageResult, }; impl UserRoleNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> { generics::generic_insert(conn, self).await } } impl UserRole { 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)), ), ) } 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 } #[allow(clippy::too_many_arguments)] 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 } 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 } #[allow(clippy::too_many_arguments)] pub async fn generic_user_roles_list_for_user( conn: &PgPooledConn, user_id: String, tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, entity_id: Option<String>, status: Option<UserStatus>, version: Option<UserRoleVersion>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(org_id) = org_id { query = query.filter(dsl::org_id.eq(org_id)); } if let Some(merchant_id) = merchant_id { query = query.filter(dsl::merchant_id.eq(merchant_id)); } if let Some(profile_id) = profile_id { query = query.filter(dsl::profile_id.eq(profile_id)); } if let Some(entity_id) = entity_id { query = query.filter(dsl::entity_id.eq(entity_id)); } if let Some(version) = version { query = query.filter(dsl::version.eq(version)); } if let Some(status) = status { query = query.filter(dsl::status.eq(status)); } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } #[allow(clippy::too_many_arguments)] pub async fn generic_user_roles_list_for_org_and_extra( conn: &PgPooledConn, user_id: Option<String>, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, version: Option<UserRoleVersion>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(user_id) = user_id { query = query.filter(dsl::user_id.eq(user_id)); } if let Some(merchant_id) = merchant_id { query = query.filter(dsl::merchant_id.eq(merchant_id)); } if let Some(profile_id) = profile_id { query = query.filter(dsl::profile_id.eq(profile_id)); } if let Some(version) = version { query = query.filter(dsl::version.eq(version)); } if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } pub async fn list_user_roles_by_user_id_across_tenants( conn: &PgPooledConn, user_id: String, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::user_id.eq(user_id)) .into_boxed(); if let Some(limit) = limit { query = query.limit(limit.into()); } router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( query.get_results_async(conn), generics::db_metrics::DatabaseOperation::Filter, ) .await { Ok(value) => Ok(value), Err(err) => match err { DieselError::NotFound => { Err(report!(err)).change_context(errors::DatabaseError::NotFound) } _ => Err(report!(err)).change_context(errors::DatabaseError::Others), }, } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/query/user_role.rs", "file_size": 11320, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_2372389477799517788
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/process_tracker.rs // File size: 11221 bytes pub use common_enums::{enums::ProcessTrackerRunner, ApiVersion}; use common_utils::ext_traits::Encode; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult}; #[derive( Clone, Debug, Eq, PartialEq, Deserialize, Identifiable, Queryable, Selectable, Serialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))] pub struct ProcessTracker { pub id: String, pub name: Option<String>, #[diesel(deserialize_as = super::DieselArray<String>)] pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, #[diesel(deserialize_as = super::DieselArray<String>)] pub event: Vec<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTracker { #[inline(always)] pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { valid_statuses.iter().any(|&x| x == self.business_status) } } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerNew { pub id: String, pub name: Option<String>, pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, pub event: Vec<String>, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTrackerNew { #[allow(clippy::too_many_arguments)] 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, }) } } #[derive(Debug)] 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, }, } #[derive(Debug, Clone, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerUpdateInternal { 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>, } impl Default for ProcessTrackerUpdateInternal { 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()), } } } impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal { 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() }, } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use common_utils::ext_traits::StringExt; use super::ProcessTrackerRunner; #[test] 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); } } pub mod business_status { /// Indicates that an irrecoverable error occurred during the workflow execution. pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE"; /// Task successfully completed by consumer. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT"; /// An error occurred during the workflow execution which prevents further execution and /// retries. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const FAILURE: &str = "FAILURE"; /// The resource associated with the task was removed, due to which further retries can/should /// not be done. pub const REVOKED: &str = "Revoked"; /// The task was executed for the maximum possible number of times without a successful outcome. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED"; /// The outgoing webhook was successfully delivered in the initial attempt. /// Further retries of the task are not required. pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL"; /// Indicates that an error occurred during the workflow execution. /// This status is typically set by the workflow error handler. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR"; /// The resource associated with the task has been significantly modified since the task was /// created, due to which further retries of the current task are not required. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH"; /// Business status set for newly created tasks. pub const PENDING: &str = "Pending"; /// For the PCR Workflow /// /// This status indicates the completion of a execute task pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK"; /// This status indicates the failure of a execute task pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_EXECUTE_TASK"; /// This status indicates that the execute task was completed to trigger the psync task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC"; /// This status indicates that the execute task was completed to trigger the review task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for execute task pub const EXECUTE_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_EXECUTE_WORKFLOW"; /// This status indicates the completion of a psync task pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK"; /// This status indicates that the psync task was completed to trigger the review task pub const PSYNC_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_PSYNC_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for psync task pub const PSYNC_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_PSYNC_WORKFLOW"; /// This status indicates the completion of a review task pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK"; /// For the CALCULATE_WORKFLOW /// /// This status indicates an invoice is queued pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED"; /// This status indicates an invoice has been declined due to hard decline pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR"; /// This status indicates that the invoice is scheduled with the best available token pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED"; /// This status indicates the invoice is in payment sync state pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING"; /// This status indicates the workflow has completed successfully when the invoice is paid pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE"; }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/process_tracker.rs", "file_size": 11221, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_3337723180026984993
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/query/customers.rs // File size: 11205 bytes use common_utils::id_type; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; #[cfg(feature = "v1")] use crate::schema::customers::dsl; #[cfg(feature = "v2")] use crate::schema_v2::customers::dsl; use crate::{ customers::{Customer, CustomerNew, CustomerUpdateInternal}, errors, PgPooledConn, StorageResult, }; impl CustomerNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> { generics::generic_insert(conn, self).await } } pub struct CustomerListConstraints { pub limit: i64, pub offset: Option<i64>, pub customer_id: Option<id_type::CustomerId>, pub time_range: Option<common_utils::types::TimeRange>, } impl Customer { #[cfg(feature = "v2")] pub async fn update_by_id( conn: &PgPooledConn, id: id_type::GlobalCustomerId, customer: CustomerUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, id.clone(), customer, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await } _ => Err(error), }, result => result, } } #[cfg(feature = "v2")] pub async fn find_by_global_id( conn: &PgPooledConn, id: &id_type::GlobalCustomerId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await } #[cfg(feature = "v1")] pub async fn get_customer_count_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, customer_list_constraints: CustomerListConstraints, ) -> StorageResult<usize> { if let Some(customer_id) = customer_list_constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::customer_id.eq(customer_id)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else if let Some(time_range) = customer_list_constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else { generics::generic_count::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } } #[cfg(feature = "v2")] pub async fn get_customer_count_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, customer_list_constraints: CustomerListConstraints, ) -> StorageResult<usize> { if let Some(customer_id) = customer_list_constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::merchant_reference_id.eq(customer_id)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else if let Some(time_range) = customer_list_constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await } else { generics::generic_count::<<Self as HasTable>::Table, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()), ) .await } } #[cfg(feature = "v1")] pub async fn list_customers_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { if let Some(customer_id) = constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::customer_id.eq(customer_id)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else if let Some(time_range) = constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else { let predicate = dsl::merchant_id.eq(merchant_id.clone()); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } } #[cfg(feature = "v2")] pub async fn list_customers_by_merchant_id_and_constraints( conn: &PgPooledConn, merchant_id: &id_type::MerchantId, constraints: CustomerListConstraints, ) -> StorageResult<Vec<Self>> { if let Some(customer_id) = constraints.customer_id { let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::merchant_reference_id.eq(customer_id)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else if let Some(time_range) = constraints.time_range { let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let predicate = dsl::merchant_id .eq(merchant_id.clone()) .and(dsl::created_at.between(start_time, end_time)); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } else { let predicate = dsl::merchant_id.eq(merchant_id.clone()); generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>( conn, predicate, Some(constraints.limit), constraints.offset, Some(dsl::created_at), ) .await } } #[cfg(feature = "v2")] pub async fn find_optional_by_merchant_id_merchant_reference_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(customer_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_optional_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Option<Self>> { generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>( conn, (customer_id.to_owned(), merchant_id.to_owned()), ) .await } #[cfg(feature = "v1")] pub async fn update_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: CustomerUpdateInternal, ) -> StorageResult<Self> { match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>( conn, (customer_id.clone(), merchant_id.clone()), customer, ) .await { Err(error) => match error.current_context() { errors::DatabaseError::NoFieldsToUpdate => { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, (customer_id, merchant_id), ) .await } _ => Err(error), }, result => result, } } #[cfg(feature = "v1")] pub async fn delete_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<bool> { generics::generic_delete::<<Self as HasTable>::Table, _>( conn, dsl::customer_id .eq(customer_id.to_owned()) .and(dsl::merchant_id.eq(merchant_id.to_owned())), ) .await } #[cfg(feature = "v2")] pub async fn find_by_merchant_reference_id_merchant_id( conn: &PgPooledConn, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::merchant_id .eq(merchant_id.to_owned()) .and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())), ) .await } #[cfg(feature = "v1")] pub async fn find_by_customer_id_merchant_id( conn: &PgPooledConn, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>( conn, (customer_id.to_owned(), merchant_id.to_owned()), ) .await } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/query/customers.rs", "file_size": 11205, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_7063426453582926996
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/payout_attempt.rs // File size: 10608 bytes use common_utils::{ payout_method_utils, pii, types::{UnifiedCode, UnifiedMessage}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::payout_attempt}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = payout_attempt, primary_key(payout_attempt_id), check_for_backend(diesel::pg::Pg))] pub struct PayoutAttempt { pub payout_attempt_id: String, pub payout_id: common_utils::id_type::PayoutId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive( Clone, Debug, Eq, PartialEq, Insertable, serde::Serialize, serde::Deserialize, router_derive::DebugAsDisplay, router_derive::Setter, )] #[diesel(table_name = payout_attempt)] pub struct PayoutAttemptNew { pub payout_attempt_id: String, pub payout_id: common_utils::id_type::PayoutId, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_id: common_utils::id_type::MerchantId, pub address_id: Option<String>, pub connector: Option<String>, pub connector_payout_id: Option<String>, pub payout_token: Option<String>, pub status: storage_enums::PayoutStatus, pub is_eligible: Option<bool>, pub error_message: Option<String>, pub error_code: Option<String>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub last_modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum PayoutAttemptUpdate { StatusUpdate { connector_payout_id: Option<String>, status: storage_enums::PayoutStatus, error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, unified_code: Option<UnifiedCode>, unified_message: Option<UnifiedMessage>, payout_connector_metadata: Option<pii::SecretSerdeValue>, }, PayoutTokenUpdate { payout_token: String, }, BusinessUpdate { business_country: Option<storage_enums::CountryAlpha2>, business_label: Option<String>, address_id: Option<String>, customer_id: Option<common_utils::id_type::CustomerId>, }, UpdateRouting { connector: String, routing_info: Option<serde_json::Value>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, AdditionalPayoutMethodDataUpdate { additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, }, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = payout_attempt)] pub struct PayoutAttemptUpdateInternal { pub payout_token: Option<String>, pub connector_payout_id: Option<String>, pub status: Option<storage_enums::PayoutStatus>, pub error_message: Option<String>, pub error_code: Option<String>, pub is_eligible: Option<bool>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub connector: Option<String>, pub routing_info: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, pub address_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub unified_code: Option<UnifiedCode>, pub unified_message: Option<UnifiedMessage>, pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>, pub merchant_order_reference_id: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } impl Default for PayoutAttemptUpdateInternal { 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, merchant_order_reference_id: None, payout_connector_metadata: None, } } } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { 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, payout_connector_metadata, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, unified_code, unified_message, payout_connector_metadata, ..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() }, } } } impl PayoutAttemptUpdate { 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, merchant_order_reference_id, payout_connector_metadata, } = 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), merchant_order_reference_id: merchant_order_reference_id .or(source.merchant_order_reference_id), payout_connector_metadata: payout_connector_metadata .or(source.payout_connector_metadata), ..source } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/payout_attempt.rs", "file_size": 10608, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_diesel_models_2747615680753680263
clm
file
// Repository: hyperswitch // Crate: diesel_models // File: crates/diesel_models/src/mandate.rs // File size: 10097 bytes use common_enums::MerchantStorageScheme; use common_utils::pii; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::mandate}; #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))] pub struct Mandate { pub mandate_id: String, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub mandate_status: storage_enums::MandateStatus, pub mandate_type: storage_enums::MandateType, pub customer_accepted_at: Option<PrimitiveDateTime>, pub customer_ip_address: Option<Secret<String, pii::IpAddress>>, pub customer_user_agent: Option<String>, pub network_transaction_id: Option<String>, pub previous_attempt_id: Option<String>, pub created_at: PrimitiveDateTime, pub mandate_amount: Option<i64>, pub mandate_currency: Option<storage_enums::Currency>, pub amount_captured: Option<i64>, pub connector: String, pub connector_mandate_id: Option<String>, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_ids: Option<pii::SecretSerdeValue>, pub original_payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub updated_by: Option<String>, // This is the extended version of customer user agent that can store string upto 2048 characters unlike customer user agent that can store 255 characters at max pub customer_user_agent_extended: Option<String>, } #[derive( router_derive::Setter, Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate)] pub struct MandateNew { pub mandate_id: String, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, pub mandate_status: storage_enums::MandateStatus, pub mandate_type: storage_enums::MandateType, pub customer_accepted_at: Option<PrimitiveDateTime>, pub customer_ip_address: Option<Secret<String, pii::IpAddress>>, pub customer_user_agent: Option<String>, pub network_transaction_id: Option<String>, pub previous_attempt_id: Option<String>, pub created_at: Option<PrimitiveDateTime>, pub mandate_amount: Option<i64>, pub mandate_currency: Option<storage_enums::Currency>, pub amount_captured: Option<i64>, pub connector: String, pub connector_mandate_id: Option<String>, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_ids: Option<pii::SecretSerdeValue>, pub original_payment_id: Option<common_utils::id_type::PaymentId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub updated_by: Option<String>, pub customer_user_agent_extended: Option<String>, } impl Mandate { /// Returns customer_user_agent_extended with customer_user_agent as fallback pub fn get_user_agent_extended(&self) -> Option<String> { self.customer_user_agent_extended .clone() .or_else(|| self.customer_user_agent.clone()) } } impl MandateNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } /// Returns customer_user_agent_extended with customer_user_agent as fallback pub fn get_customer_user_agent_extended(&self) -> Option<String> { self.customer_user_agent_extended .clone() .or_else(|| self.customer_user_agent.clone()) } } #[derive(Debug)] pub enum MandateUpdate { StatusUpdate { mandate_status: storage_enums::MandateStatus, }, CaptureAmountUpdate { amount_captured: Option<i64>, }, ConnectorReferenceUpdate { connector_mandate_ids: Option<pii::SecretSerdeValue>, }, ConnectorMandateIdUpdate { connector_mandate_id: Option<String>, connector_mandate_ids: Option<pii::SecretSerdeValue>, payment_method_id: String, original_payment_id: Option<common_utils::id_type::PaymentId>, }, } impl MandateUpdate { 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 } } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: i64, pub currency: storage_enums::Currency, } #[derive( Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay, serde::Serialize, serde::Deserialize, )] #[diesel(table_name = mandate)] 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>, } impl From<MandateUpdate> for MandateUpdateInternal { 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() }, } } } impl MandateUpdateInternal { 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 } } } impl From<&MandateNew> for Mandate { 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: None, 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(), // Using customer_user_agent as a fallback customer_user_agent_extended: mandate_new.get_customer_user_agent_extended(), } } }
{ "crate": "diesel_models", "file": "crates/diesel_models/src/mandate.rs", "file_size": 10097, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_5041368882750483366
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/router_data.rs // File size: 85608 bytes use std::{collections::HashMap, marker::PhantomData}; use common_types::{payments as common_payment_types, primitive_wrappers}; use common_utils::{ errors::IntegrityCheckError, ext_traits::{OptionExt, ValueExt}, id_type::{self}, types::MinorUnit, }; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ address::AddressDetails, network_tokenization::NetworkTokenNumber, payment_address::PaymentAddress, payment_method_data, payments, }; #[cfg(feature = "v2")] use crate::{ payments::{ payment_attempt::{ErrorDetails, PaymentAttemptUpdate}, payment_intent::PaymentIntentUpdate, }, router_flow_types, router_request_types, router_response_types, }; #[derive(Debug, Clone, Serialize)] pub struct RouterData<Flow, Request, Response> { pub flow: PhantomData<Flow>, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub connector_customer: Option<String>, pub connector: String, // TODO: This should be a PaymentId type. // Make this change after all the connector dependency has been removed from connectors pub payment_id: String, pub attempt_id: String, pub tenant_id: id_type::TenantId, pub status: common_enums::enums::AttemptStatus, pub payment_method: common_enums::enums::PaymentMethod, pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, pub connector_auth_type: ConnectorAuthType, pub description: Option<String>, pub address: PaymentAddress, pub auth_type: common_enums::enums::AuthenticationType, pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>, pub amount_captured: Option<i64>, pub access_token: Option<AccessToken>, pub session_token: Option<String>, pub reference_id: Option<String>, pub payment_method_token: Option<PaymentMethodToken>, pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub preprocessing_id: Option<String>, /// This is the balance amount for gift cards or voucher pub payment_method_balance: Option<PaymentMethodBalance>, ///for switching between two different versions of the same connector pub connector_api_version: Option<String>, /// Contains flow-specific data required to construct a request and send it to the connector. pub request: Request, /// Contains flow-specific data that the connector responds with. pub response: Result<Response, ErrorResponse>, /// Contains a reference ID that should be sent in the connector request pub connector_request_reference_id: String, #[cfg(feature = "payouts")] /// Contains payout method data pub payout_method_data: Option<api_models::payouts::PayoutMethodData>, #[cfg(feature = "payouts")] /// Contains payout's quote ID pub quote_id: Option<String>, pub test_mode: Option<bool>, pub connector_http_status_code: Option<u16>, pub external_latency: Option<u128>, /// Contains apple pay flow type simplified or manual pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>, pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>, pub dispute_id: Option<String>, pub refund_id: Option<String>, /// This field is used to store various data regarding the response from connector pub connector_response: Option<ConnectorResponseData>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, // minor amount for amount framework pub minor_amount_captured: Option<MinorUnit>, pub minor_amount_capturable: Option<MinorUnit>, // stores the authorized amount in case of partial authorization pub authorized_amount: Option<MinorUnit>, pub integrity_check: Result<(), IntegrityCheckError>, pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>, pub header_payload: Option<payments::HeaderPayload>, pub connector_mandate_request_reference_id: Option<String>, pub l2_l3_data: Option<Box<L2L3Data>>, pub authentication_id: Option<id_type::AuthenticationId>, /// Contains the type of sca exemption required for the transaction pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Contains stringified connector raw response body pub raw_connector_response: Option<Secret<String>>, /// Indicates whether the payment ID was provided by the merchant (true), /// or generated internally by Hyperswitch (false) pub is_payment_id_from_merchant: Option<bool>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct L2L3Data { pub order_date: Option<time::PrimitiveDateTime>, pub tax_status: Option<common_enums::TaxStatus>, pub customer_tax_registration_id: Option<Secret<String>>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, pub discount_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub merchant_order_reference_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub billing_address_city: Option<String>, pub merchant_tax_registration_id: Option<Secret<String>>, pub customer_email: Option<common_utils::pii::Email>, pub customer_name: Option<Secret<String>>, pub customer_phone_number: Option<Secret<String>>, pub customer_phone_country_code: Option<String>, pub shipping_details: Option<AddressDetails>, } impl L2L3Data { pub fn get_shipping_country(&self) -> Option<common_enums::enums::CountryAlpha2> { self.shipping_details .as_ref() .and_then(|address| address.country) } pub fn get_shipping_city(&self) -> Option<String> { self.shipping_details .as_ref() .and_then(|address| address.city.clone()) } pub fn get_shipping_state(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.state.clone()) } pub fn get_shipping_origin_zip(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.origin_zip.clone()) } pub fn get_shipping_zip(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.zip.clone()) } pub fn get_shipping_address_line1(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.line1.clone()) } pub fn get_shipping_address_line2(&self) -> Option<Secret<String>> { self.shipping_details .as_ref() .and_then(|address| address.line2.clone()) } } // Different patterns of authentication. #[derive(Default, Debug, Clone, Deserialize, Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, HeaderKey { api_key: Secret<String>, }, BodyKey { api_key: Secret<String>, key1: Secret<String>, }, SignatureKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, }, MultiAuthKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, key2: Secret<String>, }, CurrencyAuthKey { auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>, }, CertificateAuth { certificate: Secret<String>, private_key: Secret<String>, }, #[default] NoKey, } impl ConnectorAuthType { pub fn from_option_secret_value( value: Option<common_utils::pii::SecretSerdeValue>, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorAuthType") .change_context(common_utils::errors::ParsingError::StructParseFailure( "ConnectorAuthType", )) } pub fn from_secret_value( value: common_utils::pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorAuthType") .change_context(common_utils::errors::ParsingError::StructParseFailure( "ConnectorAuthType", )) } // show only first and last two digits of the key and mask others with * // mask the entire key if it's length is less than or equal to 4 fn mask_key(&self, key: String) -> Secret<String> { let key_len = key.len(); let masked_key = if key_len <= 4 { "*".repeat(key_len) } else { // Show the first two and last two characters, mask the rest with '*' let mut masked_key = String::new(); let key_len = key.len(); // Iterate through characters by their index for (index, character) in key.chars().enumerate() { if index < 2 || index >= key_len - 2 { masked_key.push(character); // Keep the first two and last two characters } else { masked_key.push('*'); // Mask the middle characters } } masked_key }; Secret::new(masked_key) } // Mask the keys in the auth_type pub fn get_masked_keys(&self) -> Self { match self { Self::TemporaryAuth => Self::TemporaryAuth, Self::NoKey => Self::NoKey, Self::HeaderKey { api_key } => Self::HeaderKey { api_key: self.mask_key(api_key.clone().expose()), }, Self::BodyKey { api_key, key1 } => Self::BodyKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), }, Self::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), api_secret: self.mask_key(api_secret.clone().expose()), }, Self::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key: self.mask_key(api_key.clone().expose()), key1: self.mask_key(key1.clone().expose()), api_secret: self.mask_key(api_secret.clone().expose()), key2: self.mask_key(key2.clone().expose()), }, Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey { auth_key_map: auth_key_map.clone(), }, Self::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate: self.mask_key(certificate.clone().expose()), private_key: self.mask_key(private_key.clone().expose()), }, } } } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessTokenAuthenticationResponse { pub code: Secret<String>, pub expires: i64, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct AccessToken { pub token: Secret<String>, pub expires: i64, } #[derive(Debug, Clone, Deserialize, Serialize)] pub enum PaymentMethodToken { Token(Secret<String>), ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>), GooglePayDecrypt(Box<common_payment_types::GPayPredecryptData>), PazeDecrypt(Box<PazeDecryptedData>), } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayPredecryptDataInternal { pub application_primary_account_number: cards::CardNumber, pub application_expiration_date: String, pub currency_code: String, pub transaction_amount: i64, pub device_manufacturer_identifier: Secret<String>, pub payment_data_type: Secret<String>, pub payment_data: ApplePayCryptogramDataInternal, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayCryptogramDataInternal { pub online_payment_cryptogram: Secret<String>, pub eci_indicator: Option<String>, } impl TryFrom<ApplePayPredecryptDataInternal> for common_payment_types::ApplePayPredecryptData { type Error = common_utils::errors::ValidationError; fn try_from(data: ApplePayPredecryptDataInternal) -> Result<Self, Self::Error> { let application_expiration_month = data.clone().get_expiry_month()?; let application_expiration_year = data.clone().get_four_digit_expiry_year()?; Ok(Self { application_primary_account_number: data.application_primary_account_number.clone(), application_expiration_month, application_expiration_year, payment_data: data.payment_data.into(), }) } } impl From<GooglePayPredecryptDataInternal> for common_payment_types::GPayPredecryptData { fn from(data: GooglePayPredecryptDataInternal) -> Self { Self { card_exp_month: Secret::new(data.payment_method_details.expiration_month.two_digits()), card_exp_year: Secret::new(data.payment_method_details.expiration_year.four_digits()), application_primary_account_number: data.payment_method_details.pan.clone(), cryptogram: data.payment_method_details.cryptogram.clone(), eci_indicator: data.payment_method_details.eci_indicator.clone(), } } } impl From<ApplePayCryptogramDataInternal> for common_payment_types::ApplePayCryptogramData { fn from(payment_data: ApplePayCryptogramDataInternal) -> Self { Self { online_payment_cryptogram: payment_data.online_payment_cryptogram, eci_indicator: payment_data.eci_indicator, } } } impl ApplePayPredecryptDataInternal { /// This logic being applied as apple pay provides application_expiration_date in the YYMMDD format fn get_four_digit_expiry_year( &self, ) -> Result<Secret<String>, common_utils::errors::ValidationError> { Ok(Secret::new(format!( "20{}", self.application_expiration_date.get(0..2).ok_or( common_utils::errors::ValidationError::InvalidValue { message: "Invalid two-digit year".to_string(), } )? ))) } fn get_expiry_month(&self) -> Result<Secret<String>, common_utils::errors::ValidationError> { Ok(Secret::new( self.application_expiration_date .get(2..4) .ok_or(common_utils::errors::ValidationError::InvalidValue { message: "Invalid two-digit month".to_string(), })? .to_owned(), )) } } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPredecryptDataInternal { pub message_expiration: String, pub message_id: String, #[serde(rename = "paymentMethod")] pub payment_method_type: String, pub payment_method_details: GooglePayPaymentMethodDetails, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentMethodDetails { pub auth_method: common_enums::enums::GooglePayAuthMethod, pub expiration_month: cards::CardExpirationMonth, pub expiration_year: cards::CardExpirationYear, pub pan: cards::CardNumber, pub cryptogram: Option<Secret<String>>, pub eci_indicator: Option<String>, pub card_network: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDecryptedData { pub client_id: Secret<String>, pub profile_id: String, pub token: PazeToken, pub payment_card_network: common_enums::enums::CardNetwork, pub dynamic_data: Vec<PazeDynamicData>, pub billing_address: PazeAddress, pub consumer: PazeConsumer, pub eci: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeToken { pub payment_token: NetworkTokenNumber, pub token_expiration_month: Secret<String>, pub token_expiration_year: Secret<String>, pub payment_account_reference: Secret<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeDynamicData { pub dynamic_data_value: Option<Secret<String>>, pub dynamic_data_type: Option<String>, pub dynamic_data_expiration: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeAddress { pub name: Option<Secret<String>>, pub line1: Option<Secret<String>>, pub line2: Option<Secret<String>>, pub line3: Option<Secret<String>>, pub city: Option<Secret<String>>, pub state: Option<Secret<String>>, pub zip: Option<Secret<String>>, pub country_code: Option<common_enums::enums::CountryAlpha2>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazeConsumer { // This is consumer data not customer data. pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub full_name: Secret<String>, pub email_address: common_utils::pii::Email, pub mobile_number: Option<PazePhoneNumber>, pub country_code: Option<common_enums::enums::CountryAlpha2>, pub language_code: Option<String>, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PazePhoneNumber { pub country_code: Secret<String>, pub phone_number: Secret<String>, } #[derive(Debug, Default, Clone, Serialize)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::enums::Currency>, pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentMethodBalance { pub amount: MinorUnit, pub currency: common_enums::enums::Currency, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConnectorResponseData { pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>, extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>, is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, } impl ConnectorResponseData { pub fn with_additional_payment_method_data( additional_payment_method_data: AdditionalPaymentMethodConnectorResponse, ) -> Self { Self { additional_payment_method_data: Some(additional_payment_method_data), extended_authorization_response_data: None, is_overcapture_enabled: None, } } pub fn new( additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>, is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>, extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>, ) -> Self { Self { additional_payment_method_data, extended_authorization_response_data, is_overcapture_enabled, } } pub fn get_extended_authorization_response_data( &self, ) -> Option<&ExtendedAuthorizationResponseData> { self.extended_authorization_response_data.as_ref() } pub fn is_overcapture_enabled(&self) -> Option<primitive_wrappers::OvercaptureEnabledBool> { self.is_overcapture_enabled } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum AdditionalPaymentMethodConnectorResponse { Card { /// Details regarding the authentication details of the connector, if this is a 3ds payment. authentication_data: Option<serde_json::Value>, /// Various payment checks that are done for a payment payment_checks: Option<serde_json::Value>, /// Card Network returned by the processor card_network: Option<String>, /// Domestic(Co-Branded) Card network returned by the processor domestic_network: Option<String>, }, PayLater { klarna_sdk: Option<KlarnaSdkResponse>, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExtendedAuthorizationResponseData { pub extended_authentication_applied: Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>, pub capture_before: Option<time::PrimitiveDateTime>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KlarnaSdkResponse { pub payment_type: Option<String>, } #[derive(Clone, Debug, Serialize)] pub struct ErrorResponse { pub code: String, pub message: String, pub reason: Option<String>, pub status_code: u16, pub attempt_status: Option<common_enums::enums::AttemptStatus>, pub connector_transaction_id: Option<String>, pub network_decline_code: Option<String>, pub network_advice_code: Option<String>, pub network_error_message: Option<String>, pub connector_metadata: Option<Secret<serde_json::Value>>, } impl Default for ErrorResponse { fn default() -> Self { Self { code: "HE_00".to_string(), message: "Something went wrong".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } } } impl ErrorResponse { pub fn get_not_implemented() -> Self { Self { code: "IR_00".to_string(), message: "This API is under development and will be made available soon.".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), attempt_status: None, connector_transaction_id: None, network_decline_code: None, network_advice_code: None, network_error_message: None, connector_metadata: None, } } } /// Get updatable trakcer objects of payment intent and payment attempt #[cfg(feature = "v2")] pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> { fn get_payment_intent_update( &self, payment_data: &D, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate; fn get_payment_attempt_update( &self, payment_data: &D, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate; /// Get the amount that can be captured for the payment fn get_amount_capturable(&self, payment_data: &D) -> Option<MinorUnit>; /// Get the amount that has been captured for the payment fn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>; /// Get the attempt status based on parameters like captured amount and amount capturable fn get_attempt_status_for_db_update( &self, payment_data: &D, ) -> common_enums::enums::AttemptStatus; } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Authorize, router_request_types::PaymentsAuthorizeData, payments::PaymentConfirmData<router_flow_types::Authorize>, > for RouterData< router_flow_types::Authorize, router_request_types::PaymentsAuthorizeData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); let updated_feature_metadata = payment_data .payment_intent .feature_metadata .clone() .map(|mut feature_metadata| { if let Some(ref mut payment_revenue_recovery_metadata) = feature_metadata.payment_revenue_recovery_metadata { payment_revenue_recovery_metadata.payment_connector_transmission = if self .response .is_ok() { common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded } else { common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful }; } Box::new(feature_metadata) }); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: updated_feature_metadata, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: updated_feature_metadata, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, connector_response_reference_id, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: connector_response_reference_id .clone(), }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_capturable_from_intent_status = match intent_status { // If the status is already succeeded / failed we cannot capture any more amount // So set the amount capturable to zero common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, // If status is requires capture, get the total amount that can be captured // This is in cases where the capture method will be `manual` or `manual_multiple` // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow common_enums::IntentStatus::RequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow, after doing authorization this state is invalid common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_capturable .or(amount_capturable_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); let amount_captured_from_intent_status = match intent_status { // If the status is succeeded then we have captured the whole amount // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // No amount has been captured yet common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Some(MinorUnit::zero()) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_captured .or(amount_captured_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Capture, router_request_types::PaymentsCaptureData, payments::PaymentCaptureData<router_flow_types::Capture>, > for RouterData< router_flow_types::Capture, router_request_types::PaymentsCaptureData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), }, Err(ref error) => PaymentIntentUpdate::CaptureUpdate { status: error .attempt_status .map(common_enums::IntentStatus::from) .unwrap_or(common_enums::IntentStatus::Failed), amount_captured, updated_by: storage_scheme.to_string(), }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.status; PaymentAttemptUpdate::CaptureUpdate { status: attempt_status, amount_capturable, updated_by: storage_scheme.to_string(), } } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is already succeeded / failed we cannot capture any more amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is succeeded then we have captured the whole amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let amount_to_capture = payment_data .payment_attempt .amount_details .get_amount_to_capture(); let amount_captured = amount_to_capture .unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount()); Some(amount_captured) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => { todo!() } } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::PSync, router_request_types::PaymentsSyncData, payments::PaymentStatusData<router_flow_types::PSync>, > for RouterData< router_flow_types::PSync, router_request_types::PaymentsSyncData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::SyncUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), }, Err(ref error) => PaymentIntentUpdate::SyncUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 200..=299 => common_enums::enums::AttemptStatus::Failure, _ => self.status, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); PaymentAttemptUpdate::SyncUpdate { status: attempt_status, amount_capturable, updated_by: storage_scheme.to_string(), } } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 200..=299 => common_enums::enums::AttemptStatus::Failure, _ => self.status, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> common_enums::AttemptStatus { match self.status { common_enums::AttemptStatus::Charged => { let amount_captured = self .get_captured_amount(payment_data) .unwrap_or(MinorUnit::zero()); let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); if amount_captured == total_amount { common_enums::AttemptStatus::Charged } else { common_enums::AttemptStatus::PartialCharged } } _ => self.status, } } fn get_amount_capturable( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_capturable_from_intent_status = match intent_status { // If the status is already succeeded / failed we cannot capture any more amount common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCaptured => { let total_amount = payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_capturable .or(amount_capturable_from_intent_status) } fn get_captured_amount( &self, payment_data: &payments::PaymentStatusData<router_flow_types::PSync>, ) -> Option<MinorUnit> { let payment_attempt = &payment_data.payment_attempt; // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); let amount_captured_from_intent_status = match intent_status { // If the status is succeeded then we have captured the whole amount or amount_to_capture common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let amount_to_capture = payment_attempt.amount_details.get_amount_to_capture(); let amount_captured = amount_to_capture.unwrap_or(payment_attempt.amount_details.get_net_amount()); Some(amount_captured) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, }; self.minor_amount_captured .or(amount_captured_from_intent_status) .or(Some(payment_data.payment_attempt.get_total_amount())) } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::ExternalVaultProxy, router_request_types::ExternalVaultProxyPaymentsData, payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, > for RouterData< router_flow_types::ExternalVaultProxy, router_request_types::ExternalVaultProxyPaymentsData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: { let attempt_status = match error.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; common_enums::IntentStatus::from(attempt_status) }, amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, connector_response_reference_id, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: connector_response_reference_id .clone(), }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata, } = error_response.clone(); let attempt_status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::enums::AttemptStatus::Pending, _ => common_enums::enums::AttemptStatus::Failure, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> common_enums::AttemptStatus { // For this step, consider whatever status was given by the connector module // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount self.status } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::Failed | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()), common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::SetupMandate, router_request_types::SetupMandateRequestData, payments::PaymentConfirmData<router_flow_types::SetupMandate>, > for RouterData< router_flow_types::SetupMandate, router_request_types::SetupMandateRequestData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let amount_captured = self.get_captured_amount(payment_data); match self.response { Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: common_enums::IntentStatus::from( self.get_attempt_status_for_db_update(payment_data), ), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate { status: error .attempt_status .map(common_enums::IntentStatus::from) .unwrap_or(common_enums::IntentStatus::Failed), amount_captured, updated_by: storage_scheme.to_string(), feature_metadata: None, }, } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { let amount_capturable = self.get_amount_capturable(payment_data); match self.response { Ok(ref response_router_data) => match response_router_data { router_response_types::PaymentsResponseData::TransactionResponse { resource_id, redirection_data, connector_metadata, .. } => { let attempt_status = self.get_attempt_status_for_db_update(payment_data); let connector_payment_id = match resource_id { router_request_types::ResponseId::NoResponseId => None, router_request_types::ResponseId::ConnectorTransactionId(id) | router_request_types::ResponseId::EncodedData(id) => Some(id.to_owned()), }; PaymentAttemptUpdate::ConfirmIntentResponse(Box::new( payments::payment_attempt::ConfirmIntentResponseUpdate { status: attempt_status, connector_payment_id, updated_by: storage_scheme.to_string(), redirection_data: *redirection_data.clone(), amount_capturable, connector_metadata: connector_metadata.clone().map(Secret::new), connector_token_details: response_router_data .get_updated_connector_token_details( payment_data .payment_attempt .connector_token_details .as_ref() .and_then(|token_details| { token_details.get_connector_token_request_reference_id() }), ), connector_response_reference_id: None, }, )) } router_response_types::PaymentsResponseData::MultipleCaptureResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::SessionResponse { .. } => todo!(), router_response_types::PaymentsResponseData::SessionTokenResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TransactionUnresolvedResponse { .. } => todo!(), router_response_types::PaymentsResponseData::TokenizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ConnectorCustomerResponse { .. } => todo!(), router_response_types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PreProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => todo!(), router_response_types::PaymentsResponseData::PostProcessingResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => { todo!() } router_response_types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => todo!(), }, Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status, connector_transaction_id, network_advice_code, network_decline_code, network_error_message, connector_metadata: _, } = error_response.clone(); let attempt_status = attempt_status.unwrap_or(self.status); let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status: attempt_status, error: error_details, amount_capturable, connector_payment_id: connector_transaction_id, updated_by: storage_scheme.to_string(), } } } } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> common_enums::AttemptStatus { // For this step, consider whatever status was given by the connector module // We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount self.status } fn get_amount_capturable( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount capturable let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is already succeeded / failed we cannot capture any more amount // So set the amount capturable to zero common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the capturable amount when it reaches terminal / capturable state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // If status is requires capture, get the total amount that can be captured // This is in cases where the capture method will be `manual` or `manual_multiple` // We do not need to handle the case where amount_to_capture is provided here as it cannot be passed in authroize flow common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // Invalid statues for this flow, after doing authorization this state is invalid common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } fn get_captured_amount( &self, payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>, ) -> Option<MinorUnit> { // Based on the status of the response, we can determine the amount that was captured let intent_status = common_enums::IntentStatus::from(self.status); match intent_status { // If the status is succeeded then we have captured the whole amount // we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supported common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => { let total_amount = payment_data.payment_attempt.amount_details.get_net_amount(); Some(total_amount) } // No amount is captured common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired => Some(MinorUnit::zero()), // For these statuses, update the amount captured when it reaches terminal state common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::Processing => None, // Invalid states for this flow common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation => None, // No amount has been captured yet common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => { Some(MinorUnit::zero()) } // Invalid statues for this flow common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } #[cfg(feature = "v2")] impl TrackerPostUpdateObjects< router_flow_types::Void, router_request_types::PaymentsCancelData, payments::PaymentCancelData<router_flow_types::Void>, > for RouterData< router_flow_types::Void, router_request_types::PaymentsCancelData, router_response_types::PaymentsResponseData, > { fn get_payment_intent_update( &self, payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentIntentUpdate { let intent_status = common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data)); PaymentIntentUpdate::VoidUpdate { status: intent_status, updated_by: storage_scheme.to_string(), } } fn get_payment_attempt_update( &self, payment_data: &payments::PaymentCancelData<router_flow_types::Void>, storage_scheme: common_enums::MerchantStorageScheme, ) -> PaymentAttemptUpdate { match &self.response { Err(ref error_response) => { let ErrorResponse { code, message, reason, status_code: _, attempt_status: _, connector_transaction_id, network_decline_code, network_advice_code, network_error_message, connector_metadata: _, } = error_response.clone(); // Handle errors exactly let status = match error_response.attempt_status { // Use the status sent by connector in error_response if it's present Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::AttemptStatus::Pending, _ => common_enums::AttemptStatus::VoidFailed, }, }; let error_details = ErrorDetails { code, message, reason, unified_code: None, unified_message: None, network_advice_code, network_decline_code, network_error_message, }; PaymentAttemptUpdate::ErrorUpdate { status, amount_capturable: Some(MinorUnit::zero()), error: error_details, updated_by: storage_scheme.to_string(), connector_payment_id: connector_transaction_id, } } Ok(ref _response) => PaymentAttemptUpdate::VoidUpdate { status: self.status, cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(), updated_by: storage_scheme.to_string(), }, } } fn get_amount_capturable( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> Option<MinorUnit> { // For void operations, no amount is capturable Some(MinorUnit::zero()) } fn get_captured_amount( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> Option<MinorUnit> { // For void operations, no amount is captured Some(MinorUnit::zero()) } fn get_attempt_status_for_db_update( &self, _payment_data: &payments::PaymentCancelData<router_flow_types::Void>, ) -> common_enums::AttemptStatus { // For void operations, determine status based on response match &self.response { Err(ref error_response) => match error_response.attempt_status { Some(status) => status, None => match error_response.status_code { 500..=511 => common_enums::AttemptStatus::Pending, _ => common_enums::AttemptStatus::VoidFailed, }, }, Ok(ref _response) => self.status, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/router_data.rs", "file_size": 85608, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-8338838494061444050
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/router_request_types.rs // File size: 56590 bytes pub mod authentication; pub mod fraud_check; pub mod revenue_recovery; pub mod subscriptions; pub mod unified_authentication_service; use api_models::payments::{AdditionalPaymentData, AddressDetails, RequestSurchargeDetails}; use common_types::payments as common_payments_types; use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit}; use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount}; use error_stack::ResultExt; use masking::Secret; use serde::Serialize; use serde_with::serde_as; use super::payment_method_data::PaymentMethodData; use crate::{ address, errors::api_error_response::{ApiErrorResponse, NotImplementedMessage}, mandates, payment_method_data::ExternalVaultPaymentMethodData, payments, router_data::{self, AccessTokenAuthenticationResponse, RouterData}, router_flow_types as flows, router_response_types as response_types, vault::PaymentMethodVaultingData, }; #[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthorizeData { pub payment_method_data: PaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ```text /// get_original_amount() /// get_surcharge_amount() /// get_tax_on_surcharge_amount() /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount /// ``` pub amount: i64, pub order_tax_amount: Option<MinorUnit>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_mandate_details: Option<mandates::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub order_category: Option<String>, pub session_token: Option<String>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, pub request_extended_authorization: Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_amount: MinorUnit, /// 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. pub merchant_order_reference_id: Option<String>, pub integrity_object: Option<AuthoriseIntegrityObject>, pub shipping_cost: Option<MinorUnit>, pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub order_id: Option<String>, pub locale: Option<String>, pub payment_channel: Option<common_enums::PaymentChannel>, pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>, pub is_stored_credential: Option<bool>, pub mit_category: Option<common_enums::MitCategory>, } #[derive(Debug, Clone, Serialize)] pub struct ExternalVaultProxyPaymentsData { pub payment_method_data: ExternalVaultPaymentMethodData, /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ```text /// get_original_amount() /// get_surcharge_amount() /// get_tax_on_surcharge_amount() /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount /// ``` pub amount: i64, pub order_tax_amount: Option<MinorUnit>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_mandate_details: Option<mandates::MandateData>, pub browser_info: Option<BrowserInformation>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub order_category: Option<String>, pub session_token: Option<String>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, pub payment_experience: Option<storage_enums::PaymentExperience>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub surcharge_details: Option<SurchargeDetails>, pub customer_id: Option<id_type::CustomerId>, pub request_incremental_authorization: bool, pub metadata: Option<serde_json::Value>, pub authentication_data: Option<AuthenticationData>, pub request_extended_authorization: Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_amount: MinorUnit, /// 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. pub merchant_order_reference_id: Option<id_type::PaymentReferenceId>, pub integrity_object: Option<AuthoriseIntegrityObject>, pub shipping_cost: Option<MinorUnit>, pub additional_payment_method_data: Option<AdditionalPaymentData>, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub order_id: Option<String>, } // Note: Integrity traits for ExternalVaultProxyPaymentsData are not implemented // as they are not mandatory for this flow. The integrity_check field in RouterData // will use Ok(()) as default, similar to other flows. // Implement ConnectorCustomerData conversion for ExternalVaultProxy RouterData impl TryFrom< &RouterData< flows::ExternalVaultProxy, ExternalVaultProxyPaymentsData, response_types::PaymentsResponseData, >, > for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::ExternalVaultProxy, ExternalVaultProxyPaymentsData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: None, // External vault proxy doesn't use regular payment method data description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), customer_id: None, billing_address: None, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostSessionTokensData { // amount here would include amount, surcharge_amount and shipping_cost pub amount: MinorUnit, /// original amount sent by the merchant pub order_amount: MinorUnit, pub currency: storage_enums::Currency, pub capture_method: Option<storage_enums::CaptureMethod>, /// 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. pub merchant_order_reference_id: Option<String>, pub shipping_cost: Option<MinorUnit>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub router_return_url: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentsUpdateMetadataData { pub metadata: pii::SecretSerdeValue, pub connector_transaction_id: String, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct AuthoriseIntegrityObject { /// Authorise amount pub amount: MinorUnit, /// Authorise currency pub currency: storage_enums::Currency, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SyncIntegrityObject { /// Sync amount pub amount: Option<MinorUnit>, /// Sync currency pub currency: Option<storage_enums::Currency>, } #[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsCaptureData { pub amount_to_capture: i64, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub payment_amount: i64, pub multiple_capture_data: Option<MultipleCaptureRequestData>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. pub capture_method: Option<storage_enums::CaptureMethod>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, pub minor_amount_to_capture: MinorUnit, pub integrity_object: Option<CaptureIntegrityObject>, pub webhook_url: Option<String>, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct CaptureIntegrityObject { /// capture amount pub capture_amount: Option<MinorUnit>, /// capture currency pub currency: storage_enums::Currency, } #[derive(Debug, Clone, Default, Serialize)] pub struct PaymentsIncrementalAuthorizationData { pub total_amount: i64, pub additional_amount: i64, pub currency: storage_enums::Currency, pub reason: Option<String>, pub connector_transaction_id: String, pub connector_meta: Option<serde_json::Value>, } #[derive(Debug, Clone, Default, Serialize)] pub struct MultipleCaptureRequestData { pub capture_sequence: i16, pub capture_reference: String, } #[derive(Debug, Clone, Serialize)] pub struct AuthorizeSessionTokenData { pub amount_to_capture: Option<i64>, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub amount: Option<i64>, } #[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerData { pub description: Option<String>, pub email: Option<pii::Email>, pub phone: Option<Secret<String>>, pub name: Option<Secret<String>>, pub preprocessing_id: Option<String>, pub payment_method_data: Option<PaymentMethodData>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub customer_id: Option<id_type::CustomerId>, pub billing_address: Option<AddressDetails>, } impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { email: data.email, payment_method_data: Some(data.payment_method_data), description: None, phone: None, name: None, preprocessing_id: None, split_payments: None, setup_future_usage: data.setup_future_usage, customer_acceptance: data.customer_acceptance, customer_id: None, billing_address: None, }) } } impl TryFrom<SetupMandateRequestData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: data.amount, minor_amount: data.minor_amount, email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: None, router_return_url: data.router_return_url, webhook_url: data.webhook_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: None, mandate_id: data.mandate_id, related_transaction_id: None, redirect_response: None, enrolled_for_3ds: false, split_payments: None, metadata: data.metadata, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } impl TryFrom< &RouterData<flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData>, > for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: Some(data.request.payment_method_data.clone()), description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: data.request.split_payments.clone(), setup_future_usage: data.request.setup_future_usage, customer_acceptance: data.request.customer_acceptance.clone(), customer_id: None, billing_address: None, }) } } impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::PaymentsResponseData>> for ConnectorCustomerData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: &RouterData< flows::Session, PaymentsSessionData, response_types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { Ok(Self { email: data.request.email.clone(), payment_method_data: None, description: None, phone: None, name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), split_payments: None, setup_future_usage: None, customer_acceptance: None, customer_id: None, billing_address: None, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentMethodTokenizationData { pub payment_method_data: PaymentMethodData, pub browser_info: Option<BrowserInformation>, pub currency: storage_enums::Currency, pub amount: Option<i64>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub setup_mandate_details: Option<mandates::MandateData>, pub mandate_id: Option<api_models::payments::MandateIds>, } impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, browser_info: None, currency: data.currency, amount: data.amount, split_payments: None, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> for PaymentMethodTokenizationData { fn from( data: &RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, ) -> Self { Self { payment_method_data: data.request.payment_method_data.clone(), browser_info: None, currency: data.request.currency, amount: Some(data.request.amount), split_payments: data.request.split_payments.clone(), customer_acceptance: data.request.customer_acceptance.clone(), setup_future_usage: data.request.setup_future_usage, setup_mandate_details: data.request.setup_mandate_details.clone(), mandate_id: data.request.mandate_id.clone(), } } } impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, browser_info: data.browser_info, currency: data.currency, amount: Some(data.amount), split_payments: data.split_payments.clone(), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data .payment_method_data .get_required_value("payment_method_data") .change_context(ApiErrorResponse::MissingRequiredField { field_name: "payment_method_data", })?, browser_info: data.browser_info, currency: data.currency, amount: Some(data.amount), split_payments: None, customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, setup_mandate_details: data.setup_mandate_details, mandate_id: data.mandate_id, }) } } impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(_data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> { // TODO: External vault proxy payments should not use regular payment method tokenization // This needs to be implemented separately for external vault flows Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason( "External vault proxy tokenization not implemented".to_string(), ), } .into()) } } #[derive(Debug, Clone, Serialize)] pub struct CreateOrderRequestData { pub minor_amount: MinorUnit, pub currency: storage_enums::Currency, } impl TryFrom<PaymentsAuthorizeData> for CreateOrderRequestData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { minor_amount: data.minor_amount, currency: data.currency, }) } } impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> { Ok(Self { minor_amount: data.minor_amount, currency: data.currency, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPreProcessingData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub setup_mandate_details: Option<mandates::MandateData>, pub capture_method: Option<storage_enums::CaptureMethod>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub complete_authorize_url: Option<String>, pub surcharge_details: Option<SurchargeDetails>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub mandate_id: Option<api_models::payments::MandateIds>, pub related_transaction_id: Option<String>, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, pub metadata: Option<Secret<serde_json::Value>>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub setup_future_usage: Option<storage_enums::FutureUsage>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone, Serialize)] pub struct GiftCardBalanceCheckRequestData { pub payment_method_data: PaymentMethodData, pub currency: Option<storage_enums::Currency>, pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: data.order_details, router_return_url: data.router_return_url, webhook_url: data.webhook_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: data.surcharge_details, connector_transaction_id: None, mandate_id: data.mandate_id, related_transaction_id: data.related_transaction_id, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, split_payments: data.split_payments, metadata: data.metadata.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPreAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostAuthenticateData { pub payment_method_data: Option<PaymentMethodData>, pub amount: Option<i64>, pub email: Option<pii::Email>, pub currency: Option<storage_enums::Currency>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub router_return_url: Option<String>, pub complete_authorize_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub enrolled_for_3ds: bool, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, // New amount for amount frame work pub minor_amount: Option<MinorUnit>, } impl TryFrom<PaymentsAuthorizeData> for PaymentsPostAuthenticateData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: Some(data.payment_method_data), amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: data.payment_method_type, router_return_url: data.router_return_url, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, connector_transaction_id: None, redirect_response: None, enrolled_for_3ds: data.enrolled_for_3ds, }) } } impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.payment_method_data, amount: Some(data.amount), minor_amount: Some(data.minor_amount), email: data.email, currency: Some(data.currency), payment_method_type: None, setup_mandate_details: data.setup_mandate_details, capture_method: data.capture_method, order_details: None, router_return_url: None, webhook_url: None, complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: data.connector_transaction_id, mandate_id: data.mandate_id, related_transaction_id: None, redirect_response: data.redirect_response, split_payments: None, enrolled_for_3ds: true, metadata: data.connector_meta.map(Secret::new), customer_acceptance: data.customer_acceptance, setup_future_usage: data.setup_future_usage, is_stored_credential: data.is_stored_credential, }) } } #[derive(Debug, Clone, Serialize)] pub struct PaymentsPostProcessingData { pub payment_method_data: PaymentMethodData, pub customer_id: Option<id_type::CustomerId>, pub connector_transaction_id: Option<String>, pub country: Option<common_enums::CountryAlpha2>, pub connector_meta_data: Option<pii::SecretSerdeValue>, pub header_payload: Option<payments::HeaderPayload>, } impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> for PaymentsPostProcessingData { type Error = error_stack::Report<ApiErrorResponse>; fn try_from( data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { payment_method_data: data.request.payment_method_data, connector_transaction_id: match data.response { Ok(response_types::PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(id), .. }) => Some(id.clone()), _ => None, }, customer_id: data.request.customer_id, country: data .address .get_payment_billing() .and_then(|bl| bl.address.as_ref()) .and_then(|address| address.country), connector_meta_data: data.connector_meta_data.clone(), header_payload: data.header_payload, }) } } #[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeData { pub payment_method_data: Option<PaymentMethodData>, pub amount: i64, pub email: Option<pii::Email>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, // Mandates pub setup_future_usage: Option<storage_enums::FutureUsage>, pub mandate_id: Option<api_models::payments::MandateIds>, pub off_session: Option<bool>, pub setup_mandate_details: Option<mandates::MandateData>, pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub connector_meta: Option<serde_json::Value>, pub complete_authorize_url: Option<String>, pub metadata: Option<serde_json::Value>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, // New amount for amount frame work pub minor_amount: MinorUnit, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone, Serialize)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<Secret<String>>, pub payload: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsSyncData { //TODO : add fields based on the connector requirements pub connector_transaction_id: ResponseId, pub encoded_data: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub connector_meta: Option<serde_json::Value>, pub sync_type: SyncRequestType, pub mandate_id: Option<api_models::payments::MandateIds>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub currency: storage_enums::Currency, pub payment_experience: Option<common_enums::PaymentExperience>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub amount: MinorUnit, pub integrity_object: Option<SyncIntegrityObject>, pub connector_reference_id: Option<String>, pub setup_future_usage: Option<storage_enums::FutureUsage>, } #[derive(Debug, Default, Clone, Serialize)] pub enum SyncRequestType { MultipleCaptureSync(Vec<String>), #[default] SinglePaymentSync, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, pub connector_transaction_id: String, pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. // minor amount data for amount framework pub minor_amount: Option<MinorUnit>, pub webhook_url: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsCancelPostCaptureData { pub currency: Option<storage_enums::Currency>, pub connector_transaction_id: String, pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, // minor amount data for amount framework pub minor_amount: Option<MinorUnit>, } #[derive(Debug, Default, Clone, Serialize)] pub struct PaymentsExtendAuthorizationData { pub minor_amount: MinorUnit, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub connector_meta: Option<serde_json::Value>, } #[derive(Debug, Default, Clone)] pub struct PaymentsRejectData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, } #[derive(Debug, Default, Clone)] pub struct PaymentsApproveData { pub amount: Option<i64>, pub currency: Option<storage_enums::Currency>, } #[derive(Clone, Debug, Default, Serialize, serde::Deserialize)] pub struct BrowserInformation { pub color_depth: Option<u8>, pub java_enabled: Option<bool>, pub java_script_enabled: Option<bool>, pub language: Option<String>, pub screen_height: Option<u32>, pub screen_width: Option<u32>, pub time_zone: Option<i32>, pub ip_address: Option<std::net::IpAddr>, pub accept_header: Option<String>, pub user_agent: Option<String>, pub os_type: Option<String>, pub os_version: Option<String>, pub device_model: Option<String>, pub accept_language: Option<String>, pub referer: Option<String>, } #[cfg(feature = "v2")] impl From<common_utils::types::BrowserInformation> for BrowserInformation { fn from(value: common_utils::types::BrowserInformation) -> Self { Self { color_depth: value.color_depth, java_enabled: value.java_enabled, java_script_enabled: value.java_script_enabled, language: value.language, screen_height: value.screen_height, screen_width: value.screen_width, time_zone: value.time_zone, ip_address: value.ip_address, accept_header: value.accept_header, user_agent: value.user_agent, os_type: value.os_type, os_version: value.os_version, device_model: value.device_model, accept_language: value.accept_language, referer: value.referer, } } } #[cfg(feature = "v1")] impl From<api_models::payments::BrowserInformation> for BrowserInformation { fn from(value: api_models::payments::BrowserInformation) -> Self { Self { color_depth: value.color_depth, java_enabled: value.java_enabled, java_script_enabled: value.java_script_enabled, language: value.language, screen_height: value.screen_height, screen_width: value.screen_width, time_zone: value.time_zone, ip_address: value.ip_address, accept_header: value.accept_header, user_agent: value.user_agent, os_type: value.os_type, os_version: value.os_version, device_model: value.device_model, accept_language: value.accept_language, referer: value.referer, } } } #[derive(Debug, Clone, Default, Serialize)] pub enum ResponseId { ConnectorTransactionId(String), EncodedData(String), #[default] NoResponseId, } impl ResponseId { pub fn get_connector_transaction_id( &self, ) -> errors::CustomResult<String, errors::ValidationError> { match self { Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found"), } } } #[derive(Clone, Debug, serde::Deserialize, Serialize)] pub struct SurchargeDetails { /// original_amount pub original_amount: MinorUnit, /// surcharge value pub surcharge: common_utils::types::Surcharge, /// tax on surcharge value pub tax_on_surcharge: Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>, /// surcharge amount for this payment pub surcharge_amount: MinorUnit, /// tax on surcharge amount for this payment pub tax_on_surcharge_amount: MinorUnit, } impl SurchargeDetails { pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_on_surcharge_amount } } #[cfg(feature = "v1")] impl From<( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, )> for SurchargeDetails { fn from( (request_surcharge_details, payment_attempt): ( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, ), ) -> Self { let surcharge_amount = request_surcharge_details.surcharge_amount; let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default(); Self { original_amount: payment_attempt.net_amount.get_order_amount(), surcharge: common_utils::types::Surcharge::Fixed( request_surcharge_details.surcharge_amount, ), tax_on_surcharge: None, surcharge_amount, tax_on_surcharge_amount, } } } #[cfg(feature = "v2")] impl From<( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, )> for SurchargeDetails { fn from( (_request_surcharge_details, _payment_attempt): ( &RequestSurchargeDetails, &payments::payment_attempt::PaymentAttempt, ), ) -> Self { todo!() } } #[derive(Debug, Clone, Serialize)] pub struct AuthenticationData { pub eci: Option<String>, pub cavv: Secret<String>, pub threeds_server_transaction_id: Option<String>, pub message_version: Option<common_utils::types::SemanticVersion>, pub ds_trans_id: Option<String>, pub created_at: time::PrimitiveDateTime, pub challenge_code: Option<String>, pub challenge_cancel: Option<String>, pub challenge_code_reason: Option<String>, pub message_extension: Option<pii::SecretSerdeValue>, pub acs_trans_id: Option<String>, pub authentication_type: Option<common_enums::DecoupledAuthenticationType>, } #[derive(Debug, Clone)] pub struct RefundsData { pub refund_id: String, pub connector_transaction_id: String, pub connector_refund_id: Option<String>, pub currency: storage_enums::Currency, /// Amount for the payment against which this refund is issued pub payment_amount: i64, pub reason: Option<String>, pub webhook_url: Option<String>, /// Amount to be refunded pub refund_amount: i64, /// Arbitrary metadata required for refund pub connector_metadata: Option<serde_json::Value>, /// refund method pub refund_connector_metadata: Option<pii::SecretSerdeValue>, pub browser_info: Option<BrowserInformation>, /// Charges associated with the payment pub split_refunds: Option<SplitRefundsRequest>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, pub minor_refund_amount: MinorUnit, pub integrity_object: Option<RefundIntegrityObject>, pub refund_status: storage_enums::RefundStatus, pub merchant_account_id: Option<Secret<String>>, pub merchant_config_currency: Option<storage_enums::Currency>, pub capture_method: Option<storage_enums::CaptureMethod>, pub additional_payment_method_data: Option<AdditionalPaymentData>, } #[derive(Debug, Clone, PartialEq)] pub struct RefundIntegrityObject { /// refund currency pub currency: storage_enums::Currency, /// refund amount pub refund_amount: MinorUnit, } #[derive(Debug, serde::Deserialize, Clone)] pub enum SplitRefundsRequest { StripeSplitRefund(StripeSplitRefund), AdyenSplitRefund(common_types::domain::AdyenSplitData), XenditSplitRefund(common_types::domain::XenditSplitSubMerchantData), } #[derive(Debug, serde::Deserialize, Clone)] pub struct StripeSplitRefund { pub charge_id: String, pub transfer_account_id: String, pub charge_type: api_models::enums::PaymentChargeType, pub options: ChargeRefundsOptions, } #[derive(Debug, serde::Deserialize, Clone)] pub struct ChargeRefunds { pub charge_id: String, pub transfer_account_id: String, pub charge_type: api_models::enums::PaymentChargeType, pub options: ChargeRefundsOptions, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub enum ChargeRefundsOptions { Destination(DestinationChargeRefund), Direct(DirectChargeRefund), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DirectChargeRefund { pub revert_platform_fee: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)] pub struct DestinationChargeRefund { pub revert_platform_fee: bool, pub revert_transfer: bool, } #[derive(Debug, Clone)] pub struct AccessTokenAuthenticationRequestData { pub auth_creds: router_data::ConnectorAuthType, } impl TryFrom<router_data::ConnectorAuthType> for AccessTokenAuthenticationRequestData { type Error = ApiErrorResponse; fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { Ok(Self { auth_creds: connector_auth, }) } } #[derive(Debug, Clone)] pub struct AccessTokenRequestData { pub app_id: Secret<String>, pub id: Option<Secret<String>>, pub authentication_token: Option<AccessTokenAuthenticationResponse>, // Add more keys if required } // This is for backward compatibility impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData { type Error = ApiErrorResponse; fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> { match connector_auth { router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self { app_id: api_key, id: None, authentication_token: None, }), router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self { app_id: api_key, id: Some(key1), authentication_token: None, }), _ => Err(ApiErrorResponse::InvalidDataValue { field_name: "connector_account_details", }), } } } impl TryFrom<( router_data::ConnectorAuthType, Option<AccessTokenAuthenticationResponse>, )> for AccessTokenRequestData { type Error = ApiErrorResponse; fn try_from( (connector_auth, authentication_token): ( router_data::ConnectorAuthType, Option<AccessTokenAuthenticationResponse>, ), ) -> Result<Self, Self::Error> { let mut access_token_request_data = Self::try_from(connector_auth)?; access_token_request_data.authentication_token = authentication_token; Ok(access_token_request_data) } } #[derive(Default, Debug, Clone)] pub struct AcceptDisputeRequestData { pub dispute_id: String, pub connector_dispute_id: String, pub dispute_status: storage_enums::DisputeStatus, } #[derive(Default, Debug, Clone)] pub struct DefendDisputeRequestData { pub dispute_id: String, pub connector_dispute_id: String, } #[derive(Default, Debug, Clone)] pub struct SubmitEvidenceRequestData { pub dispute_id: String, pub dispute_status: storage_enums::DisputeStatus, pub connector_dispute_id: String, pub access_activity_log: Option<String>, pub billing_address: Option<String>, //cancellation policy pub cancellation_policy: Option<Vec<u8>>, pub cancellation_policy_file_type: Option<String>, pub cancellation_policy_provider_file_id: Option<String>, pub cancellation_policy_disclosure: Option<String>, pub cancellation_rebuttal: Option<String>, //customer communication pub customer_communication: Option<Vec<u8>>, pub customer_communication_file_type: Option<String>, pub customer_communication_provider_file_id: Option<String>, pub customer_email_address: Option<String>, pub customer_name: Option<String>, pub customer_purchase_ip: Option<String>, //customer signature pub customer_signature: Option<Vec<u8>>, pub customer_signature_file_type: Option<String>, pub customer_signature_provider_file_id: Option<String>, //product description pub product_description: Option<String>, //receipts pub receipt: Option<Vec<u8>>, pub receipt_file_type: Option<String>, pub receipt_provider_file_id: Option<String>, //refund policy pub refund_policy: Option<Vec<u8>>, pub refund_policy_file_type: Option<String>, pub refund_policy_provider_file_id: Option<String>, pub refund_policy_disclosure: Option<String>, pub refund_refusal_explanation: Option<String>, //service docs pub service_date: Option<String>, pub service_documentation: Option<Vec<u8>>, pub service_documentation_file_type: Option<String>, pub service_documentation_provider_file_id: Option<String>, //shipping details docs pub shipping_address: Option<String>, pub shipping_carrier: Option<String>, pub shipping_date: Option<String>, pub shipping_documentation: Option<Vec<u8>>, pub shipping_documentation_file_type: Option<String>, pub shipping_documentation_provider_file_id: Option<String>, pub shipping_tracking_number: Option<String>, //invoice details pub invoice_showing_distinct_transactions: Option<Vec<u8>>, pub invoice_showing_distinct_transactions_file_type: Option<String>, pub invoice_showing_distinct_transactions_provider_file_id: Option<String>, //subscription details pub recurring_transaction_agreement: Option<Vec<u8>>, pub recurring_transaction_agreement_file_type: Option<String>, pub recurring_transaction_agreement_provider_file_id: Option<String>, //uncategorized details pub uncategorized_file: Option<Vec<u8>>, pub uncategorized_file_type: Option<String>, pub uncategorized_file_provider_file_id: Option<String>, pub uncategorized_text: Option<String>, } #[derive(Debug, Serialize, Clone)] pub struct FetchDisputesRequestData { pub created_from: time::PrimitiveDateTime, pub created_till: time::PrimitiveDateTime, } #[derive(Clone, Debug)] pub struct RetrieveFileRequestData { pub provider_file_id: String, pub connector_dispute_id: Option<String>, } #[serde_as] #[derive(Clone, Debug, Serialize)] pub struct UploadFileRequestData { pub file_key: String, #[serde(skip)] pub file: Vec<u8>, #[serde_as(as = "serde_with::DisplayFromStr")] pub file_type: mime::Mime, pub file_size: i32, pub dispute_id: String, pub connector_dispute_id: String, } #[cfg(feature = "payouts")] #[derive(Debug, Clone)] pub struct PayoutsData { pub payout_id: id_type::PayoutId, pub amount: i64, pub connector_payout_id: Option<String>, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub payout_type: Option<storage_enums::PayoutType>, pub entity_type: storage_enums::PayoutEntityType, pub customer_details: Option<CustomerDetails>, pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>, // New minor amount for amount framework pub minor_amount: MinorUnit, pub priority: Option<storage_enums::PayoutSendPriority>, pub connector_transfer_method_id: Option<String>, pub webhook_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone)] pub struct CustomerDetails { pub customer_id: Option<id_type::CustomerId>, pub name: Option<Secret<String, masking::WithType>>, pub email: Option<pii::Email>, pub phone: Option<Secret<String, masking::WithType>>, pub phone_country_code: Option<String>, pub tax_registration_id: Option<Secret<String, masking::WithType>>, } #[derive(Debug, Clone)] pub struct VerifyWebhookSourceRequestData { pub webhook_headers: actix_web::http::header::HeaderMap, pub webhook_body: Vec<u8>, pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets, } #[derive(Debug, Clone)] pub struct MandateRevokeRequestData { pub mandate_id: String, pub connector_mandate_id: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct PaymentsSessionData { pub amount: i64, pub currency: common_enums::Currency, pub country: Option<common_enums::CountryAlpha2>, pub surcharge_details: Option<SurchargeDetails>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub email: Option<pii::Email>, // Minor Unit amount for amount frame work pub minor_amount: MinorUnit, pub apple_pay_recurring_details: Option<api_models::payments::ApplePayRecurringPaymentRequest>, pub customer_name: Option<Secret<String>>, pub order_tax_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub metadata: Option<Secret<serde_json::Value>>, /// The specific payment method type for which the session token is being generated pub payment_method_type: Option<common_enums::PaymentMethodType>, pub payment_method: Option<common_enums::PaymentMethod>, } #[derive(Debug, Clone, Default)] pub struct PaymentsTaxCalculationData { pub amount: MinorUnit, pub currency: storage_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub shipping_address: address::Address, } #[derive(Debug, Clone, Default, Serialize)] pub struct SdkPaymentsSessionUpdateData { pub order_tax_amount: MinorUnit, // amount here would include amount, surcharge_amount, order_tax_amount and shipping_cost pub amount: MinorUnit, /// original amount sent by the merchant pub order_amount: MinorUnit, pub currency: storage_enums::Currency, pub session_id: Option<String>, pub shipping_cost: Option<MinorUnit>, } #[derive(Debug, Clone, Serialize)] pub struct SetupMandateRequestData { pub currency: storage_enums::Currency, pub payment_method_data: PaymentMethodData, pub amount: Option<i64>, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, pub mandate_id: Option<api_models::payments::MandateIds>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub setup_mandate_details: Option<mandates::MandateData>, pub router_return_url: Option<String>, pub webhook_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub return_url: Option<String>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, pub metadata: Option<pii::SecretSerdeValue>, pub complete_authorize_url: Option<String>, pub capture_method: Option<storage_enums::CaptureMethod>, pub enrolled_for_3ds: bool, pub related_transaction_id: Option<String>, // MinorUnit for amount framework pub minor_amount: Option<MinorUnit>, pub shipping_cost: Option<MinorUnit>, pub connector_testing_data: Option<pii::SecretSerdeValue>, pub customer_id: Option<id_type::CustomerId>, pub enable_partial_authorization: Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>, pub payment_channel: Option<storage_enums::PaymentChannel>, pub is_stored_credential: Option<bool>, } #[derive(Debug, Clone)] pub struct VaultRequestData { pub payment_method_vaulting_data: Option<PaymentMethodVaultingData>, pub connector_vault_id: Option<String>, pub connector_customer_id: Option<String>, } #[derive(Debug, Serialize, Clone)] pub struct DisputeSyncData { pub dispute_id: String, pub connector_dispute_id: String, }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/router_request_types.rs", "file_size": 56590, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_2938545218451679103
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/payments.rs // File size: 55683 bytes #[cfg(feature = "v2")] use std::marker::PhantomData; #[cfg(feature = "v2")] use api_models::payments::{ConnectorMetadata, SessionToken, VaultSessionDetails}; use common_types::primitive_wrappers; #[cfg(feature = "v1")] use common_types::primitive_wrappers::{ AlwaysRequestExtendedAuthorization, EnableOvercaptureBool, RequestExtendedAuthorizationBool, }; use common_utils::{ self, crypto::Encryptable, encryption::Encryption, errors::CustomResult, ext_traits::ValueExt, id_type, pii, types::{keymanager::ToEncryptable, CreatedBy, MinorUnit}, }; use diesel_models::payment_intent::TaxDetails; #[cfg(feature = "v2")] use error_stack::ResultExt; use masking::Secret; use router_derive::ToEncryption; use rustc_hash::FxHashMap; use serde_json::Value; use time::PrimitiveDateTime; pub mod payment_attempt; pub mod payment_intent; use common_enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount}; use self::payment_attempt::PaymentAttempt; #[cfg(feature = "v2")] use crate::{ address::Address, business_profile, customer, errors, merchant_connector_account, merchant_connector_account::MerchantConnectorAccountTypeDetails, merchant_context, payment_address, payment_method_data, payment_methods, revenue_recovery, routing, ApiModelToDieselModelConvertor, }; #[cfg(feature = "v1")] use crate::{payment_method_data, RemoteStorageObject}; #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: MinorUnit, pub shipping_cost: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<MinorUnit>, pub customer_id: Option<id_type::CustomerId>, pub description: Option<String>, pub return_url: Option<String>, pub metadata: Option<Value>, pub connector_id: Option<String>, pub shipping_address_id: Option<String>, pub billing_address_id: Option<String>, pub statement_descriptor_name: Option<String>, pub statement_descriptor_suffix: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub active_attempt: RemoteStorageObject<PaymentAttempt>, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<String>, pub order_details: Option<Vec<pii::SecretSerdeValue>>, pub allowed_payment_method_types: Option<Value>, pub connector_metadata: Option<Value>, pub feature_metadata: Option<Value>, pub attempt_count: i16, pub profile_id: Option<id_type::ProfileId>, pub payment_link_id: Option<String>, // Denotes the action(approve or reject) taken by merchant in case of manual review. // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub updated_by: String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub fingerprint_id: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, pub request_external_three_ds_authentication: Option<bool>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub frm_metadata: Option<pii::SecretSerdeValue>, #[encrypt] pub customer_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub billing_details: Option<Encryptable<Secret<Value>>>, pub merchant_order_reference_id: Option<String>, #[encrypt] pub shipping_details: Option<Encryptable<Secret<Value>>>, pub is_payment_processor_token_flow: Option<bool>, pub organization_id: id_type::OrganizationId, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub processor_merchant_id: id_type::MerchantId, pub created_by: Option<CreatedBy>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub is_iframe_redirection_enabled: Option<bool>, pub is_payment_id_from_merchant: Option<bool>, pub payment_channel: Option<common_enums::PaymentChannel>, pub tax_status: Option<storage_enums::TaxStatus>, pub discount_amount: Option<MinorUnit>, pub order_date: Option<PrimitiveDateTime>, pub shipping_amount_tax: Option<MinorUnit>, pub duty_amount: Option<MinorUnit>, pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, pub enable_overcapture: Option<EnableOvercaptureBool>, pub mit_category: Option<common_enums::MitCategory>, } impl PaymentIntent { #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::PaymentId { &self.payment_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentId { &self.id } #[cfg(feature = "v2")] /// This is the url to which the customer will be redirected to, to complete the redirection flow pub fn create_start_redirection_url( &self, base_url: &str, publishable_key: String, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let start_redirection_url = &format!( "{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}", base_url, self.get_id().get_string_repr(), publishable_key, self.profile_id.get_string_repr() ); url::Url::parse(start_redirection_url) .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Error creating start redirection url") } #[cfg(feature = "v1")] pub fn get_request_extended_authorization_bool_if_connector_supports( &self, connector: common_enums::connector_enums::Connector, always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>, payment_method_optional: Option<common_enums::PaymentMethod>, payment_method_type_optional: Option<common_enums::PaymentMethodType>, ) -> Option<RequestExtendedAuthorizationBool> { use router_env::logger; let is_extended_authorization_supported_by_connector = || { let supported_pms = connector.get_payment_methods_supporting_extended_authorization(); let supported_pmts = connector.get_payment_method_types_supporting_extended_authorization(); // check if payment method or payment method type is supported by the connector logger::info!( "Extended Authentication Connector:{:?}, Supported payment methods: {:?}, Supported payment method types: {:?}, Payment method Selected: {:?}, Payment method type Selected: {:?}", connector, supported_pms, supported_pmts, payment_method_optional, payment_method_type_optional ); match (payment_method_optional, payment_method_type_optional) { (Some(payment_method), Some(payment_method_type)) => { supported_pms.contains(&payment_method) && supported_pmts.contains(&payment_method_type) } (Some(payment_method), None) => supported_pms.contains(&payment_method), (None, Some(payment_method_type)) => supported_pmts.contains(&payment_method_type), (None, None) => false, } }; let intent_request_extended_authorization_optional = self.request_extended_authorization; let is_extended_authorization_requested = intent_request_extended_authorization_optional .map(|should_request_extended_authorization| *should_request_extended_authorization) .or(always_request_extended_authorization_optional.map( |should_always_request_extended_authorization| { *should_always_request_extended_authorization }, )); is_extended_authorization_requested .map(|requested| { if requested { is_extended_authorization_supported_by_connector() } else { false } }) .map(RequestExtendedAuthorizationBool::from) } #[cfg(feature = "v1")] pub fn get_enable_overcapture_bool_if_connector_supports( &self, connector: common_enums::connector_enums::Connector, always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, capture_method: &Option<common_enums::CaptureMethod>, ) -> Option<EnableOvercaptureBool> { let is_overcapture_supported_by_connector = connector.is_overcapture_supported_by_connector(); if matches!(capture_method, Some(common_enums::CaptureMethod::Manual)) && is_overcapture_supported_by_connector { self.enable_overcapture .or_else(|| always_enable_overcapture.map(EnableOvercaptureBool::from)) } else { None } } #[cfg(feature = "v2")] /// This is the url to which the customer will be redirected to, after completing the redirection flow pub fn create_finish_redirection_url( &self, base_url: &str, publishable_key: &str, ) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> { let finish_redirection_url = format!( "{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}", self.id.get_string_repr(), self.profile_id.get_string_repr() ); url::Url::parse(&finish_redirection_url) .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Error creating finish redirection url") } pub fn parse_and_get_metadata<T>( &self, type_name: &'static str, ) -> CustomResult<Option<T>, common_utils::errors::ParsingError> where T: for<'de> masking::Deserialize<'de>, { self.metadata .clone() .map(|metadata| metadata.parse_value(type_name)) .transpose() } #[cfg(feature = "v1")] pub fn merge_metadata( &self, request_metadata: Value, ) -> Result<Value, common_utils::errors::ParsingError> { if !request_metadata.is_null() { match (&self.metadata, &request_metadata) { (Some(Value::Object(existing_map)), Value::Object(req_map)) => { let mut merged = existing_map.clone(); merged.extend(req_map.clone()); Ok(Value::Object(merged)) } (None, Value::Object(_)) => Ok(request_metadata), _ => { router_env::logger::error!( "Expected metadata to be an object, got: {:?}", request_metadata ); Err(common_utils::errors::ParsingError::UnknownError) } } } else { router_env::logger::error!("Metadata does not contain any key"); Err(common_utils::errors::ParsingError::UnknownError) } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize)] pub struct AmountDetails { /// The amount of the order in the lowest denomination of currency pub order_amount: MinorUnit, /// The currency of the order pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax details related to the order. This will be calculated by the external tax provider pub tax_details: Option<TaxDetails>, /// The action to whether calculate tax by calling external tax provider or not pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount captured for the order. This is the sum of all the captured amounts for the order. /// For automatic captures, this will be the same as net amount for the order pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { /// Get the action to whether calculate surcharge or not as a boolean value fn get_surcharge_action_as_bool(&self) -> bool { self.skip_surcharge_calculation.as_bool() } /// Get the action to whether calculate external tax or not as a boolean value pub fn get_external_tax_action_as_bool(&self) -> bool { self.skip_external_tax_calculation.as_bool() } /// Calculate the net amount for the order pub fn calculate_net_amount(&self) -> MinorUnit { self.order_amount + self.shipping_cost.unwrap_or(MinorUnit::zero()) + self.surcharge_amount.unwrap_or(MinorUnit::zero()) + self.tax_on_surcharge.unwrap_or(MinorUnit::zero()) } pub fn create_attempt_amount_details( &self, confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest, ) -> payment_attempt::AttemptAmountDetails { let net_amount = self.calculate_net_amount(); let surcharge_amount = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount, common_enums::SurchargeCalculationOverride::Calculate => None, }; let tax_on_surcharge = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge, common_enums::SurchargeCalculationOverride::Calculate => None, }; let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => { self.tax_details.as_ref().and_then(|tax_details| { tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype)) }) } common_enums::TaxCalculationOverride::Calculate => None, }; payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter { net_amount, amount_to_capture: None, surcharge_amount, tax_on_surcharge, // This will be updated when we receive response from the connector amount_capturable: MinorUnit::zero(), shipping_cost: self.shipping_cost, order_tax_amount, }) } pub fn proxy_create_attempt_amount_details( &self, _confirm_intent_request: &api_models::payments::ProxyPaymentsRequest, ) -> payment_attempt::AttemptAmountDetails { let net_amount = self.calculate_net_amount(); let surcharge_amount = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount, common_enums::SurchargeCalculationOverride::Calculate => None, }; let tax_on_surcharge = match self.skip_surcharge_calculation { common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge, common_enums::SurchargeCalculationOverride::Calculate => None, }; let order_tax_amount = match self.skip_external_tax_calculation { common_enums::TaxCalculationOverride::Skip => self .tax_details .as_ref() .and_then(|tax_details| tax_details.get_tax_amount(None)), common_enums::TaxCalculationOverride::Calculate => None, }; payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter { net_amount, amount_to_capture: None, surcharge_amount, tax_on_surcharge, // This will be updated when we receive response from the connector amount_capturable: MinorUnit::zero(), shipping_cost: self.shipping_cost, order_tax_amount, }) } pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self { Self { order_amount: req .order_amount() .unwrap_or(self.order_amount.into()) .into(), currency: req.currency().unwrap_or(self.currency), shipping_cost: req.shipping_cost().or(self.shipping_cost), tax_details: req .order_tax_amount() .map(|order_tax_amount| TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount }), payment_method_type: None, }) .or(self.tax_details), skip_external_tax_calculation: req .skip_external_tax_calculation() .unwrap_or(self.skip_external_tax_calculation), skip_surcharge_calculation: req .skip_surcharge_calculation() .unwrap_or(self.skip_surcharge_calculation), surcharge_amount: req.surcharge_amount().or(self.surcharge_amount), tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge), amount_captured: self.amount_captured, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] pub struct PaymentIntent { /// The global identifier for the payment intent. This is generated by the system. /// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`. pub id: id_type::GlobalPaymentId, /// The identifier for the merchant. This is automatically derived from the api key used to create the payment. pub merchant_id: id_type::MerchantId, /// The status of payment intent. pub status: storage_enums::IntentStatus, /// The amount related details of the payment pub amount_details: AmountDetails, /// The total amount captured for the order. This is the sum of all the captured amounts for the order. pub amount_captured: Option<MinorUnit>, /// The identifier for the customer. This is the identifier for the customer in the merchant's system. pub customer_id: Option<id_type::GlobalCustomerId>, /// The description of the order. This will be passed to connectors which support description. pub description: Option<common_utils::types::Description>, /// The return url for the payment. This is the url to which the user will be redirected after the payment is completed. pub return_url: Option<common_utils::types::Url>, /// The metadata for the payment intent. This is the metadata that will be passed to the connectors. pub metadata: Option<pii::SecretSerdeValue>, /// The statement descriptor for the order, this will be displayed in the user's bank statement. pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// The time at which the order was created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The time at which the order was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_synced: Option<PrimitiveDateTime>, pub setup_future_usage: storage_enums::FutureUsage, /// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent. pub active_attempt_id: Option<id_type::GlobalAttemptId>, /// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow pub active_attempt_id_type: common_enums::ActiveAttemptIDType, /// The ID of the active attempt group for the payment intent pub active_attempts_group_id: Option<String>, /// The order details for the payment. pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// This is the list of payment method types that are allowed for the payment intent. /// This field allows the merchant to restrict the payment methods that can be used for the payment intent. pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// This metadata contains connector-specific details like Apple Pay certificates, Airwallex data, Noon order category, Braintree merchant account ID, and Adyen testing data pub connector_metadata: Option<ConnectorMetadata>, pub feature_metadata: Option<FeatureMetadata>, /// Number of attempts that have been made for the order pub attempt_count: i16, /// The profile id for the payment. pub profile_id: id_type::ProfileId, /// The payment link id for the payment. This is generated only if `enable_payment_link` is set to true. pub payment_link_id: Option<String>, /// This Denotes the action(approve or reject) taken by merchant in case of manual review. /// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub frm_merchant_decision: Option<common_enums::MerchantDecision>, /// Denotes the last instance which updated the payment pub updated_by: String, /// Denotes whether merchant requested for incremental authorization to be enabled for this payment. pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization, /// Denotes whether merchant requested for split payments to be enabled for this payment pub split_txns_enabled: storage_enums::SplitTxnsEnabled, /// Denotes the number of authorizations that have been made for the payment. pub authorization_count: Option<i32>, /// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire. #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, /// Denotes whether merchant requested for 3ds authentication to be enabled for this payment. pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, /// Metadata related to fraud and risk management pub frm_metadata: Option<pii::SecretSerdeValue>, /// The details of the customer in a denormalized form. Only a subset of fields are stored. #[encrypt] pub customer_details: Option<Encryptable<Secret<Value>>>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The billing address for the order in a denormalized form. #[encrypt(ty = Value)] pub billing_address: Option<Encryptable<Address>>, /// The shipping address for the order in a denormalized form. #[encrypt(ty = Value)] pub shipping_address: Option<Encryptable<Address>>, /// Capture method for the payment pub capture_method: storage_enums::CaptureMethod, /// Authentication type that is requested by the merchant for this payment. pub authentication_type: Option<common_enums::AuthenticationType>, /// This contains the pre routing results that are done when routing is done during listing the payment methods. pub prerouting_algorithm: Option<routing::PaymentRoutingInfo>, /// The organization id for the payment. This is derived from the merchant account pub organization_id: id_type::OrganizationId, /// Denotes the request by the merchant whether to enable a payment link for this payment. pub enable_payment_link: common_enums::EnablePaymentLinkRequest, /// Denotes the request by the merchant whether to apply MIT exemption for this payment pub apply_mit_exemption: common_enums::MitExemptionRequest, /// Denotes whether the customer is present during the payment flow. This information may be used for 3ds authentication pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// Denotes the override for payment link configuration pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, /// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile. pub routing_algorithm_id: Option<id_type::RoutingId>, /// Split Payment Data pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, /// merchant who owns the credentials of the processor, i.e. processor owner pub processor_merchant_id: id_type::MerchantId, /// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard)) pub created_by: Option<CreatedBy>, /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, /// Indicates whether the payment_id was provided by the merchant (true), /// or generated internally by Hyperswitch (false) pub is_payment_id_from_merchant: Option<bool>, /// Denotes whether merchant requested for partial authorization to be enabled for this payment. pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[cfg(feature = "v2")] impl PaymentIntent { /// Extract customer_id from payment intent feature metadata pub fn extract_connector_customer_id_from_payment_intent( &self, ) -> Result<String, common_utils::errors::ValidationError> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()) .map(|recovery| { recovery .billing_connector_payment_details .connector_customer_id .clone() }) .ok_or( common_utils::errors::ValidationError::MissingRequiredField { field_name: "connector_customer_id".to_string(), }, ) } fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.get_payment_method_sub_type()) } fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.get_payment_method_type()) } pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()) .map(|recovery_metadata| { recovery_metadata .billing_connector_payment_details .connector_customer_id .clone() }) } pub fn get_billing_merchant_connector_account_id( &self, ) -> Option<id_type::MerchantConnectorAccountId> { self.feature_metadata.as_ref().and_then(|feature_metadata| { feature_metadata.get_billing_merchant_connector_account_id() }) } fn get_request_incremental_authorization_value( request: &api_models::payments::PaymentsCreateIntentRequest, ) -> CustomResult< common_enums::RequestIncrementalAuthorization, errors::api_error_response::ApiErrorResponse, > { request.request_incremental_authorization .map(|request_incremental_authorization| { if request_incremental_authorization == common_enums::RequestIncrementalAuthorization::True { if request.capture_method == Some(common_enums::CaptureMethod::Automatic) { Err(errors::api_error_response::ApiErrorResponse::InvalidRequestData { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })? } Ok(common_enums::RequestIncrementalAuthorization::True) } else { Ok(common_enums::RequestIncrementalAuthorization::False) } }) .unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default())) } pub async fn create_domain_model_from_request( payment_id: &id_type::GlobalPaymentId, merchant_context: &merchant_context::MerchantContext, profile: &business_profile::Profile, request: api_models::payments::PaymentsCreateIntentRequest, decrypted_payment_intent: DecryptedPaymentIntent, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let request_incremental_authorization = Self::get_request_incremental_authorization_value(&request)?; let allowed_payment_method_types = request.allowed_payment_method_types; let session_expiry = common_utils::date_time::now().saturating_add(time::Duration::seconds( request.session_expiry.map(i64::from).unwrap_or( profile .session_expiry .unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY), ), )); let order_details = request.order_details.map(|order_details| { order_details .into_iter() .map(|order_detail| Secret::new(OrderDetailsWithAmount::convert_from(order_detail))) .collect() }); Ok(Self { id: payment_id.clone(), merchant_id: merchant_context.get_merchant_account().get_id().clone(), // Intent status would be RequiresPaymentMethod because we are creating a new payment intent status: common_enums::IntentStatus::RequiresPaymentMethod, amount_details: AmountDetails::from(request.amount_details), amount_captured: None, customer_id: request.customer_id, description: request.description, return_url: request.return_url, metadata: request.metadata, statement_descriptor: request.statement_descriptor, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: request.setup_future_usage.unwrap_or_default(), active_attempt_id: None, active_attempt_id_type: common_enums::ActiveAttemptIDType::AttemptID, active_attempts_group_id: None, order_details, allowed_payment_method_types, connector_metadata: request.connector_metadata, feature_metadata: request.feature_metadata.map(FeatureMetadata::convert_from), // Attempt count is 0 in create intent as no attempt is made yet attempt_count: 0, profile_id: profile.get_id().clone(), payment_link_id: None, frm_merchant_decision: None, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), request_incremental_authorization, // Authorization count is 0 in create intent as no authorization is made yet authorization_count: Some(0), session_expiry, request_external_three_ds_authentication: request .request_external_three_ds_authentication .unwrap_or_default(), split_txns_enabled: profile.split_txns_enabled, frm_metadata: request.frm_metadata, customer_details: None, merchant_reference_id: request.merchant_reference_id, billing_address: decrypted_payment_intent .billing_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode billing address")?, shipping_address: decrypted_payment_intent .shipping_address .as_ref() .map(|data| { data.clone() .deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Unable to decode shipping address")?, capture_method: request.capture_method.unwrap_or_default(), authentication_type: request.authentication_type, prerouting_algorithm: None, organization_id: merchant_context .get_merchant_account() .organization_id .clone(), enable_payment_link: request.payment_link_enabled.unwrap_or_default(), apply_mit_exemption: request.apply_mit_exemption.unwrap_or_default(), customer_present: request.customer_present.unwrap_or_default(), payment_link_config: request .payment_link_config .map(ApiModelToDieselModelConvertor::convert_from), routing_algorithm_id: request.routing_algorithm_id, split_payments: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, processor_merchant_id: merchant_context.get_merchant_account().get_id().clone(), created_by: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, enable_partial_authorization: request.enable_partial_authorization, }) } pub fn get_revenue_recovery_metadata( &self, ) -> Option<diesel_models::types::PaymentRevenueRecoveryMetadata> { self.feature_metadata .as_ref() .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()) } pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> { self.feature_metadata.clone() } pub fn create_revenue_recovery_attempt_data( &self, revenue_recovery_metadata: api_models::payments::PaymentRevenueRecoveryMetadata, billing_connector_account: &merchant_connector_account::MerchantConnectorAccount, card_info: api_models::payments::AdditionalCardInfo, payment_processor_token: &str, ) -> CustomResult< revenue_recovery::RevenueRecoveryAttemptData, errors::api_error_response::ApiErrorResponse, > { let merchant_reference_id = self.merchant_reference_id.clone().ok_or_else(|| { error_stack::report!( errors::api_error_response::ApiErrorResponse::GenericNotFoundError { message: "mandate reference id not found".to_string() } ) })?; let connector_account_reference_id = billing_connector_account .get_account_reference_id_using_payment_merchant_connector_account_id( revenue_recovery_metadata.active_attempt_payment_connector_id, ) .ok_or_else(|| { error_stack::report!( errors::api_error_response::ApiErrorResponse::GenericNotFoundError { message: "connector account reference id not found".to_string() } ) })?; Ok(revenue_recovery::RevenueRecoveryAttemptData { amount: self.amount_details.order_amount, currency: self.amount_details.currency, merchant_reference_id, connector_transaction_id: None, // No connector id error_code: None, error_message: None, processor_payment_method_token: payment_processor_token.to_string(), connector_customer_id: revenue_recovery_metadata .billing_connector_payment_details .connector_customer_id, connector_account_reference_id, transaction_created_at: None, // would unwrap_or as now status: common_enums::AttemptStatus::Started, payment_method_type: self .get_payment_method_type() .unwrap_or(revenue_recovery_metadata.payment_method_type), payment_method_sub_type: self .get_payment_method_sub_type() .unwrap_or(revenue_recovery_metadata.payment_method_subtype), network_advice_code: None, network_decline_code: None, network_error_message: None, retry_count: None, invoice_next_billing_time: None, invoice_billing_started_at_time: None, // No charge id is present here since it is an internal payment and we didn't call connector yet. charge_id: None, card_info: card_info.clone(), }) } pub fn get_optional_customer_id( &self, ) -> CustomResult<Option<id_type::CustomerId>, common_utils::errors::ValidationError> { self.customer_id .as_ref() .map(|customer_id| id_type::CustomerId::try_from(customer_id.clone())) .transpose() } pub fn get_currency(&self) -> storage_enums::Currency { self.amount_details.currency } } #[cfg(feature = "v1")] #[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { pub payment_confirm_source: Option<common_enums::PaymentSource>, pub client_source: Option<String>, pub client_version: Option<String>, pub x_hs_latency: Option<bool>, pub browser_name: Option<common_enums::BrowserName>, pub x_client_platform: Option<common_enums::ClientPlatform>, pub x_merchant_domain: Option<String>, pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, pub x_reference_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ClickToPayMetaData { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, pub dpa_client_id: Option<String>, } // TODO: uncomment fields as necessary #[cfg(feature = "v2")] #[derive(Default, Debug, Clone, serde::Serialize)] pub struct HeaderPayload { /// The source with which the payment is confirmed. pub payment_confirm_source: Option<common_enums::PaymentSource>, // pub client_source: Option<String>, // pub client_version: Option<String>, pub x_hs_latency: Option<bool>, pub browser_name: Option<common_enums::BrowserName>, pub x_client_platform: Option<common_enums::ClientPlatform>, pub x_merchant_domain: Option<String>, pub locale: Option<String>, pub x_app_id: Option<String>, pub x_redirect_uri: Option<String>, pub x_reference_id: Option<String>, } impl HeaderPayload { pub fn with_source(payment_confirm_source: common_enums::PaymentSource) -> Self { Self { payment_confirm_source: Some(payment_confirm_source), ..Default::default() } } } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentIntentData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub sessions_token: Vec<SessionToken>, pub client_secret: Option<Secret<String>>, pub vault_session_details: Option<VaultSessionDetails>, pub connector_customer_id: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentAttemptListData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_attempt_list: Vec<PaymentAttempt>, } // TODO: Check if this can be merged with existing payment data #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct PaymentConfirmData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub payment_method_data: Option<payment_method_data::PaymentMethodData>, pub payment_address: payment_address::PaymentAddress, pub mandate_data: Option<api_models::payments::MandateIds>, pub payment_method: Option<payment_methods::PaymentMethod>, pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, pub external_vault_pmd: Option<payment_method_data::ExternalVaultPaymentMethodData>, /// The webhook url of the merchant, to which the connector will send the webhook. pub webhook_url: Option<String>, } #[cfg(feature = "v2")] impl<F: Clone> PaymentConfirmData<F> { pub fn get_connector_customer_id( &self, customer: Option<&customer::Customer>, merchant_connector_account: &MerchantConnectorAccountTypeDetails, ) -> Option<String> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => customer .and_then(|customer| customer.get_connector_customer_id(merchant_connector_account)) .map(|id| id.to_string()) .or_else(|| { self.payment_intent .get_connector_customer_id_from_feature_metadata() }), MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, } } pub fn update_payment_method_data( &mut self, payment_method_data: payment_method_data::PaymentMethodData, ) { self.payment_method_data = Some(payment_method_data); } pub fn update_payment_method_and_pm_id( &mut self, payment_method_id: id_type::GlobalPaymentMethodId, payment_method: payment_methods::PaymentMethod, ) { self.payment_attempt.payment_method_id = Some(payment_method_id); self.payment_method = Some(payment_method); } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct PaymentStatusData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub payment_address: payment_address::PaymentAddress, pub attempts: Option<Vec<PaymentAttempt>>, /// Should the payment status be synced with connector /// This will depend on the payment status and the force sync flag in the request pub should_sync_with_connector: bool, pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentCaptureData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentCancelData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, } #[cfg(feature = "v2")] impl<F> PaymentStatusData<F> where F: Clone, { pub fn get_payment_id(&self) -> &id_type::GlobalPaymentId { &self.payment_intent.id } } #[cfg(feature = "v2")] #[derive(Clone)] pub struct PaymentAttemptRecordData<F> where F: Clone, { pub flow: PhantomData<F>, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub revenue_recovery_data: RevenueRecoveryData, pub payment_address: payment_address::PaymentAddress, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct RevenueRecoveryData { pub billing_connector_id: id_type::MerchantConnectorAccountId, pub processor_payment_method_token: String, pub connector_customer_id: String, pub retry_count: Option<u16>, pub invoice_next_billing_time: Option<PrimitiveDateTime>, pub triggered_by: storage_enums::enums::TriggeredBy, pub card_network: Option<common_enums::CardNetwork>, pub card_issuer: Option<String>, } #[cfg(feature = "v2")] impl<F> PaymentAttemptRecordData<F> where F: Clone, { pub fn get_updated_feature_metadata( &self, ) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> { let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata(); let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata(); let payment_attempt_connector = self.payment_attempt.connector.clone(); let feature_metadata_first_pg_error_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_pg_error_code.clone()); let (first_pg_error_code, first_network_advice_code, first_network_decline_code) = feature_metadata_first_pg_error_code.map_or_else( || { let first_pg_error_code = self .payment_attempt .error .as_ref() .map(|error| error.code.clone()); let first_network_advice_code = self .payment_attempt .error .as_ref() .and_then(|error| error.network_advice_code.clone()); let first_network_decline_code = self .payment_attempt .error .as_ref() .and_then(|error| error.network_decline_code.clone()); ( first_pg_error_code, first_network_advice_code, first_network_decline_code, ) }, |pg_code| { let advice_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_network_advice_code.clone()); let decline_code = revenue_recovery .as_ref() .and_then(|data| data.first_payment_attempt_network_decline_code.clone()); (Some(pg_code), advice_code, decline_code) }, ); let billing_connector_payment_method_details = Some( diesel_models::types::BillingConnectorPaymentMethodDetails::Card( diesel_models::types::BillingConnectorAdditionalCardInfo { card_network: self.revenue_recovery_data.card_network.clone(), card_issuer: self.revenue_recovery_data.card_issuer.clone(), }, ), ); let payment_revenue_recovery_metadata = match payment_attempt_connector { Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata { // Update retry count by one. total_retry_count: revenue_recovery.as_ref().map_or( self.revenue_recovery_data .retry_count .map_or_else(|| 1, |retry_count| retry_count), |data| (data.total_retry_count + 1), ), // Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded. payment_connector_transmission: common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(), active_attempt_payment_connector_id: self .payment_attempt .get_attempt_merchant_connector_account_id()?, billing_connector_payment_details: diesel_models::types::BillingConnectorPaymentDetails { payment_processor_token: self .revenue_recovery_data .processor_payment_method_token .clone(), connector_customer_id: self .revenue_recovery_data .connector_customer_id .clone(), }, payment_method_type: self.payment_attempt.payment_method_type, payment_method_subtype: self.payment_attempt.payment_method_subtype, connector: connector.parse().map_err(|err| { router_env::logger::error!(?err, "Failed to parse connector string to enum"); errors::api_error_response::ApiErrorResponse::InternalServerError })?, invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time, invoice_billing_started_at_time: self .revenue_recovery_data .invoice_next_billing_time, billing_connector_payment_method_details, first_payment_attempt_network_advice_code: first_network_advice_code, first_payment_attempt_network_decline_code: first_network_decline_code, first_payment_attempt_pg_error_code: first_pg_error_code, }), None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError) .attach_printable("Connector not found in payment attempt")?, }; Ok(Some(FeatureMetadata { redirect_response: payment_intent_feature_metadata .as_ref() .and_then(|data| data.redirect_response.clone()), search_tags: payment_intent_feature_metadata .as_ref() .and_then(|data| data.search_tags.clone()), apple_pay_recurring_details: payment_intent_feature_metadata .as_ref() .and_then(|data| data.apple_pay_recurring_details.clone()), payment_revenue_recovery_metadata, })) } } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardAndNetworkTokenDataForVault { pub card_data: payment_method_data::Card, pub network_token: NetworkTokenDataForVault, } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct NetworkTokenDataForVault { pub network_token_data: payment_method_data::NetworkTokenData, pub network_token_req_ref_id: String, } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardDataForVault { pub card_data: payment_method_data::Card, pub network_token_req_ref_id: Option<String>, } #[derive(Clone, serde::Serialize, Debug)] pub enum VaultOperation { ExistingVaultData(VaultData), SaveCardData(CardDataForVault), SaveCardAndNetworkTokenData(Box<CardAndNetworkTokenDataForVault>), } impl VaultOperation { pub fn get_updated_vault_data( existing_vault_data: Option<&Self>, payment_method_data: &payment_method_data::PaymentMethodData, ) -> Option<Self> { match (existing_vault_data, payment_method_data) { (None, payment_method_data::PaymentMethodData::Card(card)) => { Some(Self::ExistingVaultData(VaultData::Card(card.clone()))) } (None, payment_method_data::PaymentMethodData::NetworkToken(nt_data)) => Some( Self::ExistingVaultData(VaultData::NetworkToken(nt_data.clone())), ), (Some(Self::ExistingVaultData(vault_data)), payment_method_data) => { match (vault_data, payment_method_data) { ( VaultData::Card(card), payment_method_data::PaymentMethodData::NetworkToken(nt_data), ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( Box::new(CardAndNetworkTokenData { card_data: card.clone(), network_token_data: nt_data.clone(), }), ))), ( VaultData::NetworkToken(nt_data), payment_method_data::PaymentMethodData::Card(card), ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( Box::new(CardAndNetworkTokenData { card_data: card.clone(), network_token_data: nt_data.clone(), }), ))), _ => Some(Self::ExistingVaultData(vault_data.clone())), } } //payment_method_data is not card or network token _ => None, } } } #[derive(Clone, serde::Serialize, Debug)] pub enum VaultData { Card(payment_method_data::Card), NetworkToken(payment_method_data::NetworkTokenData), CardAndNetworkToken(Box<CardAndNetworkTokenData>), } #[derive(Default, Clone, serde::Serialize, Debug)] pub struct CardAndNetworkTokenData { pub card_data: payment_method_data::Card, pub network_token_data: payment_method_data::NetworkTokenData, } impl VaultData { pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> { match self { Self::Card(card_data) => Some(card_data.clone()), Self::NetworkToken(_network_token_data) => None, Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()), } } pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> { match self { Self::Card(_card_data) => None, Self::NetworkToken(network_token_data) => Some(network_token_data.clone()), Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()), } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/payments.rs", "file_size": 55683, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-6621167028748419870
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/payment_methods.rs // File size: 54149 bytes #[cfg(feature = "v2")] use api_models::payment_methods::PaymentMethodsData; use api_models::{customers, payment_methods, payments}; // specific imports because of using the macro use common_enums::enums::MerchantStorageScheme; #[cfg(feature = "v1")] use common_utils::crypto::OptionalEncryptableValue; #[cfg(feature = "v2")] use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable}; use common_utils::{ errors::{CustomResult, ParsingError, ValidationError}, id_type, pii, type_name, types::keymanager, }; pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate}; use error_stack::ResultExt; #[cfg(feature = "v1")] use masking::ExposeInterface; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use router_env::logger; #[cfg(feature = "v2")] use rustc_hash::FxHashMap; #[cfg(feature = "v2")] use serde_json::Value; use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::address::Address; #[cfg(feature = "v1")] use crate::type_encryption::AsyncLift; use crate::{ mandates::{self, CommonMandateReference}, merchant_key_store::MerchantKeyStore, payment_method_data as domain_payment_method_data, transformers::ForeignTryFrom, type_encryption::{crypto_operation, CryptoOperation}, }; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct VaultId(String); impl VaultId { pub fn get_string_repr(&self) -> &String { &self.0 } pub fn generate(id: String) -> Self { Self(id) } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct PaymentMethod { pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, pub payment_method_id: String, pub accepted_currency: Option<Vec<storage_enums::Currency>>, pub scheme: Option<String>, pub token: Option<String>, pub cardholder_name: Option<Secret<String>>, pub issuer_name: Option<String>, pub issuer_country: Option<String>, pub payer_country: Option<Vec<String>>, pub is_stored: Option<bool>, pub swift_code: Option<String>, pub direct_debit_token: Option<String>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method: Option<storage_enums::PaymentMethod>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub payment_method_issuer: Option<String>, pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: OptionalEncryptableValue, pub locker_id: Option<String>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<serde_json::Value>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, pub payment_method_billing_address: OptionalEncryptableValue, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, pub network_token_payment_method_data: OptionalEncryptableValue, pub vault_source_details: PaymentMethodVaultSourceDetails, } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethod { /// The identifier for the payment method. Using this recurring payments can be made pub id: id_type::GlobalPaymentMethodId, /// The customer id against which the payment method is saved pub customer_id: id_type::GlobalCustomerId, /// The merchant id against which the payment method is saved pub merchant_id: id_type::MerchantId, /// The merchant connector account id of the external vault where the payment method is saved pub external_vault_source: Option<id_type::MerchantConnectorAccountId>, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub payment_method_type: Option<storage_enums::PaymentMethod>, pub payment_method_subtype: Option<storage_enums::PaymentMethodType>, #[encrypt(ty = Value)] pub payment_method_data: Option<Encryptable<PaymentMethodsData>>, pub locker_id: Option<VaultId>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<CommonMandateReference>, pub customer_acceptance: Option<pii::SecretSerdeValue>, pub status: storage_enums::PaymentMethodStatus, pub network_transaction_id: Option<String>, pub client_secret: Option<String>, #[encrypt(ty = Value)] pub payment_method_billing_address: Option<Encryptable<Address>>, pub updated_by: Option<String>, pub locker_fingerprint_id: Option<String>, pub version: common_enums::ApiVersion, pub network_token_requestor_reference_id: Option<String>, pub network_token_locker_id: Option<String>, #[encrypt(ty = Value)] pub network_token_payment_method_data: Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>, #[encrypt(ty = Value)] pub external_vault_token_data: Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>, pub vault_type: Option<storage_enums::VaultType>, } impl PaymentMethod { #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v1")] pub fn get_payment_methods_data( &self, ) -> Option<domain_payment_method_data::PaymentMethodsData> { self.payment_method_data .clone() .map(|value| value.into_inner().expose()) .and_then(|value| { serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value) .map_err(|error| { logger::warn!( ?error, "Failed to parse payment method data in payment method info" ); }) .ok() }) } #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId { &self.id } #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method } #[cfg(feature = "v2")] pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> { self.payment_method_type } #[cfg(feature = "v1")] pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_type } #[cfg(feature = "v2")] pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> { self.payment_method_subtype } #[cfg(feature = "v1")] pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> { let payments_data = self .connector_mandate_details .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<mandates::PaymentsMandateReference>(mandate_details) .inspect_err(|err| { router_env::logger::error!("Failed to parse payments data: {:?}", err); }) }) .transpose() .map_err(|err| { router_env::logger::error!("Failed to parse payments data: {:?}", err); ParsingError::StructParseFailure("Failed to parse payments data") })?; let payouts_data = self .connector_mandate_details .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details) .inspect_err(|err| { router_env::logger::error!("Failed to parse payouts data: {:?}", err); }) .map(|optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }) }) .transpose() .map_err(|err| { router_env::logger::error!("Failed to parse payouts data: {:?}", err); ParsingError::StructParseFailure("Failed to parse payouts data") })? .flatten(); Ok(CommonMandateReference { payments: payments_data, payouts: payouts_data, }) } #[cfg(feature = "v2")] pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> { if let Some(value) = &self.connector_mandate_details { Ok(value.clone()) } else { Ok(CommonMandateReference { payments: None, payouts: None, }) } } #[cfg(feature = "v2")] pub fn set_payment_method_type(&mut self, payment_method_type: common_enums::PaymentMethod) { self.payment_method_type = Some(payment_method_type); } #[cfg(feature = "v2")] pub fn set_payment_method_subtype( &mut self, payment_method_subtype: common_enums::PaymentMethodType, ) { self.payment_method_subtype = Some(payment_method_subtype); } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethod { type DstType = diesel_models::payment_method::PaymentMethod; type NewDstType = diesel_models::payment_method::PaymentMethodNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::DstType { customer_id: self.customer_id, merchant_id: self.merchant_id, payment_method_id: self.payment_method_id, accepted_currency: self.accepted_currency, scheme: self.scheme, token: self.token, cardholder_name: self.cardholder_name, issuer_name: self.issuer_name, issuer_country: self.issuer_country, payer_country: self.payer_country, is_stored: self.is_stored, swift_code: self.swift_code, direct_debit_token: self.direct_debit_token, created_at: self.created_at, last_modified: self.last_modified, payment_method: self.payment_method, payment_method_type: self.payment_method_type, payment_method_issuer: self.payment_method_issuer, payment_method_issuer_code: self.payment_method_issuer_code, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id, last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source, vault_type, }) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { // Decrypt encrypted fields first let ( payment_method_data, payment_method_billing_address, network_token_payment_method_data, ) = async { let payment_method_data = item .payment_method_data .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; let payment_method_billing_address = item .payment_method_billing_address .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; let network_token_payment_method_data = item .network_token_payment_method_data .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?; Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(( payment_method_data, payment_method_billing_address, network_token_payment_method_data, )) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), })?; let vault_source_details = PaymentMethodVaultSourceDetails::try_from(( item.vault_type, item.external_vault_source, ))?; // Construct the domain type Ok(Self { customer_id: item.customer_id, merchant_id: item.merchant_id, payment_method_id: item.payment_method_id, accepted_currency: item.accepted_currency, scheme: item.scheme, token: item.token, cardholder_name: item.cardholder_name, issuer_name: item.issuer_name, issuer_country: item.issuer_country, payer_country: item.payer_country, is_stored: item.is_stored, swift_code: item.swift_code, direct_debit_token: item.direct_debit_token, created_at: item.created_at, last_modified: item.last_modified, payment_method: item.payment_method, payment_method_type: item.payment_method_type, payment_method_issuer: item.payment_method_issuer, payment_method_issuer_code: item.payment_method_issuer_code, metadata: item.metadata, payment_method_data, locker_id: item.locker_id, last_used_at: item.last_used_at, connector_mandate_details: item.connector_mandate_details, customer_acceptance: item.customer_acceptance, status: item.status, network_transaction_id: item.network_transaction_id, client_secret: item.client_secret, payment_method_billing_address, updated_by: item.updated_by, version: item.version, network_token_requestor_reference_id: item.network_token_requestor_reference_id, network_token_locker_id: item.network_token_locker_id, network_token_payment_method_data, vault_source_details, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let (vault_type, external_vault_source) = self.vault_source_details.into(); Ok(Self::NewDstType { customer_id: self.customer_id, merchant_id: self.merchant_id, payment_method_id: self.payment_method_id, accepted_currency: self.accepted_currency, scheme: self.scheme, token: self.token, cardholder_name: self.cardholder_name, issuer_name: self.issuer_name, issuer_country: self.issuer_country, payer_country: self.payer_country, is_stored: self.is_stored, swift_code: self.swift_code, direct_debit_token: self.direct_debit_token, created_at: self.created_at, last_modified: self.last_modified, payment_method: self.payment_method, payment_method_type: self.payment_method_type, payment_method_issuer: self.payment_method_issuer, payment_method_issuer_code: self.payment_method_issuer_code, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id, last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source, vault_type, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethod { type DstType = diesel_models::payment_method::PaymentMethod; type NewDstType = diesel_models::payment_method::PaymentMethodNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(Self::DstType { customer_id: self.customer_id, merchant_id: self.merchant_id, id: self.id, created_at: self.created_at, last_modified: self.last_modified, payment_method_type_v2: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()), customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, locker_fingerprint_id: self.locker_fingerprint_id, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_source: self.external_vault_source, external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), vault_type: self.vault_type, }) } async fn convert_back( state: &keymanager::KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { use common_utils::ext_traits::ValueExt; async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable( EncryptedPaymentMethod { payment_method_data: storage_model.payment_method_data, payment_method_billing_address: storage_model .payment_method_billing_address, network_token_payment_method_data: storage_model .network_token_payment_method_data, external_vault_token_data: storage_model.external_vault_token_data, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = EncryptedPaymentMethod::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let payment_method_billing_address = data .payment_method_billing_address .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; let payment_method_data = data .payment_method_data .map(|payment_method_data| { payment_method_data .deserialize_inner_value(|value| value.parse_value("Payment Method Data")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Payment Method Data")?; let network_token_payment_method_data = data .network_token_payment_method_data .map(|network_token_payment_method_data| { network_token_payment_method_data.deserialize_inner_value(|value| { value.parse_value("Network token Payment Method Data") }) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Network token Payment Method Data")?; let external_vault_token_data = data .external_vault_token_data .map(|external_vault_token_data| { external_vault_token_data.deserialize_inner_value(|value| { value.parse_value("External Vault Token Data") }) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing External Vault Token Data")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { customer_id: storage_model.customer_id, merchant_id: storage_model.merchant_id, id: storage_model.id, created_at: storage_model.created_at, last_modified: storage_model.last_modified, payment_method_type: storage_model.payment_method_type_v2, payment_method_subtype: storage_model.payment_method_subtype, payment_method_data, locker_id: storage_model.locker_id.map(VaultId::generate), last_used_at: storage_model.last_used_at, connector_mandate_details: storage_model.connector_mandate_details.map(From::from), customer_acceptance: storage_model.customer_acceptance, status: storage_model.status, network_transaction_id: storage_model.network_transaction_id, client_secret: storage_model.client_secret, payment_method_billing_address, updated_by: storage_model.updated_by, locker_fingerprint_id: storage_model.locker_fingerprint_id, version: storage_model.version, network_token_requestor_reference_id: storage_model .network_token_requestor_reference_id, network_token_locker_id: storage_model.network_token_locker_id, network_token_payment_method_data, external_vault_source: storage_model.external_vault_source, external_vault_token_data, vault_type: storage_model.vault_type, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(Self::NewDstType { customer_id: self.customer_id, merchant_id: self.merchant_id, id: self.id, created_at: self.created_at, last_modified: self.last_modified, payment_method_type_v2: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, payment_method_data: self.payment_method_data.map(|val| val.into()), locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()), customer_acceptance: self.customer_acceptance, status: self.status, network_transaction_id: self.network_transaction_id, client_secret: self.client_secret, payment_method_billing_address: self .payment_method_billing_address .map(|val| val.into()), updated_by: self.updated_by, locker_fingerprint_id: self.locker_fingerprint_id, version: self.version, network_token_requestor_reference_id: self.network_token_requestor_reference_id, network_token_locker_id: self.network_token_locker_id, network_token_payment_method_data: self .network_token_payment_method_data .map(|val| val.into()), external_vault_token_data: self.external_vault_token_data.map(|val| val.into()), vault_type: self.vault_type, }) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct PaymentMethodSession { pub id: id_type::GlobalPaymentMethodSessionId, pub customer_id: id_type::GlobalCustomerId, #[encrypt(ty = Value)] pub billing: Option<Encryptable<Address>>, pub return_url: Option<common_utils::types::Url>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenization_data: Option<pii::SecretSerdeValue>, pub expires_at: PrimitiveDateTime, pub associated_payment_methods: Option<Vec<String>>, pub associated_payment: Option<id_type::GlobalPaymentId>, pub associated_token_id: Option<id_type::GlobalTokenId>, } #[cfg(feature = "v2")] #[async_trait::async_trait] impl super::behaviour::Conversion for PaymentMethodSession { type DstType = diesel_models::payment_methods_session::PaymentMethodSession; type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(Self::DstType { id: self.id, customer_id: self.customer_id, billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, associated_token_id: self.associated_token_id, }) } async fn convert_back( state: &keymanager::KeyManagerState, storage_model: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { use common_utils::ext_traits::ValueExt; async { let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable( EncryptedPaymentMethodSession { billing: storage_model.billing, }, )), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation())?; let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data) .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Invalid batch operation data")?; let billing = data .billing .map(|billing| { billing.deserialize_inner_value(|value| value.parse_value("Address")) }) .transpose() .change_context(common_utils::errors::CryptoError::DecodingFailed) .attach_printable("Error while deserializing Address")?; Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id: storage_model.id, customer_id: storage_model.customer_id, billing, psp_tokenization: storage_model.psp_tokenization, network_tokenization: storage_model.network_tokenization, tokenization_data: storage_model.tokenization_data, expires_at: storage_model.expires_at, associated_payment_methods: storage_model.associated_payment_methods, associated_payment: storage_model.associated_payment, return_url: storage_model.return_url, associated_token_id: storage_model.associated_token_id, }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting payment method data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(Self::NewDstType { id: self.id, customer_id: self.customer_id, billing: self.billing.map(|val| val.into()), psp_tokenization: self.psp_tokenization, network_tokenization: self.network_tokenization, tokenization_data: self.tokenization_data, expires_at: self.expires_at, associated_payment_methods: self.associated_payment_methods, associated_payment: self.associated_payment, return_url: self.return_url, associated_token_id: self.associated_token_id, }) } } #[async_trait::async_trait] pub trait PaymentMethodInterface { type Error; #[cfg(feature = "v1")] async fn find_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_method_by_locker_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; // Need to fix this once we start moving to v2 for payment method #[cfg(feature = "v2")] async fn find_payment_method_list_by_global_customer_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<PaymentMethod>, Self::Error>; #[cfg(feature = "v1")] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, Self::Error>; async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, Self::Error>; async fn insert_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; async fn update_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, payment_method_update: PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn delete_payment_method( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, payment_method: PaymentMethod, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v2")] async fn find_payment_method_by_fingerprint_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<PaymentMethod, Self::Error>; #[cfg(feature = "v1")] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &keymanager::KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<PaymentMethod, Self::Error>; } #[cfg(feature = "v2")] pub enum PaymentMethodsSessionUpdateEnum { GeneralUpdate { billing: Box<Option<Encryptable<Address>>>, psp_tokenization: Option<common_types::payment_methods::PspTokenization>, network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, tokenization_data: Option<pii::SecretSerdeValue>, }, UpdateAssociatedPaymentMethods { associated_payment_methods: Option<Vec<String>>, }, } #[cfg(feature = "v2")] impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateInternal { fn from(update: PaymentMethodsSessionUpdateEnum) -> Self { match update { PaymentMethodsSessionUpdateEnum::GeneralUpdate { billing, psp_tokenization, network_tokenization, tokenization_data, } => Self { billing: *billing, psp_tokenization, network_tokenization, tokenization_data, associated_payment_methods: None, }, PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods { associated_payment_methods, } => Self { billing: None, psp_tokenization: None, network_tokenization: None, tokenization_data: None, associated_payment_methods, }, } } } #[cfg(feature = "v2")] impl PaymentMethodSession { pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self { let Self { id, customer_id, billing, psp_tokenization, network_tokenization, tokenization_data, expires_at, return_url, associated_payment_methods, associated_payment, associated_token_id, } = self; Self { id, customer_id, billing: update_session.billing.or(billing), psp_tokenization: update_session.psp_tokenization.or(psp_tokenization), network_tokenization: update_session.network_tokenization.or(network_tokenization), tokenization_data: update_session.tokenization_data.or(tokenization_data), expires_at, return_url, associated_payment_methods: update_session .associated_payment_methods .or(associated_payment_methods), associated_payment, associated_token_id, } } } #[cfg(feature = "v2")] pub struct PaymentMethodsSessionUpdateInternal { pub billing: Option<Encryptable<Address>>, pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, pub tokenization_data: Option<pii::SecretSerdeValue>, pub associated_payment_methods: Option<Vec<String>>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct ConnectorCustomerDetails { pub connector_customer_id: String, pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodCustomerMigrate { pub customer: customers::CustomerRequest, pub connector_customer_details: Option<Vec<ConnectorCustomerDetails>>, } #[cfg(feature = "v1")] impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)> for PaymentMethodCustomerMigrate { type Error = error_stack::Report<ValidationError>; fn try_from( value: (payment_methods::PaymentMethodRecord, id_type::MerchantId), ) -> Result<Self, Self::Error> { let (record, merchant_id) = value; let connector_customer_details = record .connector_customer_id .and_then(|connector_customer_id| { // Handle single merchant_connector_id record .merchant_connector_id .as_ref() .map(|merchant_connector_id| { Ok(vec![ConnectorCustomerDetails { connector_customer_id: connector_customer_id.clone(), merchant_connector_id: merchant_connector_id.clone(), }]) }) // Handle comma-separated merchant_connector_ids .or_else(|| { record .merchant_connector_ids .as_ref() .map(|merchant_connector_ids_str| { merchant_connector_ids_str .split(',') .map(|id| id.trim()) .filter(|id| !id.is_empty()) .map(|merchant_connector_id| { id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .map_err(|_| { error_stack::report!(ValidationError::InvalidValue { message: format!( "Invalid merchant_connector_account_id: {merchant_connector_id}" ), }) }) .map( |merchant_connector_id| ConnectorCustomerDetails { connector_customer_id: connector_customer_id .clone(), merchant_connector_id, }, ) }) .collect::<Result<Vec<_>, _>>() }) }) }) .transpose()?; Ok(Self { customer: customers::CustomerRequest { 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: record.billing_address_city, country: record.billing_address_country, line1: record.billing_address_line1, line2: record.billing_address_line2, state: record.billing_address_state, line3: record.billing_address_line3, zip: record.billing_address_zip, first_name: record.billing_address_first_name, last_name: record.billing_address_last_name, origin_zip: None, }), metadata: None, tax_registration_id: None, }, connector_customer_details, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<(&[payment_methods::PaymentMethodRecord], id_type::MerchantId)> for Vec<PaymentMethodCustomerMigrate> { type Error = error_stack::Report<ValidationError>; fn foreign_try_from( (records, merchant_id): (&[payment_methods::PaymentMethodRecord], id_type::MerchantId), ) -> Result<Self, Self::Error> { let (customers_migration, migration_errors): (Self, Vec<_>) = records .iter() .map(|record| { PaymentMethodCustomerMigrate::try_from((record.clone(), merchant_id.clone())) }) .fold((Self::new(), Vec::new()), |mut acc, result| { match result { Ok(customer) => acc.0.push(customer), Err(e) => acc.1.push(e.to_string()), } acc }); migration_errors .is_empty() .then_some(customers_migration) .ok_or_else(|| { error_stack::report!(ValidationError::InvalidValue { message: migration_errors.join(", "), }) }) } } #[cfg(feature = "v1")] #[derive(Clone, Debug, Default)] pub enum PaymentMethodVaultSourceDetails { ExternalVault { external_vault_source: id_type::MerchantConnectorAccountId, }, #[default] InternalVault, } #[cfg(feature = "v1")] impl TryFrom<( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, )> for PaymentMethodVaultSourceDetails { type Error = error_stack::Report<ValidationError>; fn try_from( value: ( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { match value { (Some(storage_enums::VaultType::External), Some(external_vault_source)) => { Ok(Self::ExternalVault { external_vault_source, }) } (Some(storage_enums::VaultType::External), None) => { Err(ValidationError::MissingRequiredField { field_name: "external vault mca id".to_string(), } .into()) } (Some(storage_enums::VaultType::Internal), _) | (None, _) => Ok(Self::InternalVault), // defaulting to internal vault if vault type is none } } } #[cfg(feature = "v1")] impl From<PaymentMethodVaultSourceDetails> for ( Option<storage_enums::VaultType>, Option<id_type::MerchantConnectorAccountId>, ) { fn from(value: PaymentMethodVaultSourceDetails) -> Self { match value { PaymentMethodVaultSourceDetails::ExternalVault { external_vault_source, } => ( Some(storage_enums::VaultType::External), Some(external_vault_source), ), PaymentMethodVaultSourceDetails::InternalVault => { (Some(storage_enums::VaultType::Internal), None) } } } } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use id_type::MerchantConnectorAccountId; use super::*; fn get_payment_method_with_mandate_data( mandate_data: Option<serde_json::Value>, ) -> PaymentMethod { let payment_method = PaymentMethod { customer_id: id_type::CustomerId::default(), merchant_id: id_type::MerchantId::default(), payment_method_id: String::from("abc"), accepted_currency: None, scheme: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: common_utils::date_time::now(), last_modified: common_utils::date_time::now(), payment_method: None, payment_method_type: None, payment_method_issuer: None, payment_method_issuer_code: None, metadata: None, payment_method_data: None, locker_id: None, last_used_at: common_utils::date_time::now(), connector_mandate_details: mandate_data, customer_acceptance: None, status: storage_enums::PaymentMethodStatus::Active, network_transaction_id: None, client_secret: None, payment_method_billing_address: None, updated_by: None, version: common_enums::ApiVersion::V1, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, vault_source_details: Default::default(), }; payment_method.clone() } #[test] fn test_get_common_mandate_reference_payments_only() { let connector_mandate_details = serde_json::json!({ "mca_kGz30G8B95MxRwmeQqy6": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o", "connector_mandate_status": "active", "original_payment_authorized_amount": 51, "original_payment_authorized_currency": "USD", "connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk" } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_none()); let payments = common_mandate.payments.unwrap(); let result_mca = MerchantConnectorAccountId::wrap("mca_kGz30G8B95MxRwmeQqy6".to_string()); assert!( result_mca.is_ok(), "Expected Ok, but got Err: {result_mca:?}", ); let mca = result_mca.unwrap(); assert!(payments.0.contains_key(&mca)); } #[test] fn test_get_common_mandate_reference_empty_details() { let payment_method = get_payment_method_with_mandate_data(None); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_none()); assert!(common_mandate.payouts.is_none()); } #[test] fn test_get_common_mandate_reference_payouts_only() { let connector_mandate_details = serde_json::json!({ "payouts": { "mca_DAHVXbXpbYSjnL7fQWEs": { "transfer_method_id": "TRM-678ab3997b16cb7cd" } } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_some()); let payouts = common_mandate.payouts.unwrap(); let result_mca = MerchantConnectorAccountId::wrap("mca_DAHVXbXpbYSjnL7fQWEs".to_string()); assert!( result_mca.is_ok(), "Expected Ok, but got Err: {result_mca:?}", ); let mca = result_mca.unwrap(); assert!(payouts.0.contains_key(&mca)); } #[test] fn test_get_common_mandate_reference_invalid_data() { let connector_mandate_details = serde_json::json!("invalid"); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_err()); } #[test] fn test_get_common_mandate_reference_with_payments_and_payouts_details() { let connector_mandate_details = serde_json::json!({ "mca_kGz30G8B95MxRwmeQqy6": { "mandate_metadata": null, "payment_method_type": null, "connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o", "connector_mandate_status": "active", "original_payment_authorized_amount": 51, "original_payment_authorized_currency": "USD", "connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk" }, "payouts": { "mca_DAHVXbXpbYSjnL7fQWEs": { "transfer_method_id": "TRM-678ab3997b16cb7cd" } } }); let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details)); let result = payment_method.get_common_mandate_reference(); assert!(result.is_ok()); let common_mandate = result.unwrap(); assert!(common_mandate.payments.is_some()); assert!(common_mandate.payouts.is_some()); } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/payment_methods.rs", "file_size": 54149, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-5880454141130917788
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/type_encryption.rs // File size: 52832 bytes use async_trait::async_trait; use common_utils::{ crypto, encryption::Encryption, errors::{self, CustomResult}, ext_traits::AsyncExt, metrics::utils::record_operation_time, types::keymanager::{Identifier, KeyManagerState}, }; use encrypt::TypeEncryption; use masking::Secret; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; mod encrypt { use async_trait::async_trait; use common_utils::{ crypto, encryption::Encryption, errors::{self, CustomResult}, ext_traits::ByteSliceExt, keymanager::call_encryption_service, transformers::{ForeignFrom, ForeignTryFrom}, types::keymanager::{ BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse, DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier, KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; use error_stack::ResultExt; use http::Method; use masking::{PeekInterface, Secret}; use router_env::{instrument, logger, tracing}; use rustc_hash::FxHashMap; use super::{metrics, EncryptedJsonType}; #[async_trait] pub trait TypeEncryption< T, V: crypto::EncodeMessage + crypto::DecodeMessage, S: masking::Strategy<T>, >: Sized { async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<T, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn encrypt( masked_data: Secret<T, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError>; async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<T, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_encrypt( masked_data: FxHashMap<String, Secret<T, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>; } fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool { #[cfg(feature = "encryption_service")] { _state.enabled } #[cfg(not(feature = "encryption_service"))] { false } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<String> + Send + Sync, > TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<String, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<String, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: String = std::str::from_utf8(&data) .change_context(errors::CryptoError::DecodingFailed)? .to_string(); Ok(Self::new(value.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<String, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<String, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new( v.clone(), crypt_algo.encode_message(key, v.peek().as_bytes())?.into(), ), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { let data = crypt_algo.decode_message(key, v.clone().into_inner())?; let value: String = std::str::from_utf8(&data) .change_context(errors::CryptoError::DecodingFailed)? .to_string(); Ok((k, Self::new(value.into(), v.into_inner()))) }) .collect() } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<serde_json::Value> + Send + Sync, > TypeEncryption<serde_json::Value, V, S> for crypto::Encryptable<Secret<serde_json::Value, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<serde_json::Value, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::EncodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<serde_json::Value, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let data = serde_json::to_vec(&masked_data.peek()) .change_context(errors::CryptoError::DecodingFailed)?; let encrypted_data = crypt_algo.encode_message(key, &data)?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; let value: serde_json::Value = serde_json::from_slice(&data) .change_context(errors::CryptoError::DecodingFailed)?; Ok(Self::new(value.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<serde_json::Value, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { let data = serde_json::to_vec(v.peek()) .change_context(errors::CryptoError::DecodingFailed)?; Ok(( k, Self::new(v, crypt_algo.encode_message(key, &data)?.into()), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?; let value: serde_json::Value = serde_json::from_slice(&data) .change_context(errors::CryptoError::DecodingFailed)?; Ok((k, Self::new(value.into(), v.into_inner()))) }) .collect() } } impl<T> EncryptedJsonType<T> where T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned, { fn serialize_json_bytes(&self) -> CustomResult<Secret<Vec<u8>>, errors::CryptoError> { common_utils::ext_traits::Encode::encode_to_vec(self.inner()) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to JSON serialize data before encryption") .map(Secret::new) } fn deserialize_json_bytes<S>( bytes: Secret<Vec<u8>>, ) -> CustomResult<Secret<Self, S>, errors::ParsingError> where S: masking::Strategy<Self>, { bytes .peek() .as_slice() .parse_struct::<T>(std::any::type_name::<T>()) .map(|result| Secret::new(Self::from(result))) .attach_printable("Failed to JSON deserialize data after decryption") } } #[async_trait] impl< T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned + Send, V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<EncryptedJsonType<T>> + Send + Sync, > TypeEncryption<EncryptedJsonType<T>, V, S> for crypto::Encryptable<Secret<EncryptedJsonType<T>, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<EncryptedJsonType<T>, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?; let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::encrypt_via_api(state, data_bytes, identifier, key, crypt_algo) .await?; Ok(Self::new(masked_data, result.into_encrypted())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::decrypt_via_api(state, encrypted_data, identifier, key, crypt_algo) .await?; result .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<EncryptedJsonType<T>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?; let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::encrypt(data_bytes, key, crypt_algo).await?; Ok(Self::new(masked_data, result.into_encrypted())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { let result: crypto::Encryptable<Secret<Vec<u8>>> = TypeEncryption::decrypt(encrypted_data, key, crypt_algo).await?; result .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let hashmap_capacity = masked_data.len(); let data_bytes = masked_data.iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?; map.insert(key.to_owned(), value_bytes); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_encrypt_via_api( state, data_bytes, identifier, key, crypt_algo, ) .await?; let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let original_value = masked_data .get(&key) .ok_or(errors::CryptoError::EncodingFailed) .attach_printable_lazy(|| { format!("Failed to find {key} in input hashmap") })?; map.insert( key, Self::new(original_value.clone(), value.into_encrypted()), ); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_decrypt_via_api( state, encrypted_data, identifier, key, crypt_algo, ) .await?; let hashmap_capacity = result.len(); let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let deserialized_value = value .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed)?; map.insert(key, deserialized_value); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let hashmap_capacity = masked_data.len(); let data_bytes = masked_data.iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?; map.insert(key.to_owned(), value_bytes); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_encrypt(data_bytes, key, crypt_algo).await?; let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let original_value = masked_data .get(&key) .ok_or(errors::CryptoError::EncodingFailed) .attach_printable_lazy(|| { format!("Failed to find {key} in input hashmap") })?; map.insert( key, Self::new(original_value.clone(), value.into_encrypted()), ); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> = TypeEncryption::batch_decrypt(encrypted_data, key, crypt_algo).await?; let hashmap_capacity = result.len(); let result_hashmap = result.into_iter().try_fold( FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()), |mut map, (key, value)| { let deserialized_value = value .deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes) .change_context(errors::CryptoError::DecodingFailed)?; map.insert(key, deserialized_value); Ok::<_, error_stack::Report<errors::CryptoError>>(map) }, )?; Ok(result_hashmap) } } #[async_trait] impl< V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static, S: masking::Strategy<Vec<u8>> + Send + Sync, > TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>> { // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt_via_api( state: &KeyManagerState, masked_data: Secret<Vec<u8>, S>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::encrypt(masked_data, key, crypt_algo).await } else { let result: Result< EncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", EncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))), Err(err) => { logger::error!("Encryption error {:?}", err); metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Encryption"); Self::encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt_via_api( state: &KeyManagerState, encrypted_data: Encryption, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< DecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(decrypted_data) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn encrypt( masked_data: Secret<Vec<u8>, S>, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?; Ok(Self::new(masked_data, encrypted_data.into())) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn decrypt( encrypted_data: Encryption, key: &[u8], crypt_algo: V, ) -> CustomResult<Self, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); let encrypted = encrypted_data.into_inner(); let data = crypt_algo.decode_message(key, encrypted.clone())?; Ok(Self::new(data.into(), encrypted)) } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt_via_api( state: &KeyManagerState, masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_encrypt(masked_data, key, crypt_algo).await } else { let result: Result< BatchEncryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/encrypt", BatchEncryptDataRequest::from((masked_data.clone(), identifier)), ) .await; match result { Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))), Err(err) => { metrics::ENCRYPTION_API_FAILURES.add(1, &[]); logger::error!("Encryption error {:?}", err); logger::info!("Fall back to Application Encryption"); Self::batch_encrypt(masked_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt_via_api( state: &KeyManagerState, encrypted_data: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { // If encryption service is not enabled, fall back to application encryption or else call encryption service if !is_encryption_service_enabled(state) { Self::batch_decrypt(encrypted_data, key, crypt_algo).await } else { let result: Result< BatchDecryptDataResponse, error_stack::Report<errors::KeyManagerClientError>, > = call_encryption_service( state, Method::POST, "data/decrypt", TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)), ) .await; let decrypted = match result { Ok(response) => { ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response)) } Err(err) => { logger::error!("Decryption error {:?}", err); Err(err.change_context(errors::CryptoError::DecodingFailed)) } }; match decrypted { Ok(de) => Ok(de), Err(_) => { metrics::DECRYPTION_API_FAILURES.add(1, &[]); logger::info!("Fall back to Application Decryption"); Self::batch_decrypt(encrypted_data, key, crypt_algo).await } } } } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_encrypt( masked_data: FxHashMap<String, Secret<Vec<u8>, S>>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]); masked_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()), )) }) .collect() } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all)] async fn batch_decrypt( encrypted_data: FxHashMap<String, Encryption>, key: &[u8], crypt_algo: V, ) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> { metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]); encrypted_data .into_iter() .map(|(k, v)| { Ok(( k, Self::new( crypt_algo .decode_message(key, v.clone().into_inner().clone())? .into(), v.into_inner(), ), )) }) .collect() } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EncryptedJsonType<T>(T); impl<T> EncryptedJsonType<T> { pub fn inner(&self) -> &T { &self.0 } pub fn into_inner(self) -> T { self.0 } } impl<T> From<T> for EncryptedJsonType<T> { fn from(value: T) -> Self { Self(value) } } impl<T> std::ops::Deref for EncryptedJsonType<T> { type Target = T; fn deref(&self) -> &Self::Target { self.inner() } } /// Type alias for `Option<Encryptable<Secret<EncryptedJsonType<T>>>>` pub type OptionalEncryptableJsonType<T> = Option<crypto::Encryptable<Secret<EncryptedJsonType<T>>>>; pub trait Lift<U> { type SelfWrapper<T>; type OtherWrapper<T, E>; fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>; } impl<U> Lift<U> for Option<U> { type SelfWrapper<T> = Option<T>; type OtherWrapper<T, E> = CustomResult<Option<T>, E>; fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>, { func(self) } } #[async_trait] pub trait AsyncLift<U> { type SelfWrapper<T>; type OtherWrapper<T, E>; async fn async_lift<Func, F, E, V>(self, func: Func) -> Self::OtherWrapper<V, E> where Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync, F: futures::Future<Output = Self::OtherWrapper<V, E>> + Send; } #[async_trait] impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V { type SelfWrapper<T> = <V as Lift<U>>::SelfWrapper<T>; type OtherWrapper<T, E> = <V as Lift<U>>::OtherWrapper<T, E>; async fn async_lift<Func, F, E, W>(self, func: Func) -> Self::OtherWrapper<W, E> where Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync, F: futures::Future<Output = Self::OtherWrapper<W, E>> + Send, { func(self).await } } #[inline] async fn encrypt<E: Clone, S>( state: &KeyManagerState, inner: Secret<E, S>, identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<E, S>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { record_operation_time( crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::ENCRYPTION_TIME, &[], ) .await } #[inline] async fn batch_encrypt<E: Clone, S>( state: &KeyManagerState, inner: FxHashMap<String, Secret<E, S>>, identifier: Identifier, key: &[u8], ) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { if !inner.is_empty() { record_operation_time( crypto::Encryptable::batch_encrypt_via_api( state, inner, identifier, key, crypto::GcmAes256, ), &metrics::ENCRYPTION_TIME, &[], ) .await } else { Ok(FxHashMap::default()) } } #[inline] async fn encrypt_optional<E: Clone, S>( state: &KeyManagerState, inner: Option<Secret<E, S>>, identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, CryptoError> where Secret<E, S>: Send, S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { inner .async_map(|f| encrypt(state, f, identifier, key)) .await .transpose() } #[inline] async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>( state: &KeyManagerState, inner: Option<Encryption>, identifier: Identifier, key: &[u8], ) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { inner .async_map(|item| decrypt(state, item, identifier, key)) .await .transpose() } #[inline] async fn decrypt<T: Clone, S: masking::Strategy<T>>( state: &KeyManagerState, inner: Encryption, identifier: Identifier, key: &[u8], ) -> CustomResult<crypto::Encryptable<Secret<T, S>>, CryptoError> where crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { record_operation_time( crypto::Encryptable::decrypt_via_api(state, inner, identifier, key, crypto::GcmAes256), &metrics::DECRYPTION_TIME, &[], ) .await } #[inline] async fn batch_decrypt<E: Clone, S>( state: &KeyManagerState, inner: FxHashMap<String, Encryption>, identifier: Identifier, key: &[u8], ) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError> where S: masking::Strategy<E>, crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>, { if !inner.is_empty() { record_operation_time( crypto::Encryptable::batch_decrypt_via_api( state, inner, identifier, key, crypto::GcmAes256, ), &metrics::ENCRYPTION_TIME, &[], ) .await } else { Ok(FxHashMap::default()) } } pub enum CryptoOperation<T: Clone, S: masking::Strategy<T>> { Encrypt(Secret<T, S>), EncryptOptional(Option<Secret<T, S>>), Decrypt(Encryption), DecryptOptional(Option<Encryption>), BatchEncrypt(FxHashMap<String, Secret<T, S>>), BatchDecrypt(FxHashMap<String, Encryption>), } use errors::CryptoError; #[derive(router_derive::TryGetEnumVariant)] #[error(CryptoError::EncodingFailed)] pub enum CryptoOutput<T: Clone, S: masking::Strategy<T>> { Operation(crypto::Encryptable<Secret<T, S>>), OptionalOperation(Option<crypto::Encryptable<Secret<T, S>>>), BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>), } // Do not remove the `skip_all` as the key would be logged otherwise #[instrument(skip_all, fields(table = table_name))] pub async fn crypto_operation<T: Clone + Send, S: masking::Strategy<T>>( state: &KeyManagerState, table_name: &str, operation: CryptoOperation<T, S>, identifier: Identifier, key: &[u8], ) -> CustomResult<CryptoOutput<T, S>, CryptoError> where Secret<T, S>: Send, crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>, { match operation { CryptoOperation::Encrypt(data) => { let data = encrypt(state, data, identifier, key).await?; Ok(CryptoOutput::Operation(data)) } CryptoOperation::EncryptOptional(data) => { let data = encrypt_optional(state, data, identifier, key).await?; Ok(CryptoOutput::OptionalOperation(data)) } CryptoOperation::Decrypt(data) => { let data = decrypt(state, data, identifier, key).await?; Ok(CryptoOutput::Operation(data)) } CryptoOperation::DecryptOptional(data) => { let data = decrypt_optional(state, data, identifier, key).await?; Ok(CryptoOutput::OptionalOperation(data)) } CryptoOperation::BatchEncrypt(data) => { let data = batch_encrypt(state, data, identifier, key).await?; Ok(CryptoOutput::BatchOperation(data)) } CryptoOperation::BatchDecrypt(data) => { let data = batch_decrypt(state, data, identifier, key).await?; Ok(CryptoOutput::BatchOperation(data)) } } } pub(crate) mod metrics { use router_env::{counter_metric, global_meter, histogram_metric_f64}; global_meter!(GLOBAL_METER, "ROUTER_API"); // Encryption and Decryption metrics histogram_metric_f64!(ENCRYPTION_TIME, GLOBAL_METER); histogram_metric_f64!(DECRYPTION_TIME, GLOBAL_METER); counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER); counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER); counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER); counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER); }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/type_encryption.rs", "file_size": 52832, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-4271311096126242454
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/errors/api_error_response.rs // File size: 45626 bytes use api_models::errors::types::Extra; use common_utils::errors::ErrorSwitch; use http::StatusCode; use crate::router_data; #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorType { InvalidRequestError, ObjectNotFound, RouterError, ProcessingError, BadGateway, ServerNotAvailable, DuplicateRequest, ValidationError, ConnectorError, LockTimeout, } // CE Connector Error Errors originating from connector's end // HE Hyperswitch Error Errors originating from Hyperswitch's end // IR Invalid Request Error Error caused due to invalid fields and values in API request // WE Webhook Error Errors related to Webhooks #[derive(Debug, Clone, router_derive::ApiError)] #[error(error_type_enum = ErrorType)] pub enum ApiErrorResponse { #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, reason: Option<String>, }, #[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")] PaymentAuthorizationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")] PaymentAuthenticationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")] PaymentCaptureFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")] InvalidCardData { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")] CardExpired { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")] RefundFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")] VerificationFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")] ResourceBusy, #[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")] InternalServerError, #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")] HealthCheckError { component: &'static str, message: String, }, #[error(error_type = ErrorType::ValidationError, code = "HE_00", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")] DuplicateRefundRequest, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")] DuplicateMandate, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")] DuplicateMerchantAccount, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")] DuplicatePaymentMethod, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")] DuplicatePayment { payment_id: common_utils::id_type::PaymentId, }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id:?}' already exists in our records")] DuplicatePayout { payout_id: common_utils::id_type::PayoutId, }, #[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")] DuplicateConfig, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")] RefundNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")] CustomerNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Config key does not exist in our records.")] ConfigNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")] PaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")] PaymentMethodNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")] MerchantAccountNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")] ProfileNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'.")] ProfileAcquirerNotFound { profile_acquirer_id: String, profile_id: String, }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")] PollNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")] ResourceIdNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")] MandateNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")] AuthenticationNotFound { id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")] MandateUpdateFailed, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")] ApiKeyNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")] PayoutNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")] EventNotFound, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")] MandateSerializationFailed, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")] MandateDeserializationFailed, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")] ReturnUrlUnavailable, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")] RefundNotPossible { connector: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )] MandateValidationFailed { reason: String }, #[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")] PaymentNotSucceeded, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")] FileValidationFailed { reason: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Dispute status validation failed")] DisputeStatusValidationFailed { reason: String }, #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")] AddressNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")] DisputeNotFound { dispute_id: String }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")] FileNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")] FileNotAvailable, #[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Missing tenant id")] MissingTenantId, #[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Invalid tenant id: {tenant_id}")] InvalidTenant { tenant_id: String }, #[error(error_type = ErrorType::ValidationError, code = "HE_06", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")] NotImplemented { message: NotImplementedMessage }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_01", message = "API key not provided or invalid API key used" )] Unauthorized, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")] InvalidRequestUrl, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")] InvalidHttpMethod, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_05", message = "{field_name} contains invalid data. Expected format is {expected_format}" )] InvalidDataFormat { field_name: String, expected_format: String, }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")] InvalidRequestData { message: String }, /// Typically used when a field has invalid value, or deserialization of the value contained in a field fails. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")] InvalidDataValue { field_name: &'static str }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")] ClientSecretNotGiven, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")] ClientSecretExpired, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")] ClientSecretInvalid, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")] MandateActive, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")] CustomerRedacted, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")] MaximumRefundCount, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")] RefundAmountExceedsPaymentAmount, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")] PaymentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")] InvalidEphemeralKey, /// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition. #[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")] PreconditionFailed { message: String }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_17", message = "Access forbidden, invalid JWT token was used" )] InvalidJwtToken, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_18", message = "{message}", )] GenericUnauthorized { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] NotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")] FlowNotSupported { flow: String, connector: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")] MissingRequiredFields { field_names: Vec<&'static str> }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")] AccessForbidden { resource: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")] FileProviderNotSupported { message: String }, #[error( error_type = ErrorType::ProcessingError, code = "IR_24", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_26", message = "Invalid Cookie" )] InvalidCookie, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_29", message = "{message}")] UnprocessableEntity { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_30", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_31", message = "Card with the provided iin does not exist")] InvalidCardIin, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_32", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")] InvalidCardIinLength, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_33", message = "File not found / valid in the request")] MissingFile, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_34", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_35", message = "File purpose not found in the request or is invalid")] MissingFilePurpose, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_36", message = "File content type not found / valid")] MissingFileContentType, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_37", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_38", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_39", message = "required payment method is not configured or configured incorrectly for all configured connectors")] IncorrectPaymentMethodConfiguration, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_40", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, #[error( error_type = ErrorType::InvalidRequestError, code = "IR_42", message = "Cookies are not found in the request" )] CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")] PlatformAccountAuthNotSupported, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")] InvalidPlatformOperation, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_45", message = "External vault failed during processing with connector")] ExternalVaultFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_46", message = "Field {fields} doesn't match with the ones used during mandate creation")] MandatePaymentDataMismatch { fields: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_47", message = "Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}")] MaxFieldLengthViolated { connector: String, field_name: String, max_length: usize, received_length: usize, }, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")] WebhookBadRequest, #[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")] WebhookProcessingFailure, #[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")] WebhookResourceNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")] WebhookUnprocessableEntity, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")] WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")] TokenizationRecordNotFound { id: String }, #[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")] SubscriptionError { operation: String }, } #[derive(Clone)] pub enum NotImplementedMessage { Reason(String), Default, } impl std::fmt::Debug for NotImplementedMessage { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Reason(message) => write!(fmt, "{message} is not implemented"), Self::Default => { write!( fmt, "This API is under development and will be made available soon." ) } } } } impl ::core::fmt::Display for ApiErrorResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, r#"{{"error":{}}}"#, serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse { fn switch(&self) -> api_models::errors::types::ApiErrorResponse { use api_models::errors::types::{ApiError, ApiErrorResponse as AER}; match self { Self::ExternalConnectorError { code, message, connector, reason, status_code, } => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)), Self::PaymentAuthorizationFailed { data } => { AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::PaymentAuthenticationFailed { data } => { AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::PaymentCaptureFailed { data } => { AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))), Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))), Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))), Self::VerificationFailed { data } => { AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) }, Self::DisputeFailed { data } => { AER::BadRequest(ApiError::new("CE", 8, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()}))) } Self::ResourceBusy => { AER::Unprocessable(ApiError::new("HE", 0, "There was an issue processing the webhook body", None)) } Self::CurrencyConversionFailed => { AER::Unprocessable(ApiError::new("HE", 0, "Failed to convert currency to minor unit", None)) } Self::InternalServerError => { AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None)) }, Self::HealthCheckError { message,component } => { AER::InternalServerError(ApiError::new("HE",0,format!("{component} health check failed with error: {message}"),None)) }, Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)), Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)), Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)), Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => { AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None)) } Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)), Self::DuplicatePayment { payment_id } => { AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id:?} already exists")), ..Default::default()}))) } Self::DuplicatePayout { payout_id } => { AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id:?}' already exists in our records"), None)) } Self::DuplicateConfig => { AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None)) } Self::RefundNotFound => { AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None)) } Self::PaymentLinkNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None)) } Self::CustomerNotFound => { AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None)) } Self::ConfigNotFound => { AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None)) }, Self::PaymentNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None)) } Self::PaymentMethodNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None)) } Self::MerchantAccountNotFound => { AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None)) } Self::MerchantConnectorAccountNotFound {id } => { AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()}))) } Self::ProfileNotFound { id } => { AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None)) } Self::ProfileAcquirerNotFound { profile_acquirer_id, profile_id } => { AER::NotFound(ApiError::new("HE", 2, format!("Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'."), None)) } Self::PollNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None)) }, Self::ResourceIdNotFound => { AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None)) } Self::MandateNotFound => { AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None)) } Self::AuthenticationNotFound { .. } => { AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None)) }, Self::MandateUpdateFailed => { AER::InternalServerError(ApiError::new("HE", 2, "Mandate update failed", None)) }, Self::ApiKeyNotFound => { AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None)) } Self::PayoutNotFound => { AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None)) } Self::EventNotFound => { AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None)) } Self::MandateSerializationFailed | Self::MandateDeserializationFailed => { AER::InternalServerError(ApiError::new("HE", 3, "Something went wrong", None)) }, Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)), Self::RefundNotPossible { connector } => { AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None)) } Self::MandateValidationFailed { reason } => { AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() }))) } Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), Self::MerchantConnectorAccountDisabled => { AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None)) } Self::PaymentBlockedError { message, reason, .. } => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))), Self::FileValidationFailed { reason } => { AER::BadRequest(ApiError::new("HE", 3, format!("File validation failed {reason}"), None)) } Self::DisputeStatusValidationFailed { .. } => { AER::BadRequest(ApiError::new("HE", 3, "Dispute status validation failed", None)) } Self::SuccessfulPaymentNotFound => { AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) } Self::IncorrectConnectorNameGiven => { AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None)) } Self::AddressNotFound => { AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None)) }, Self::DisputeNotFound { .. } => { AER::NotFound(ApiError::new("HE", 4, "Dispute does not exist in our records", None)) }, Self::FileNotFound => { AER::NotFound(ApiError::new("HE", 4, "File does not exist in our records", None)) } Self::FileNotAvailable => { AER::NotFound(ApiError::new("HE", 4, "File not available", None)) } Self::MissingTenantId => { AER::InternalServerError(ApiError::new("HE", 5, "Missing Tenant ID in the request".to_string(), None)) } Self::InvalidTenant { tenant_id } => { AER::InternalServerError(ApiError::new("HE", 5, format!("Invalid Tenant {tenant_id}"), None)) } Self::AmountConversionFailed { amount_type } => { AER::InternalServerError(ApiError::new("HE", 6, format!("Failed to convert amount to {amount_type} type"), None)) } Self::NotImplemented { message } => { AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None)) } Self::Unauthorized => AER::Unauthorized(ApiError::new( "IR", 1, "API key not provided or invalid API key used", None )), Self::InvalidRequestUrl => { AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None)) } Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new( "IR", 3, "The HTTP method is not applicable for this API", None )), Self::MissingRequiredField { field_name } => AER::BadRequest( ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None), ), Self::InvalidDataFormat { field_name, expected_format, } => AER::Unprocessable(ApiError::new( "IR", 5, format!( "{field_name} contains invalid data. Expected format is {expected_format}" ), None )), Self::InvalidRequestData { message } => { AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None)) } Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new( "IR", 7, format!("Invalid value provided: {field_name}"), None )), Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new( "IR", 8, "client_secret was not provided", None )), Self::ClientSecretExpired => AER::BadRequest(ApiError::new( "IR", 8, "The provided client_secret has expired", None )), Self::ClientSecretInvalid => { AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None)) } Self::MandateActive => { AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None)) } Self::CustomerRedacted => { AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None)) } Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)), Self::RefundAmountExceedsPaymentAmount => { AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None)) } Self::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)), Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)), Self::PreconditionFailed { message } => { AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None)) } Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)), Self::GenericUnauthorized { message } => { AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None)) }, Self::NotSupported { message } => { AER::BadRequest(ApiError::new("IR", 19, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()}))) }, Self::FlowNotSupported { flow, connector } => { AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message } Self::MissingRequiredFields { field_names } => AER::BadRequest( ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })), ), Self::AccessForbidden {resource} => { AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None)) }, Self::FileProviderNotSupported { message } => { AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None)) }, Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new( "IR", 24, format!("Invalid {wallet_name} wallet token"), None )), Self::PaymentMethodDeleteFailed => { AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None)) } Self::InvalidCookie => { AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None)) } Self::ExtendedCardInfoNotFound => { AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None)) } Self::CurrencyNotSupported { message } => { AER::BadRequest(ApiError::new("IR", 28, message, None)) } Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 29, message.to_string(), None)), Self::InvalidConnectorConfiguration {config} => { AER::BadRequest(ApiError::new("IR", 30, format!("Merchant connector account is configured with invalid {config}"), None)) } Self::InvalidCardIin => AER::BadRequest(ApiError::new("IR", 31, "The provided card IIN does not exist", None)), Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("IR", 32, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)), Self::MissingFile => { AER::BadRequest(ApiError::new("IR", 33, "File not found in the request", None)) } Self::MissingDisputeId => { AER::BadRequest(ApiError::new("IR", 34, "Dispute id not found in the request", None)) } Self::MissingFilePurpose => { AER::BadRequest(ApiError::new("IR", 35, "File purpose not found in the request or is invalid", None)) } Self::MissingFileContentType => { AER::BadRequest(ApiError::new("IR", 36, "File content type not found", None)) } Self::GenericNotFoundError { message } => { AER::NotFound(ApiError::new("IR", 37, message, None)) }, Self::GenericDuplicateError { message } => { AER::BadRequest(ApiError::new("IR", 38, message, None)) } Self::IncorrectPaymentMethodConfiguration => { AER::BadRequest(ApiError::new("IR", 39, "No eligible connector was found for the current payment method configuration", None)) } Self::LinkConfigurationError { message } => { AER::BadRequest(ApiError::new("IR", 40, message, None)) }, Self::PayoutFailed { data } => { AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()}))) }, Self::CookieNotFound => { AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None)) }, Self::ExternalVaultFailed => { AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None)) }, Self::MandatePaymentDataMismatch { fields} => { AER::BadRequest(ApiError::new("IR", 46, format!("Field {fields} doesn't match with the ones used during mandate creation"), Some(Extra {fields: Some(fields.to_owned()), ..Default::default()}))) //FIXME: error message } Self::MaxFieldLengthViolated { connector, field_name, max_length, received_length} => { AER::BadRequest(ApiError::new("IR", 47, format!("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}"), Some(Extra {connector: Some(connector.to_string()), ..Default::default()}))) } Self::WebhookAuthenticationFailed => { AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) } Self::WebhookBadRequest => { AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None)) } Self::WebhookProcessingFailure => { AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None)) }, Self::WebhookResourceNotFound => { AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None)) } Self::WebhookUnprocessableEntity => { AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None)) }, Self::WebhookInvalidMerchantSecret => { AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None)) } Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id } => AER::InternalServerError(ApiError::new( "IE", 0, format!("{reason} as data mismatched for {field_names}"), Some(Extra { connector_transaction_id: connector_transaction_id.to_owned(), ..Default::default() }) )), Self::PlatformAccountAuthNotSupported => { AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None)) } Self::InvalidPlatformOperation => { AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None)) } Self::TokenizationRecordNotFound{ id } => { AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None)) } Self::SubscriptionError { operation } => { AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None)) } } } } impl actix_web::ResponseError for ApiErrorResponse { fn status_code(&self) -> StatusCode { ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code() } fn error_response(&self) -> actix_web::HttpResponse { ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response() } } impl From<ApiErrorResponse> for router_data::ErrorResponse { fn from(error: ApiErrorResponse) -> Self { Self { code: error.error_code(), message: error.error_message(), reason: None, status_code: match error { ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code, _ => 500, }, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/errors/api_error_response.rs", "file_size": 45626, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-2409175948284331607
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs // File size: 44148 bytes #[cfg(feature = "v2")] use std::collections::HashMap; use common_utils::{ crypto::Encryptable, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, id_type, pii, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; #[cfg(feature = "v2")] use diesel_models::merchant_connector_account::{ BillingAccountReference as DieselBillingAccountReference, MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata, RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata, }; use diesel_models::{ enums, merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use rustc_hash::FxHashMap; use serde_json::Value; use super::behaviour; #[cfg(feature = "v2")] use crate::errors::api_error_response; use crate::{ mandates::CommonMandateReference, merchant_key_store::MerchantKeyStore, router_data, type_encryption::{crypto_operation, CryptoOperation}, }; #[cfg(feature = "v1")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub merchant_id: id_type::MerchantId, pub connector_name: String, #[encrypt] pub connector_account_details: Encryptable<Secret<Value>>, pub test_mode: Option<bool>, pub disabled: Option<bool>, pub merchant_connector_id: id_type::MerchantConnectorAccountId, pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, pub connector_type: enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub frm_configs: Option<Vec<pii::SecretSerdeValue>>, pub connector_label: Option<String>, pub business_country: Option<enums::CountryAlpha2>, pub business_label: Option<String>, pub business_sub_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, #[encrypt] pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, } #[cfg(feature = "v1")] impl MerchantConnectorAccount { pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.merchant_connector_id.clone() } pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { self.connector_account_details .get_inner() .clone() .parse_value("ConnectorAuthType") } pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> { self.connector_wallets_details.as_deref().cloned() } pub fn get_connector_test_mode(&self) -> Option<bool> { self.test_mode } pub fn get_connector_name_as_string(&self) -> String { self.connector_name.clone() } pub fn get_metadata(&self) -> Option<Secret<Value>> { self.metadata.clone() } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub enum MerchantConnectorAccountTypeDetails { MerchantConnectorAccount(Box<MerchantConnectorAccount>), MerchantConnectorDetails(common_types::domain::MerchantConnectorAuthDetails), } #[cfg(feature = "v2")] impl MerchantConnectorAccountTypeDetails { pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account .connector_account_details .peek() .clone() .parse_value("ConnectorAuthType") } Self::MerchantConnectorDetails(merchant_connector_details) => { merchant_connector_details .merchant_connector_creds .peek() .clone() .parse_value("ConnectorAuthType") } } } pub fn is_disabled(&self) -> bool { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.disabled.unwrap_or(false) } Self::MerchantConnectorDetails(_) => false, } } pub fn get_metadata(&self) -> Option<Secret<Value>> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.metadata.to_owned() } Self::MerchantConnectorDetails(_) => None, } } pub fn get_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.id.clone()) } Self::MerchantConnectorDetails(_) => None, } } pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.get_id()) } Self::MerchantConnectorDetails(_) => None, } } pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account.connector_name) } Self::MerchantConnectorDetails(merchant_connector_details) => { Some(merchant_connector_details.connector_name) } } } pub fn get_connector_name_as_string(&self) -> String { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { merchant_connector_account.connector_name.to_string() } Self::MerchantConnectorDetails(merchant_connector_details) => { merchant_connector_details.connector_name.to_string() } } } pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> { match self { Self::MerchantConnectorAccount(merchant_connector_account) => { Some(merchant_connector_account) } Self::MerchantConnectorDetails(_) => None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct MerchantConnectorAccount { pub id: id_type::MerchantConnectorAccountId, pub merchant_id: id_type::MerchantId, pub connector_name: common_enums::connector_enums::Connector, #[encrypt] pub connector_account_details: Encryptable<Secret<Value>>, pub disabled: Option<bool>, pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, pub connector_type: enums::ConnectorType, pub metadata: Option<pii::SecretSerdeValue>, pub frm_configs: Option<Vec<pii::SecretSerdeValue>>, pub connector_label: Option<String>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub connector_webhook_details: Option<pii::SecretSerdeValue>, pub profile_id: id_type::ProfileId, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<pii::SecretSerdeValue>, pub status: enums::ConnectorStatus, #[encrypt] pub connector_wallets_details: Option<Encryptable<Secret<Value>>>, #[encrypt] pub additional_merchant_data: Option<Encryptable<Secret<Value>>>, pub version: common_enums::ApiVersion, pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorAccount { pub fn get_retry_threshold(&self) -> Option<u16> { self.feature_metadata .as_ref() .and_then(|metadata| metadata.revenue_recovery.as_ref()) .map(|recovery| recovery.billing_connector_retry_threshold) } pub fn get_id(&self) -> id_type::MerchantConnectorAccountId { self.id.clone() } pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone() } pub fn is_disabled(&self) -> bool { self.disabled.unwrap_or(false) } pub fn get_connector_account_details( &self, ) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError> { use common_utils::ext_traits::ValueExt; self.connector_account_details .get_inner() .clone() .parse_value("ConnectorAuthType") } pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> { self.connector_wallets_details.as_deref().cloned() } pub fn get_connector_test_mode(&self) -> Option<bool> { todo!() } pub fn get_connector_name_as_string(&self) -> String { self.connector_name.clone().to_string() } #[cfg(feature = "v2")] pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { self.connector_name } pub fn get_payment_merchant_connector_account_id_using_account_reference_id( &self, account_reference_id: String, ) -> Option<id_type::MerchantConnectorAccountId> { self.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .mca_reference .billing_to_recovery .get(&account_reference_id) .cloned() }) }) } pub fn get_account_reference_id_using_payment_merchant_connector_account_id( &self, payment_merchant_connector_account_id: id_type::MerchantConnectorAccountId, ) -> Option<String> { self.feature_metadata.as_ref().and_then(|metadata| { metadata.revenue_recovery.as_ref().and_then(|recovery| { recovery .mca_reference .recovery_to_billing .get(&payment_merchant_connector_account_id) .cloned() }) }) } } #[cfg(feature = "v2")] /// Holds the payment methods enabled for a connector along with the connector name /// This struct is a flattened representation of the payment methods enabled for a connector #[derive(Debug)] pub struct PaymentMethodsEnabledForConnector { pub payment_methods_enabled: common_types::payment_methods::RequestPaymentMethodTypes, pub payment_method: common_enums::PaymentMethod, pub connector: common_enums::connector_enums::Connector, pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct MerchantConnectorAccountFeatureMetadata { pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct RevenueRecoveryMetadata { pub max_retry_count: u16, pub billing_connector_retry_threshold: u16, pub mca_reference: AccountReferenceMap, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize)] pub struct ExternalVaultConnectorMetadata { pub proxy_url: common_utils::types::Url, pub certificate: Secret<String>, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub struct AccountReferenceMap { pub recovery_to_billing: HashMap<id_type::MerchantConnectorAccountId, String>, pub billing_to_recovery: HashMap<String, id_type::MerchantConnectorAccountId>, } #[cfg(feature = "v2")] impl AccountReferenceMap { pub fn new( hash_map: HashMap<id_type::MerchantConnectorAccountId, String>, ) -> Result<Self, api_error_response::ApiErrorResponse> { Self::validate(&hash_map)?; let recovery_to_billing = hash_map.clone(); let mut billing_to_recovery = HashMap::new(); for (key, value) in &hash_map { billing_to_recovery.insert(value.clone(), key.clone()); } Ok(Self { recovery_to_billing, billing_to_recovery, }) } fn validate( hash_map: &HashMap<id_type::MerchantConnectorAccountId, String>, ) -> Result<(), api_error_response::ApiErrorResponse> { let mut seen_values = std::collections::HashSet::new(); // To check uniqueness of values for value in hash_map.values() { if !seen_values.insert(value.clone()) { return Err(api_error_response::ApiErrorResponse::InvalidRequestData { message: "Duplicate account reference IDs found in Recovery feature metadata. Each account reference ID must be unique.".to_string(), }); } } Ok(()) } } #[cfg(feature = "v2")] /// Holds the payment methods enabled for a connector pub struct FlattenedPaymentMethodsEnabled { pub payment_methods_enabled: Vec<PaymentMethodsEnabledForConnector>, } #[cfg(feature = "v2")] impl FlattenedPaymentMethodsEnabled { /// This functions flattens the payment methods enabled from the connector accounts /// Retains the connector name and payment method in every flattened element pub fn from_payment_connectors_list(payment_connectors: Vec<MerchantConnectorAccount>) -> Self { let payment_methods_enabled_flattened_with_connector = payment_connectors .into_iter() .map(|connector| { ( connector .payment_methods_enabled .clone() .unwrap_or_default(), connector.connector_name, connector.get_id(), ) }) .flat_map( |(payment_method_enabled, connector, merchant_connector_id)| { payment_method_enabled .into_iter() .flat_map(move |payment_method| { let request_payment_methods_enabled = payment_method.payment_method_subtypes.unwrap_or_default(); let length = request_payment_methods_enabled.len(); request_payment_methods_enabled .into_iter() .zip(std::iter::repeat_n( ( connector, merchant_connector_id.clone(), payment_method.payment_method_type, ), length, )) }) }, ) .map( |(request_payment_methods, (connector, merchant_connector_id, payment_method))| { PaymentMethodsEnabledForConnector { payment_methods_enabled: request_payment_methods, connector, payment_method, merchant_connector_id, } }, ) .collect(); Self { payment_methods_enabled: payment_methods_enabled_flattened_with_connector, } } } #[cfg(feature = "v1")] #[derive(Debug)] pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, connector_name: Option<String>, connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, test_mode: Option<bool>, disabled: Option<bool>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, connector_webhook_details: Box<Option<pii::SecretSerdeValue>>, applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, }, } #[cfg(feature = "v2")] #[derive(Debug)] pub enum MerchantConnectorAccountUpdate { Update { connector_type: Option<enums::ConnectorType>, connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, disabled: Option<bool>, payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, metadata: Option<pii::SecretSerdeValue>, frm_configs: Option<Vec<pii::SecretSerdeValue>>, connector_webhook_details: Box<Option<pii::SecretSerdeValue>>, applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Box<Option<pii::SecretSerdeValue>>, connector_label: Option<String>, status: Option<enums::ConnectorStatus>, connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>, additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>, feature_metadata: Box<Option<MerchantConnectorAccountFeatureMetadata>>, }, ConnectorWalletDetailsUpdate { connector_wallets_details: Encryptable<pii::SecretSerdeValue>, }, } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for MerchantConnectorAccount { type DstType = storage::MerchantConnectorAccount; type NewDstType = storage::MerchantConnectorAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(storage::MerchantConnectorAccount { merchant_id: self.merchant_id, connector_name: self.connector_name, connector_account_details: self.connector_account_details.into(), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id.clone(), id: Some(self.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, connector_type: self.connector_type, metadata: self.metadata, frm_configs: None, frm_config: self.frm_configs, business_country: self.business_country, business_label: self.business_label, connector_label: self.connector_label, business_sub_label: self.business_sub_label, created_at: self.created_at, modified_at: self.modified_at, connector_webhook_details: self.connector_webhook_details, profile_id: Some(self.profile_id), applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( EncryptedMerchantConnectorAccount { connector_account_details: other.connector_account_details, additional_merchant_data: other.additional_merchant_data, connector_wallets_details: other.connector_wallets_details, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; Ok(Self { merchant_id: other.merchant_id, connector_name: other.connector_name, connector_account_details: decrypted_data.connector_account_details, test_mode: other.test_mode, disabled: other.disabled, merchant_connector_id: other.merchant_connector_id, payment_methods_enabled: other.payment_methods_enabled, connector_type: other.connector_type, metadata: other.metadata, frm_configs: other.frm_config, business_country: other.business_country, business_label: other.business_label, connector_label: other.connector_label, business_sub_label: other.business_sub_label, created_at: other.created_at, modified_at: other.modified_at, connector_webhook_details: other.connector_webhook_details, profile_id: other .profile_id .ok_or(ValidationError::MissingRequiredField { field_name: "profile_id".to_string(), })?, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, connector_wallets_details: decrypted_data.connector_wallets_details, additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), connector_account_details: Some(self.connector_account_details.into()), test_mode: self.test_mode, disabled: self.disabled, merchant_connector_id: self.merchant_connector_id.clone(), id: Some(self.merchant_connector_id), payment_methods_enabled: self.payment_methods_enabled, connector_type: Some(self.connector_type), metadata: self.metadata, frm_configs: None, frm_config: self.frm_configs, business_country: self.business_country, business_label: self.business_label, connector_label: self.connector_label, business_sub_label: self.business_sub_label, created_at: now, modified_at: now, connector_webhook_details: self.connector_webhook_details, profile_id: Some(self.profile_id), applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for MerchantConnectorAccount { type DstType = storage::MerchantConnectorAccount; type NewDstType = storage::MerchantConnectorAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(storage::MerchantConnectorAccount { id: self.id, merchant_id: self.merchant_id, connector_name: self.connector_name, connector_account_details: self.connector_account_details.into(), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, connector_type: self.connector_type, metadata: self.metadata, frm_config: self.frm_configs, connector_label: self.connector_label, created_at: self.created_at, modified_at: self.modified_at, connector_webhook_details: self.connector_webhook_details, profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, feature_metadata: self.feature_metadata.map(From::from), }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted_data = crypto_operation( state, type_name!(Self::DstType), CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable( EncryptedMerchantConnectorAccount { connector_account_details: other.connector_account_details, additional_merchant_data: other.additional_merchant_data, connector_wallets_details: other.connector_wallets_details, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting connector account details".to_string(), })?; Ok(Self { id: other.id, merchant_id: other.merchant_id, connector_name: other.connector_name, connector_account_details: decrypted_data.connector_account_details, disabled: other.disabled, payment_methods_enabled: other.payment_methods_enabled, connector_type: other.connector_type, metadata: other.metadata, frm_configs: other.frm_config, connector_label: other.connector_label, created_at: other.created_at, modified_at: other.modified_at, connector_webhook_details: other.connector_webhook_details, profile_id: other.profile_id, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, connector_wallets_details: decrypted_data.connector_wallets_details, additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, feature_metadata: other.feature_metadata.map(From::from), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { id: self.id, merchant_id: Some(self.merchant_id), connector_name: Some(self.connector_name), connector_account_details: Some(self.connector_account_details.into()), disabled: self.disabled, payment_methods_enabled: self.payment_methods_enabled, connector_type: Some(self.connector_type), metadata: self.metadata, frm_config: self.frm_configs, connector_label: self.connector_label, created_at: now, modified_at: now, connector_webhook_details: self.connector_webhook_details, profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, status: self.status, connector_wallets_details: self.connector_wallets_details.map(Encryption::from), additional_merchant_data: self.additional_merchant_data.map(|data| data.into()), version: self.version, feature_metadata: self.feature_metadata.map(From::from), }) } } #[cfg(feature = "v1")] impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { match merchant_connector_account_update { MerchantConnectorAccountUpdate::Update { connector_type, connector_name, connector_account_details, test_mode, disabled, merchant_connector_id, payment_methods_enabled, metadata, frm_configs, connector_webhook_details, applepay_verified_domains, pm_auth_config, connector_label, status, connector_wallets_details, additional_merchant_data, } => Self { connector_type, connector_name, connector_account_details: connector_account_details.map(Encryption::from), test_mode, disabled, merchant_connector_id, payment_methods_enabled, metadata, frm_configs: None, frm_config: frm_configs, modified_at: Some(date_time::now()), connector_webhook_details: *connector_webhook_details, applepay_verified_domains, pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), additional_merchant_data: additional_merchant_data.map(Encryption::from), }, MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { connector_wallets_details, } => Self { connector_wallets_details: Some(Encryption::from(connector_wallets_details)), connector_type: None, connector_name: None, connector_account_details: None, connector_label: None, test_mode: None, disabled: None, merchant_connector_id: None, payment_methods_enabled: None, frm_configs: None, metadata: None, modified_at: None, connector_webhook_details: None, frm_config: None, applepay_verified_domains: None, pm_auth_config: None, status: None, additional_merchant_data: None, }, } } } #[cfg(feature = "v2")] impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal { fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self { match merchant_connector_account_update { MerchantConnectorAccountUpdate::Update { connector_type, connector_account_details, disabled, payment_methods_enabled, metadata, frm_configs, connector_webhook_details, applepay_verified_domains, pm_auth_config, connector_label, status, connector_wallets_details, additional_merchant_data, feature_metadata, } => Self { connector_type, connector_account_details: connector_account_details.map(Encryption::from), disabled, payment_methods_enabled, metadata, frm_config: frm_configs, modified_at: Some(date_time::now()), connector_webhook_details: *connector_webhook_details, applepay_verified_domains, pm_auth_config: *pm_auth_config, connector_label, status, connector_wallets_details: connector_wallets_details.map(Encryption::from), additional_merchant_data: additional_merchant_data.map(Encryption::from), feature_metadata: feature_metadata.map(From::from), }, MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate { connector_wallets_details, } => Self { connector_wallets_details: Some(Encryption::from(connector_wallets_details)), connector_type: None, connector_account_details: None, connector_label: None, disabled: None, payment_methods_enabled: None, metadata: None, modified_at: None, connector_webhook_details: None, frm_config: None, applepay_verified_domains: None, pm_auth_config: None, status: None, additional_merchant_data: None, feature_metadata: None, }, } } } common_utils::create_list_wrapper!( MerchantConnectorAccounts, MerchantConnectorAccount, impl_functions: { fn filter_and_map<'a, T>( &'a self, filter: impl Fn(&'a MerchantConnectorAccount) -> bool, func: impl Fn(&'a MerchantConnectorAccount) -> T, ) -> rustc_hash::FxHashSet<T> where T: std::hash::Hash + Eq, { self.0 .iter() .filter(|mca| filter(mca)) .map(func) .collect::<rustc_hash::FxHashSet<_>>() } pub fn filter_by_profile<'a, T>( &'a self, profile_id: &'a id_type::ProfileId, func: impl Fn(&'a MerchantConnectorAccount) -> T, ) -> rustc_hash::FxHashSet<T> where T: std::hash::Hash + Eq, { self.filter_and_map(|mca| mca.profile_id == *profile_id, func) } #[cfg(feature = "v2")] pub fn get_connector_and_supporting_payment_method_type_for_session_call( &self, ) -> Vec<(&MerchantConnectorAccount, common_enums::PaymentMethodType, common_enums::PaymentMethod)> { // This vector is created to work around lifetimes let ref_vector = Vec::default(); let connector_and_supporting_payment_method_type = self.iter().flat_map(|connector_account| { connector_account .payment_methods_enabled.as_ref() .unwrap_or(&Vec::default()) .iter() .flat_map(|payment_method_types| payment_method_types.payment_method_subtypes.as_ref().unwrap_or(&ref_vector).iter().map(|payment_method_subtype| (payment_method_subtype, payment_method_types.payment_method_type)).collect::<Vec<_>>()) .filter(|(payment_method_types_enabled, _)| { payment_method_types_enabled.payment_experience == Some(api_models::enums::PaymentExperience::InvokeSdkClient) }) .map(|(payment_method_subtypes, payment_method_type)| { (connector_account, payment_method_subtypes.payment_method_subtype, payment_method_type) }) .collect::<Vec<_>>() }).collect(); connector_and_supporting_payment_method_type } pub fn filter_based_on_profile_and_connector_type( self, profile_id: &id_type::ProfileId, connector_type: common_enums::ConnectorType, ) -> Self { self.into_iter() .filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type) .collect() } pub fn is_merchant_connector_account_id_in_connector_mandate_details( &self, profile_id: Option<&id_type::ProfileId>, connector_mandate_details: &CommonMandateReference, ) -> bool { let mca_ids = self .iter() .filter(|mca| { mca.disabled.is_some_and(|disabled| !disabled) && profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id) }) .map(|mca| mca.get_id()) .collect::<std::collections::HashSet<_>>(); connector_mandate_details .payments .as_ref() .as_ref().is_some_and(|payments| { payments.0.keys().any(|mca_id| mca_ids.contains(mca_id)) }) } } ); #[cfg(feature = "v2")] impl From<MerchantConnectorAccountFeatureMetadata> for DieselMerchantConnectorAccountFeatureMetadata { fn from(feature_metadata: MerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| { DieselRevenueRecoveryMetadata { max_retry_count: recovery_metadata.max_retry_count, billing_connector_retry_threshold: recovery_metadata .billing_connector_retry_threshold, billing_account_reference: DieselBillingAccountReference( recovery_metadata.mca_reference.recovery_to_billing, ), } }); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl From<DieselMerchantConnectorAccountFeatureMetadata> for MerchantConnectorAccountFeatureMetadata { fn from(feature_metadata: DieselMerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| { let mut billing_to_recovery = HashMap::new(); for (key, value) in &recovery_metadata.billing_account_reference.0 { billing_to_recovery.insert(value.to_string(), key.clone()); } RevenueRecoveryMetadata { max_retry_count: recovery_metadata.max_retry_count, billing_connector_retry_threshold: recovery_metadata .billing_connector_retry_threshold, mca_reference: AccountReferenceMap { recovery_to_billing: recovery_metadata.billing_account_reference.0, billing_to_recovery, }, } }); Self { revenue_recovery } } } #[async_trait::async_trait] pub trait MerchantConnectorAccountInterface where MerchantConnectorAccount: behaviour::Conversion< DstType = storage::MerchantConnectorAccount, NewDstType = storage::MerchantConnectorAccountNew, >, { type Error; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_label: &str, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_name: &str, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: MerchantConnectorAccount, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &id_type::MerchantConnectorAccountId, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, get_disabled: bool, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccounts, Self::Error>; #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>; async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: MerchantConnectorAccount, merchant_connector_account: MerchantConnectorAccountUpdateInternal, key_store: &MerchantKeyStore, ) -> CustomResult<MerchantConnectorAccount, Self::Error>; async fn update_multiple_merchant_connector_accounts( &self, this: Vec<( MerchantConnectorAccount, MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), Self::Error>; #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, Self::Error>; }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/merchant_connector_account.rs", "file_size": 44148, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_4656405390708126527
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/merchant_account.rs // File size: 39030 bytes use common_utils::{ crypto::{OptionalEncryptableName, OptionalEncryptableValue}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, pii, type_name, types::keymanager::{self}, }; use diesel_models::{ enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use router_env::logger; use crate::{ behaviour::Conversion, merchant_key_store, type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, }; #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { merchant_id: common_utils::id_type::MerchantId, 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 merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: diesel_models::enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] #[derive(Clone)] /// Set the private fields of merchant account pub struct MerchantAccountSetter { pub merchant_id: common_utils::id_type::MerchantId, 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 merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>, pub sub_merchants_enabled: Option<bool>, pub parent_merchant_id: Option<common_utils::id_type::MerchantId>, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub locker_id: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub routing_algorithm: Option<serde_json::Value>, pub primary_business_details: serde_json::Value, pub frm_routing_algorithm: Option<serde_json::Value>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub intent_fulfillment_time: Option<i64>, pub payout_routing_algorithm: Option<serde_json::Value>, pub organization_id: common_utils::id_type::OrganizationId, pub is_recon_enabled: bool, pub default_profile: Option<common_utils::id_type::ProfileId>, pub recon_status: diesel_models::enums::ReconStatus, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, pub is_platform_account: bool, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v1")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item.merchant_name, merchant_details: item.merchant_details, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: item.publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, primary_business_details: item.primary_business_details, frm_routing_algorithm: item.frm_routing_algorithm, created_at: item.created_at, modified_at: item.modified_at, intent_fulfillment_time: item.intent_fulfillment_time, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: item.merchant_account_type, } } } #[cfg(feature = "v2")] #[derive(Clone)] /// Set the private fields of merchant account pub struct MerchantAccountSetter { pub id: common_utils::id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } #[cfg(feature = "v2")] impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { let MerchantAccountSetter { id, merchant_name, merchant_details, publishable_key, storage_scheme, metadata, created_at, modified_at, organization_id, recon_status, is_platform_account, version, product_type, merchant_account_type, } = item; Self { id, merchant_name, merchant_details, publishable_key, storage_scheme, metadata, created_at, modified_at, organization_id, recon_status, is_platform_account, version, product_type, merchant_account_type, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { id: common_utils::id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub merchant_details: OptionalEncryptableValue, pub publishable_key: String, pub storage_scheme: MerchantStorageScheme, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, pub is_platform_account: bool, pub version: common_enums::ApiVersion, pub product_type: Option<common_enums::MerchantProductType>, pub merchant_account_type: common_enums::MerchantAccountType, } impl MerchantAccount { #[cfg(feature = "v1")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.merchant_id } #[cfg(feature = "v2")] /// Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId { &self.id } /// Get the organization_id from MerchantAccount pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId { &self.organization_id } /// Get the merchant_details from MerchantAccount pub fn get_merchant_details(&self) -> &OptionalEncryptableValue { &self.merchant_details } /// Extract merchant_tax_registration_id from merchant_details pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> { self.merchant_details.as_ref().and_then(|details| { details .get_inner() .peek() .get("merchant_tax_registration_id") .and_then(|id| id.as_str().map(|s| Secret::new(s.to_string()))) }) } /// Check whether the merchant account is a platform account pub fn is_platform_account(&self) -> bool { matches!( self.merchant_account_type, common_enums::MerchantAccountType::Platform ) } } #[cfg(feature = "v1")] #[allow(clippy::large_enum_variant)] #[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, merchant_details: OptionalEncryptableValue, return_url: Option<String>, webhook_details: Option<diesel_models::business_profile::WebhookDetails>, sub_merchants_enabled: Option<bool>, parent_merchant_id: Option<common_utils::id_type::MerchantId>, enable_payment_response_hash: Option<bool>, payment_response_hash_key: Option<String>, redirect_to_merchant_with_http_post: Option<bool>, publishable_key: Option<String>, locker_id: Option<String>, metadata: Option<pii::SecretSerdeValue>, routing_algorithm: Option<serde_json::Value>, primary_business_details: Option<serde_json::Value>, intent_fulfillment_time: Option<i64>, frm_routing_algorithm: Option<serde_json::Value>, payout_routing_algorithm: Option<serde_json::Value>, default_profile: Option<Option<common_utils::id_type::ProfileId>>, payment_link_config: Option<serde_json::Value>, pm_collect_link_config: Option<serde_json::Value>, }, StorageSchemeUpdate { storage_scheme: MerchantStorageScheme, }, ReconUpdate { recon_status: diesel_models::enums::ReconStatus, }, UnsetDefaultProfile, ModifiedAtUpdate, ToPlatformAccount, } #[cfg(feature = "v2")] #[derive(Debug, Clone)] pub enum MerchantAccountUpdate { Update { merchant_name: OptionalEncryptableName, merchant_details: OptionalEncryptableValue, publishable_key: Option<String>, metadata: Option<Box<pii::SecretSerdeValue>>, }, StorageSchemeUpdate { storage_scheme: MerchantStorageScheme, }, ReconUpdate { recon_status: diesel_models::enums::ReconStatus, }, ModifiedAtUpdate, ToPlatformAccount, } #[cfg(feature = "v1")] impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); match merchant_account_update { MerchantAccountUpdate::Update { merchant_name, merchant_details, webhook_details, return_url, routing_algorithm, sub_merchants_enabled, parent_merchant_id, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, locker_id, metadata, primary_business_details, intent_fulfillment_time, frm_routing_algorithm, payout_routing_algorithm, default_profile, payment_link_config, pm_collect_link_config, } => Self { merchant_name: merchant_name.map(Encryption::from), merchant_details: merchant_details.map(Encryption::from), frm_routing_algorithm, webhook_details, routing_algorithm, sub_merchants_enabled, parent_merchant_id, return_url, enable_payment_response_hash, payment_response_hash_key, redirect_to_merchant_with_http_post, publishable_key, locker_id, metadata, primary_business_details, modified_at: now, intent_fulfillment_time, payout_routing_algorithm, default_profile, payment_link_config, pm_collect_link_config, storage_scheme: None, organization_id: None, is_recon_enabled: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::UnsetDefaultProfile => Self { default_profile: Some(None), modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ToPlatformAccount => Self { modified_at: now, merchant_name: None, merchant_details: None, return_url: None, webhook_details: None, sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: None, payment_response_hash_key: None, redirect_to_merchant_with_http_post: None, publishable_key: None, storage_scheme: None, locker_id: None, metadata: None, routing_algorithm: None, primary_business_details: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: None, is_recon_enabled: None, default_profile: None, recon_status: None, payment_link_config: None, pm_collect_link_config: None, is_platform_account: Some(true), product_type: None, }, } } } #[cfg(feature = "v2")] impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); match merchant_account_update { MerchantAccountUpdate::Update { merchant_name, merchant_details, publishable_key, metadata, } => Self { merchant_name: merchant_name.map(Encryption::from), merchant_details: merchant_details.map(Encryption::from), publishable_key, metadata: metadata.map(|metadata| *metadata), modified_at: now, storage_scheme: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: None, product_type: None, }, MerchantAccountUpdate::ToPlatformAccount => Self { modified_at: now, merchant_name: None, merchant_details: None, publishable_key: None, storage_scheme: None, metadata: None, organization_id: None, recon_status: None, is_platform_account: Some(true), product_type: None, }, } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let id = self.get_id().to_owned(); let setter = diesel_models::merchant_account::MerchantAccountSetter { id, merchant_name: self.merchant_name.map(|name| name.into()), merchant_details: self.merchant_details.map(|details| details.into()), publishable_key: Some(self.publishable_key), storage_scheme: self.storage_scheme, metadata: self.metadata, created_at: self.created_at, modified_at: self.modified_at, organization_id: self.organization_id, recon_status: self.recon_status, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self.product_type, merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { id, merchant_name: item .merchant_name .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: item .merchant_details .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, publishable_key, storage_scheme: item.storage_scheme, metadata: item.metadata, created_at: item.created_at, modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, is_platform_account: item.is_platform_account, version: item.version, product_type: item.product_type, merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting merchant data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::merchant_account::MerchantAccountNew { id: self.id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), publishable_key: Some(self.publishable_key), metadata: self.metadata, created_at: now, modified_at: now, organization_id: self.organization_id, recon_status: self.recon_status, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), merchant_account_type: self.merchant_account_type, }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl Conversion for MerchantAccount { type DstType = diesel_models::merchant_account::MerchantAccount; type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let setter = diesel_models::merchant_account::MerchantAccountSetter { merchant_id: self.merchant_id, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, merchant_name: self.merchant_name.map(|name| name.into()), merchant_details: self.merchant_details.map(|details| details.into()), webhook_details: self.webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id: self.parent_merchant_id, publishable_key: Some(self.publishable_key), storage_scheme: self.storage_scheme, locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, primary_business_details: self.primary_business_details, created_at: self.created_at, modified_at: self.modified_at, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: self.version, is_platform_account: self.is_platform_account, product_type: self.product_type, merchant_account_type: self.merchant_account_type, }; Ok(diesel_models::MerchantAccount::from(setter)) } async fn convert_back( state: &keymanager::KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let merchant_id = item.get_id().to_owned(); let publishable_key = item.publishable_key .ok_or(ValidationError::MissingRequiredField { field_name: "publishable_key".to_string(), })?; async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_name: item .merchant_name .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, merchant_details: item .merchant_details .async_lift(|inner| async { crypto_operation( state, type_name!(Self::DstType), CryptoOperation::DecryptOptional(inner), key_manager_identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await?, webhook_details: item.webhook_details, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key, storage_scheme: item.storage_scheme, locker_id: item.locker_id, metadata: item.metadata, routing_algorithm: item.routing_algorithm, frm_routing_algorithm: item.frm_routing_algorithm, primary_business_details: item.primary_business_details, created_at: item.created_at, modified_at: item.modified_at, intent_fulfillment_time: item.intent_fulfillment_time, payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, is_platform_account: item.is_platform_account, product_type: item.product_type, merchant_account_type: item.merchant_account_type.unwrap_or_default(), }) } .await .change_context(ValidationError::InvalidValue { message: "Failed while decrypting merchant data".to_string(), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::merchant_account::MerchantAccountNew { id: Some(self.merchant_id.clone()), merchant_id: self.merchant_id, merchant_name: self.merchant_name.map(Encryption::from), merchant_details: self.merchant_details.map(Encryption::from), return_url: self.return_url, webhook_details: self.webhook_details, sub_merchants_enabled: self.sub_merchants_enabled, parent_merchant_id: self.parent_merchant_id, enable_payment_response_hash: Some(self.enable_payment_response_hash), payment_response_hash_key: self.payment_response_hash_key, redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post), publishable_key: Some(self.publishable_key), locker_id: self.locker_id, metadata: self.metadata, routing_algorithm: self.routing_algorithm, primary_business_details: self.primary_business_details, created_at: now, modified_at: now, intent_fulfillment_time: self.intent_fulfillment_time, frm_routing_algorithm: self.frm_routing_algorithm, payout_routing_algorithm: self.payout_routing_algorithm, organization_id: self.organization_id, is_recon_enabled: self.is_recon_enabled, default_profile: self.default_profile, recon_status: self.recon_status, payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: common_types::consts::API_VERSION, is_platform_account: self.is_platform_account, product_type: self .product_type .or(Some(common_enums::MerchantProductType::Orchestration)), merchant_account_type: self.merchant_account_type, }) } } impl MerchantAccount { pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> { let metadata: Option<api_models::admin::MerchantAccountMetadata> = self.metadata.as_ref().and_then(|meta| { meta.clone() .parse_value("MerchantAccountMetadata") .map_err(|err| logger::error!("Failed to deserialize {:?}", err)) .ok() }); metadata.and_then(|a| a.compatible_connector) } } #[async_trait::async_trait] pub trait MerchantAccountInterface where MerchantAccount: Conversion< DstType = diesel_models::merchant_account::MerchantAccount, NewDstType = diesel_models::merchant_account::MerchantAccountNew, >, { type Error; async fn insert_merchant( &self, state: &keymanager::KeyManagerState, merchant_account: MerchantAccount, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn find_merchant_account_by_merchant_id( &self, state: &keymanager::KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn update_all_merchant_account( &self, merchant_account: MerchantAccountUpdate, ) -> CustomResult<usize, Self::Error>; async fn update_merchant( &self, state: &keymanager::KeyManagerState, this: MerchantAccount, merchant_account: MerchantAccountUpdate, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn update_specific_fields_in_merchant( &self, state: &keymanager::KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: MerchantAccountUpdate, merchant_key_store: &merchant_key_store::MerchantKeyStore, ) -> CustomResult<MerchantAccount, Self::Error>; async fn find_merchant_account_by_publishable_key( &self, state: &keymanager::KeyManagerState, publishable_key: &str, ) -> CustomResult<(MerchantAccount, merchant_key_store::MerchantKeyStore), Self::Error>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &keymanager::KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<MerchantAccount>, Self::Error>; async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &keymanager::KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<MerchantAccount>, Self::Error>; #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &keymanager::KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, Self::Error, >; }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/merchant_account.rs", "file_size": 39030, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_507670902330565031
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/customer.rs // File size: 28462 bytes use common_enums::enums::MerchantStorageScheme; #[cfg(feature = "v2")] use common_enums::DeleteStatus; use common_utils::{ crypto::{self, Encryptable}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, ext_traits::ValueExt, id_type, pii, types::{ keymanager::{self, KeyManagerState, ToEncryptable}, Description, }, }; use diesel_models::{ customers as storage_types, customers::CustomerUpdateInternal, query::customers as query, }; use error_stack::ResultExt; use masking::{ExposeOptionInterface, PeekInterface, Secret, SwitchStrategy}; use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use time::PrimitiveDateTime; #[cfg(feature = "v2")] use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails; use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types}; #[cfg(feature = "v1")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, #[encrypt] pub name: Option<Encryptable<Secret<String>>>, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, #[encrypt] pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: PrimitiveDateTime, pub connector_customer: Option<pii::SecretSerdeValue>, pub address_id: Option<String>, pub default_payment_method_id: Option<String>, pub updated_by: Option<String>, pub version: common_enums::ApiVersion, #[encrypt] pub tax_registration_id: Option<Encryptable<Secret<String>>>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Customer { pub merchant_id: id_type::MerchantId, #[encrypt] pub name: Option<Encryptable<Secret<String>>>, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, #[encrypt] pub phone: Option<Encryptable<Secret<String>>>, pub phone_country_code: Option<String>, pub description: Option<Description>, pub created_at: PrimitiveDateTime, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>, pub modified_at: PrimitiveDateTime, pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, pub updated_by: Option<String>, pub merchant_reference_id: Option<id_type::CustomerId>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub id: id_type::GlobalCustomerId, pub version: common_enums::ApiVersion, pub status: DeleteStatus, #[encrypt] pub tax_registration_id: Option<Encryptable<Secret<String>>>, } impl Customer { /// Get the unique identifier of Customer #[cfg(feature = "v1")] pub fn get_id(&self) -> &id_type::CustomerId { &self.customer_id } /// Get the global identifier of Customer #[cfg(feature = "v2")] pub fn get_id(&self) -> &id_type::GlobalCustomerId { &self.id } /// Get the connector customer ID for the specified connector label, if present #[cfg(feature = "v1")] pub fn get_connector_customer_map( &self, ) -> FxHashMap<id_type::MerchantConnectorAccountId, String> { use masking::PeekInterface; if let Some(connector_customer_value) = &self.connector_customer { connector_customer_value .peek() .clone() .parse_value("ConnectorCustomerMap") .unwrap_or_default() } else { FxHashMap::default() } } /// Get the connector customer ID for the specified connector label, if present #[cfg(feature = "v1")] pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> { use masking::PeekInterface; self.connector_customer .as_ref() .and_then(|connector_customer_value| { connector_customer_value.peek().get(connector_label) }) .and_then(|connector_customer| connector_customer.as_str()) } /// Get the connector customer ID for the specified merchant connector account ID, if present #[cfg(feature = "v2")] pub fn get_connector_customer_id( &self, merchant_connector_account: &MerchantConnectorAccountTypeDetails, ) -> Option<&str> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => { let connector_account_id = account.get_id(); self.connector_customer .as_ref()? .get(&connector_account_id) .map(|connector_customer_id| connector_customer_id.as_str()) } MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None, } } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl behaviour::Conversion for Customer { type DstType = diesel_models::customers::Customer; type NewDstType = diesel_models::customers::CustomerNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::customers::Customer { customer_id: self.customer_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), phone_country_code: self.phone_country_code, description: self.description, created_at: self.created_at, metadata: self.metadata, modified_at: self.modified_at, connector_customer: self.connector_customer, address_id: self.address_id, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, version: self.version, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_store_ref_id: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), tax_registration_id: item.tax_registration_id.clone(), }, )), keymanager::Identifier::Merchant(item.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), }, )?; Ok(Self { customer_id: item.customer_id, merchant_id: item.merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, created_at: item.created_at, metadata: item.metadata, modified_at: item.modified_at, connector_customer: item.connector_customer, address_id: item.address_id, default_payment_method_id: item.default_payment_method_id, updated_by: item.updated_by, version: item.version, tax_registration_id: encryptable_customer.tax_registration_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::customers::CustomerNew { customer_id: self.customer_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), description: self.description, phone_country_code: self.phone_country_code, metadata: self.metadata, created_at: now, modified_at: now, connector_customer: self.connector_customer, address_id: self.address_id, updated_by: self.updated_by, version: self.version, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl behaviour::Conversion for Customer { type DstType = diesel_models::customers::Customer; type NewDstType = diesel_models::customers::CustomerNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::customers::Customer { id: self.id, merchant_reference_id: self.merchant_reference_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), phone_country_code: self.phone_country_code, description: self.description, created_at: self.created_at, metadata: self.metadata, modified_at: self.modified_at, connector_customer: self.connector_customer, default_payment_method_id: self.default_payment_method_id, updated_by: self.updated_by, default_billing_address: self.default_billing_address, default_shipping_address: self.default_shipping_address, version: self.version, status: self.status, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_store_ref_id: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, common_utils::type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable( EncryptedCustomer { name: item.name.clone(), phone: item.phone.clone(), email: item.email.clone(), tax_registration_id: item.tax_registration_id.clone(), }, )), keymanager::Identifier::Merchant(item.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?; let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), }, )?; Ok(Self { id: item.id, merchant_reference_id: item.merchant_reference_id, merchant_id: item.merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, phone_country_code: item.phone_country_code, description: item.description, created_at: item.created_at, metadata: item.metadata, modified_at: item.modified_at, connector_customer: item.connector_customer, default_payment_method_id: item.default_payment_method_id, updated_by: item.updated_by, default_billing_address: item.default_billing_address, default_shipping_address: item.default_shipping_address, version: item.version, status: item.status, tax_registration_id: encryptable_customer.tax_registration_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(diesel_models::customers::CustomerNew { id: self.id, merchant_reference_id: self.merchant_reference_id, merchant_id: self.merchant_id, name: self.name.map(Encryption::from), email: self.email.map(Encryption::from), phone: self.phone.map(Encryption::from), description: self.description, phone_country_code: self.phone_country_code, metadata: self.metadata, default_payment_method_id: None, created_at: now, modified_at: now, connector_customer: self.connector_customer, updated_by: self.updated_by, default_billing_address: self.default_billing_address, default_shipping_address: self.default_shipping_address, version: common_types::consts::API_VERSION, status: self.status, tax_registration_id: self.tax_registration_id.map(Encryption::from), }) } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct CustomerGeneralUpdate { pub name: crypto::OptionalEncryptableName, pub email: Box<crypto::OptionalEncryptableEmail>, pub phone: Box<crypto::OptionalEncryptablePhone>, pub description: Option<Description>, pub phone_country_code: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>, pub default_billing_address: Option<Encryption>, pub default_shipping_address: Option<Encryption>, pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, pub status: Option<DeleteStatus>, pub tax_registration_id: crypto::OptionalEncryptableSecretString, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub enum CustomerUpdate { Update(Box<CustomerGeneralUpdate>), ConnectorCustomer { connector_customer: Option<common_types::customers::ConnectorCustomerMap>, }, UpdateDefaultPaymentMethod { default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>, }, } #[cfg(feature = "v2")] impl From<CustomerUpdate> for CustomerUpdateInternal { fn from(customer_update: CustomerUpdate) -> Self { match customer_update { CustomerUpdate::Update(update) => { let CustomerGeneralUpdate { name, email, phone, description, phone_country_code, metadata, connector_customer, default_billing_address, default_shipping_address, default_payment_method_id, status, tax_registration_id, } = *update; Self { name: name.map(Encryption::from), email: email.map(Encryption::from), phone: phone.map(Encryption::from), description, phone_country_code, metadata, connector_customer: *connector_customer, modified_at: date_time::now(), default_billing_address, default_shipping_address, default_payment_method_id, updated_by: None, status, tax_registration_id: tax_registration_id.map(Encryption::from), } } CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, modified_at: date_time::now(), default_payment_method_id: None, updated_by: None, default_billing_address: None, default_shipping_address: None, status: None, tax_registration_id: None, }, CustomerUpdate::UpdateDefaultPaymentMethod { default_payment_method_id, } => Self { default_payment_method_id, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, connector_customer: None, updated_by: None, default_billing_address: None, default_shipping_address: None, status: None, tax_registration_id: None, }, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub enum CustomerUpdate { Update { name: crypto::OptionalEncryptableName, email: crypto::OptionalEncryptableEmail, phone: Box<crypto::OptionalEncryptablePhone>, description: Option<Description>, phone_country_code: Option<String>, metadata: Box<Option<pii::SecretSerdeValue>>, connector_customer: Box<Option<pii::SecretSerdeValue>>, address_id: Option<String>, tax_registration_id: crypto::OptionalEncryptableSecretString, }, ConnectorCustomer { connector_customer: Option<pii::SecretSerdeValue>, }, UpdateDefaultPaymentMethod { default_payment_method_id: Option<Option<String>>, }, } #[cfg(feature = "v1")] impl From<CustomerUpdate> for CustomerUpdateInternal { fn from(customer_update: CustomerUpdate) -> Self { match customer_update { CustomerUpdate::Update { name, email, phone, description, phone_country_code, metadata, connector_customer, address_id, tax_registration_id, } => Self { name: name.map(Encryption::from), email: email.map(Encryption::from), phone: phone.map(Encryption::from), description, phone_country_code, metadata: *metadata, connector_customer: *connector_customer, modified_at: date_time::now(), address_id, default_payment_method_id: None, updated_by: None, tax_registration_id: tax_registration_id.map(Encryption::from), }, CustomerUpdate::ConnectorCustomer { connector_customer } => Self { connector_customer, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, default_payment_method_id: None, updated_by: None, address_id: None, tax_registration_id: None, }, CustomerUpdate::UpdateDefaultPaymentMethod { default_payment_method_id, } => Self { default_payment_method_id, modified_at: date_time::now(), name: None, email: None, phone: None, description: None, phone_country_code: None, metadata: None, connector_customer: None, updated_by: None, address_id: None, tax_registration_id: None, }, } } } pub struct CustomerListConstraints { pub limit: u16, pub offset: Option<u32>, pub customer_id: Option<id_type::CustomerId>, pub time_range: Option<common_utils::types::TimeRange>, } impl From<CustomerListConstraints> for query::CustomerListConstraints { fn from(value: CustomerListConstraints) -> Self { Self { limit: i64::from(value.limit), offset: value.offset.map(i64::from), customer_id: value.customer_id, time_range: value.time_range, } } } #[async_trait::async_trait] pub trait CustomerInterface where Customer: behaviour::Conversion< DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew, >, { type Error; #[cfg(feature = "v1")] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v2")] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<Customer>, Self::Error>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: Customer, customer_update: CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v1")] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<Customer>, Self::Error>; async fn list_customers_by_merchant_id_with_count( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<(Vec<Customer>, usize), Self::Error>; async fn insert_customer( &self, customer_data: Customer, state: &KeyManagerState, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: Customer, customer_update: CustomerUpdate, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; #[cfg(feature = "v2")] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Customer, Self::Error>; } #[cfg(feature = "v1")] #[instrument] pub async fn update_connector_customer_in_customers( connector_label: &str, customer: Option<&Customer>, connector_customer_id: Option<String>, ) -> Option<CustomerUpdate> { let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone().expose_option()) .and_then(|connector_customer| connector_customer.as_object().cloned()) .unwrap_or_default(); let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| { let connector_customer_value = serde_json::Value::String(connector_customer_id); connector_customer_map.insert(connector_label.to_string(), connector_customer_value); connector_customer_map }); updated_connector_customer_map .map(serde_json::Value::Object) .map( |connector_customer_value| CustomerUpdate::ConnectorCustomer { connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)), }, ) } #[cfg(feature = "v2")] #[instrument] pub async fn update_connector_customer_in_customers( merchant_connector_account: &MerchantConnectorAccountTypeDetails, customer: Option<&Customer>, connector_customer_id: Option<String>, ) -> Option<CustomerUpdate> { match merchant_connector_account { MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => { connector_customer_id.map(|new_conn_cust_id| { let connector_account_id = account.get_id().clone(); let mut connector_customer_map = customer .and_then(|customer| customer.connector_customer.clone()) .unwrap_or_default(); connector_customer_map.insert(connector_account_id, new_conn_cust_id); CustomerUpdate::ConnectorCustomer { connector_customer: Some(connector_customer_map), } }) } // TODO: Construct connector_customer for MerchantConnectorDetails if required by connector. MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { todo!("Handle connector_customer construction for MerchantConnectorDetails"); } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/customer.rs", "file_size": 28462, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-8818908692104103279
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/lib.rs // File size: 27121 bytes pub mod address; pub mod api; pub mod authentication; pub mod behaviour; pub mod bulk_tokenization; pub mod business_profile; pub mod callback_mapper; pub mod card_testing_guard_data; pub mod cards_info; pub mod chat; pub mod configs; pub mod connector_endpoints; pub mod consts; pub mod customer; pub mod disputes; pub mod errors; pub mod ext_traits; pub mod gsm; pub mod invoice; pub mod mandates; pub mod master_key; pub mod merchant_account; pub mod merchant_connector_account; pub mod merchant_context; pub mod merchant_key_store; pub mod network_tokenization; pub mod payment_address; pub mod payment_method_data; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod refunds; pub mod relay; #[cfg(all(feature = "v2", feature = "revenue_recovery"))] pub mod revenue_recovery; pub mod router_data; pub mod router_data_v2; pub mod router_flow_types; pub mod router_request_types; pub mod router_response_types; pub mod routing; pub mod subscription; #[cfg(feature = "tokenization_v2")] pub mod tokenization; pub mod transformers; pub mod type_encryption; pub mod types; pub mod vault; #[cfg(not(feature = "payouts"))] pub trait PayoutAttemptInterface {} #[cfg(not(feature = "payouts"))] pub trait PayoutsInterface {} use api_models::payments::{ ApplePayRecurringDetails as ApiApplePayRecurringDetails, ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails, FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount, RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit, RedirectResponse as ApiRedirectResponse, }; #[cfg(feature = "v2")] use api_models::payments::{ BillingConnectorAdditionalCardInfo as ApiBillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails, BillingConnectorPaymentMethodDetails as ApiBillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata, }; use diesel_models::types::{ ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata, OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse, }; #[cfg(feature = "v2")] use diesel_models::types::{ BillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails, BillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata, }; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub enum RemoteStorageObject<T: ForeignIDRef> { ForeignID(String), Object(T), } impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> { fn from(value: T) -> Self { Self::Object(value) } } pub trait ForeignIDRef { fn foreign_id(&self) -> String; } impl<T: ForeignIDRef> RemoteStorageObject<T> { pub fn get_id(&self) -> String { match self { Self::ForeignID(id) => id.clone(), Self::Object(i) => i.foreign_id(), } } } use std::fmt::Debug; pub trait ApiModelToDieselModelConvertor<F> { /// Convert from a foreign type to the current type fn convert_from(from: F) -> Self; fn convert_back(self) -> F; } #[cfg(feature = "v1")] impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { fn convert_from(from: ApiFeatureMetadata) -> Self { let ApiFeatureMetadata { redirect_response, search_tags, apple_pay_recurring_details, } = from; Self { redirect_response: redirect_response.map(RedirectResponse::convert_from), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(ApplePayRecurringDetails::convert_from), gateway_system: None, } } fn convert_back(self) -> ApiFeatureMetadata { let Self { redirect_response, search_tags, apple_pay_recurring_details, .. } = self; ApiFeatureMetadata { redirect_response: redirect_response .map(|redirect_response| redirect_response.convert_back()), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(|value| value.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { fn convert_from(from: ApiFeatureMetadata) -> Self { let ApiFeatureMetadata { redirect_response, search_tags, apple_pay_recurring_details, revenue_recovery: payment_revenue_recovery_metadata, } = from; Self { redirect_response: redirect_response.map(RedirectResponse::convert_from), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(ApplePayRecurringDetails::convert_from), payment_revenue_recovery_metadata: payment_revenue_recovery_metadata .map(PaymentRevenueRecoveryMetadata::convert_from), } } fn convert_back(self) -> ApiFeatureMetadata { let Self { redirect_response, search_tags, apple_pay_recurring_details, payment_revenue_recovery_metadata, } = self; ApiFeatureMetadata { redirect_response: redirect_response .map(|redirect_response| redirect_response.convert_back()), search_tags, apple_pay_recurring_details: apple_pay_recurring_details .map(|value| value.convert_back()), revenue_recovery: payment_revenue_recovery_metadata.map(|value| value.convert_back()), } } } impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse { fn convert_from(from: ApiRedirectResponse) -> Self { let ApiRedirectResponse { param, json_payload, } = from; Self { param, json_payload, } } fn convert_back(self) -> ApiRedirectResponse { let Self { param, json_payload, } = self; ApiRedirectResponse { param, json_payload, } } } impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit> for RecurringPaymentIntervalUnit { fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self { match from { ApiRecurringPaymentIntervalUnit::Year => Self::Year, ApiRecurringPaymentIntervalUnit::Month => Self::Month, ApiRecurringPaymentIntervalUnit::Day => Self::Day, ApiRecurringPaymentIntervalUnit::Hour => Self::Hour, ApiRecurringPaymentIntervalUnit::Minute => Self::Minute, } } fn convert_back(self) -> ApiRecurringPaymentIntervalUnit { match self { Self::Year => ApiRecurringPaymentIntervalUnit::Year, Self::Month => ApiRecurringPaymentIntervalUnit::Month, Self::Day => ApiRecurringPaymentIntervalUnit::Day, Self::Hour => ApiRecurringPaymentIntervalUnit::Hour, Self::Minute => ApiRecurringPaymentIntervalUnit::Minute, } } } impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails> for ApplePayRegularBillingDetails { fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self { Self { label: from.label, recurring_payment_start_date: from.recurring_payment_start_date, recurring_payment_end_date: from.recurring_payment_end_date, recurring_payment_interval_unit: from .recurring_payment_interval_unit .map(RecurringPaymentIntervalUnit::convert_from), recurring_payment_interval_count: from.recurring_payment_interval_count, } } fn convert_back(self) -> ApiApplePayRegularBillingDetails { ApiApplePayRegularBillingDetails { label: self.label, recurring_payment_start_date: self.recurring_payment_start_date, recurring_payment_end_date: self.recurring_payment_end_date, recurring_payment_interval_unit: self .recurring_payment_interval_unit .map(|value| value.convert_back()), recurring_payment_interval_count: self.recurring_payment_interval_count, } } } impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails { fn convert_from(from: ApiApplePayRecurringDetails) -> Self { Self { payment_description: from.payment_description, regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing), billing_agreement: from.billing_agreement, management_url: from.management_url, } } fn convert_back(self) -> ApiApplePayRecurringDetails { ApiApplePayRecurringDetails { payment_description: self.payment_description, regular_billing: self.regular_billing.convert_back(), billing_agreement: self.billing_agreement, management_url: self.management_url, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorAdditionalCardInfo> for BillingConnectorAdditionalCardInfo { fn convert_from(from: ApiBillingConnectorAdditionalCardInfo) -> Self { Self { card_issuer: from.card_issuer, card_network: from.card_network, } } fn convert_back(self) -> ApiBillingConnectorAdditionalCardInfo { ApiBillingConnectorAdditionalCardInfo { card_issuer: self.card_issuer, card_network: self.card_network, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentMethodDetails> for BillingConnectorPaymentMethodDetails { fn convert_from(from: ApiBillingConnectorPaymentMethodDetails) -> Self { match from { ApiBillingConnectorPaymentMethodDetails::Card(data) => { Self::Card(BillingConnectorAdditionalCardInfo::convert_from(data)) } } } fn convert_back(self) -> ApiBillingConnectorPaymentMethodDetails { match self { Self::Card(data) => ApiBillingConnectorPaymentMethodDetails::Card(data.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata { fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self { Self { total_retry_count: from.total_retry_count, payment_connector_transmission: from.payment_connector_transmission.unwrap_or_default(), billing_connector_id: from.billing_connector_id, active_attempt_payment_connector_id: from.active_attempt_payment_connector_id, billing_connector_payment_details: BillingConnectorPaymentDetails::convert_from( from.billing_connector_payment_details, ), payment_method_type: from.payment_method_type, payment_method_subtype: from.payment_method_subtype, connector: from.connector, invoice_next_billing_time: from.invoice_next_billing_time, billing_connector_payment_method_details: from .billing_connector_payment_method_details .map(BillingConnectorPaymentMethodDetails::convert_from), first_payment_attempt_network_advice_code: from .first_payment_attempt_network_advice_code, first_payment_attempt_network_decline_code: from .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code, invoice_billing_started_at_time: from.invoice_billing_started_at_time, } } fn convert_back(self) -> ApiRevenueRecoveryMetadata { ApiRevenueRecoveryMetadata { total_retry_count: self.total_retry_count, payment_connector_transmission: Some(self.payment_connector_transmission), billing_connector_id: self.billing_connector_id, active_attempt_payment_connector_id: self.active_attempt_payment_connector_id, billing_connector_payment_details: self .billing_connector_payment_details .convert_back(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, connector: self.connector, invoice_next_billing_time: self.invoice_next_billing_time, billing_connector_payment_method_details: self .billing_connector_payment_method_details .map(|data| data.convert_back()), first_payment_attempt_network_advice_code: self .first_payment_attempt_network_advice_code, first_payment_attempt_network_decline_code: self .first_payment_attempt_network_decline_code, first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code, invoice_billing_started_at_time: self.invoice_billing_started_at_time, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentDetails> for BillingConnectorPaymentDetails { fn convert_from(from: ApiBillingConnectorPaymentDetails) -> Self { Self { payment_processor_token: from.payment_processor_token, connector_customer_id: from.connector_customer_id, } } fn convert_back(self) -> ApiBillingConnectorPaymentDetails { ApiBillingConnectorPaymentDetails { payment_processor_token: self.payment_processor_token, connector_customer_id: self.connector_customer_id, } } } impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount { fn convert_from(from: ApiOrderDetailsWithAmount) -> Self { let ApiOrderDetailsWithAmount { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } = from; Self { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } } fn convert_back(self) -> ApiOrderDetailsWithAmount { let Self { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } = self; ApiOrderDetailsWithAmount { product_name, quantity, amount, requires_shipping, product_img_link, product_id, category, sub_category, brand, product_type, product_tax_code, tax_rate, total_tax_amount, description, sku, upc, commodity_code, unit_of_measure, total_amount, unit_discount_amount, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest> for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments { fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, details_layout: item.details_layout, transaction_details: item.transaction_details.map(|transaction_details| { transaction_details .into_iter() .map(|transaction_detail| { diesel_models::PaymentLinkTransactionDetails::convert_from( transaction_detail, ) }) .collect() }), background_image: item.background_image.map(|background_image| { diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from( background_image, ) }), payment_button_text: item.payment_button_text, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, skip_status_screen: item.skip_status_screen, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, payment_form_header_text: item.payment_form_header_text, payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest { let Self { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, transaction_details, background_image, details_layout, payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, } = self; api_models::admin::PaymentLinkConfigRequest { theme, logo, seller_name, sdk_layout, display_sdk_only, enabled_saved_payment_method, hide_card_nickname_field, show_card_form_by_default, details_layout, transaction_details: transaction_details.map(|transaction_details| { transaction_details .into_iter() .map(|transaction_detail| transaction_detail.convert_back()) .collect() }), background_image: background_image .map(|background_image| background_image.convert_back()), payment_button_text, custom_message_for_card_terms, payment_button_colour, skip_status_screen, background_colour, payment_button_text_colour, sdk_ui_rules, payment_link_ui_rules, enable_button_only_on_form_ready, payment_form_header_text, payment_form_label_type, show_card_terms, is_setup_mandate_flow, color_icon_card_cvc_error, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails> for diesel_models::PaymentLinkTransactionDetails { fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self { Self { key: from.key, value: from.value, ui_configuration: from .ui_configuration .map(diesel_models::TransactionDetailsUiConfiguration::convert_from), } } fn convert_back(self) -> api_models::admin::PaymentLinkTransactionDetails { let Self { key, value, ui_configuration, } = self; api_models::admin::PaymentLinkTransactionDetails { key, value, ui_configuration: ui_configuration .map(|ui_configuration| ui_configuration.convert_back()), } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig> for diesel_models::business_profile::PaymentLinkBackgroundImageConfig { fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self { Self { url: from.url, position: from.position, size: from.size, } } fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig { let Self { url, position, size, } = self; api_models::admin::PaymentLinkBackgroundImageConfig { url, position, size, } } } #[cfg(feature = "v2")] impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration> for diesel_models::TransactionDetailsUiConfiguration { fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self { Self { position: from.position, is_key_bold: from.is_key_bold, is_value_bold: from.is_value_bold, } } fn convert_back(self) -> api_models::admin::TransactionDetailsUiConfiguration { let Self { position, is_key_bold, is_value_bold, } = self; api_models::admin::TransactionDetailsUiConfiguration { position, is_key_bold, is_value_bold, } } } #[cfg(feature = "v2")] impl From<api_models::payments::AmountDetails> for payments::AmountDetails { fn from(amount_details: api_models::payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount().into(), currency: amount_details.currency(), shipping_cost: amount_details.shipping_cost(), tax_details: amount_details.order_tax_amount().map(|order_tax_amount| { diesel_models::TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount }), payment_method_type: None, } }), skip_external_tax_calculation: amount_details.skip_external_tax_calculation(), skip_surcharge_calculation: amount_details.skip_surcharge_calculation(), surcharge_amount: amount_details.surcharge_amount(), tax_on_surcharge: amount_details.tax_on_surcharge(), // We will not receive this in the request. This will be populated after calling the connector / processor amount_captured: None, } } } #[cfg(feature = "v2")] impl From<payments::AmountDetails> for api_models::payments::AmountDetailsSetter { fn from(amount_details: payments::AmountDetails) -> Self { Self { order_amount: amount_details.order_amount.into(), currency: amount_details.currency, shipping_cost: amount_details.shipping_cost, order_tax_amount: amount_details .tax_details .and_then(|tax_detail| tax_detail.get_default_tax_amount()), skip_external_tax_calculation: amount_details.skip_external_tax_calculation, skip_surcharge_calculation: amount_details.skip_surcharge_calculation, surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, } } } #[cfg(feature = "v2")] impl From<&api_models::payments::PaymentAttemptAmountDetails> for payments::payment_attempt::AttemptAmountDetailsSetter { fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self { Self { net_amount: amount.net_amount, amount_to_capture: amount.amount_to_capture, surcharge_amount: amount.surcharge_amount, tax_on_surcharge: amount.tax_on_surcharge, amount_capturable: amount.amount_capturable, shipping_cost: amount.shipping_cost, order_tax_amount: amount.order_tax_amount, } } } #[cfg(feature = "v2")] impl From<&payments::payment_attempt::AttemptAmountDetailsSetter> for api_models::payments::PaymentAttemptAmountDetails { fn from(amount: &payments::payment_attempt::AttemptAmountDetailsSetter) -> Self { Self { net_amount: amount.net_amount, amount_to_capture: amount.amount_to_capture, surcharge_amount: amount.surcharge_amount, tax_on_surcharge: amount.tax_on_surcharge, amount_capturable: amount.amount_capturable, shipping_cost: amount.shipping_cost, order_tax_amount: amount.order_tax_amount, } } } #[cfg(feature = "v2")] impl From<&api_models::payments::RecordAttemptErrorDetails> for payments::payment_attempt::ErrorDetails { fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self { Self { code: error.code.clone(), message: error.message.clone(), reason: Some(error.message.clone()), unified_code: None, unified_message: None, network_advice_code: error.network_advice_code.clone(), network_decline_code: error.network_decline_code.clone(), network_error_message: error.network_error_message.clone(), } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/lib.rs", "file_size": 27121, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-2473829800454306751
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/router_response_types.rs // File size: 24429 bytes pub mod disputes; pub mod fraud_check; pub mod revenue_recovery; pub mod subscriptions; use std::collections::HashMap; use api_models::payments::AddressDetails; use common_utils::{pii, request::Method, types::MinorUnit}; pub use disputes::{ AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, SubmitEvidenceResponse, }; use serde::Serialize; use crate::{ errors::api_error_response::ApiErrorResponse, router_request_types::{authentication::AuthNFlowType, ResponseId}, vault::PaymentMethodVaultingData, }; #[derive(Debug, Clone)] pub struct RefundsResponseData { pub connector_refund_id: String, pub refund_status: common_enums::RefundStatus, // pub amount_received: Option<i32>, // Calculation for amount received not in place yet } #[derive(Debug, Clone, Serialize)] pub struct ConnectorCustomerResponseData { pub connector_customer_id: String, pub name: Option<String>, pub email: Option<String>, pub billing_address: Option<AddressDetails>, } impl ConnectorCustomerResponseData { pub fn new_with_customer_id(connector_customer_id: String) -> Self { Self::new(connector_customer_id, None, None, None) } pub fn new( connector_customer_id: String, name: Option<String>, email: Option<String>, billing_address: Option<AddressDetails>, ) -> Self { Self { connector_customer_id, name, email, billing_address, } } } #[derive(Debug, Clone, Serialize)] pub enum PaymentsResponseData { TransactionResponse { resource_id: ResponseId, redirection_data: Box<Option<RedirectForm>>, mandate_reference: Box<Option<MandateReference>>, connector_metadata: Option<serde_json::Value>, network_txn_id: Option<String>, connector_response_reference_id: Option<String>, incremental_authorization_allowed: Option<bool>, charges: Option<common_types::payments::ConnectorChargeResponseData>, }, MultipleCaptureResponse { // pending_capture_id_list: Vec<String>, capture_sync_response_list: HashMap<String, CaptureSyncResponse>, }, SessionResponse { session_token: api_models::payments::SessionToken, }, SessionTokenResponse { session_token: String, }, TransactionUnresolvedResponse { resource_id: ResponseId, //to add more info on cypto response, like `unresolved` reason(overpaid, underpaid, delayed) reason: Option<api_models::enums::UnresolvedResponseReason>, connector_response_reference_id: Option<String>, }, TokenizationResponse { token: String, }, ConnectorCustomerResponse(ConnectorCustomerResponseData), ThreeDSEnrollmentResponse { enrolled_v2: bool, related_transaction_id: Option<String>, }, PreProcessingResponse { pre_processing_id: PreprocessingResponseId, connector_metadata: Option<serde_json::Value>, session_token: Option<api_models::payments::SessionToken>, connector_response_reference_id: Option<String>, }, IncrementalAuthorizationResponse { status: common_enums::AuthorizationStatus, connector_authorization_id: Option<String>, error_code: Option<String>, error_message: Option<String>, }, PostProcessingResponse { session_token: Option<api_models::payments::OpenBankingSessionToken>, }, PaymentResourceUpdateResponse { status: common_enums::PaymentResourceUpdateStatus, }, PaymentsCreateOrderResponse { order_id: String, }, } #[derive(Debug, Clone)] pub struct GiftCardBalanceCheckResponseData { pub balance: MinorUnit, pub currency: common_enums::Currency, } #[derive(Debug, Clone)] pub struct TaxCalculationResponseData { pub order_tax_amount: MinorUnit, } #[derive(Serialize, Debug, Clone)] pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_request_reference_id: Option<String>, } #[derive(Debug, Clone, Serialize)] pub enum CaptureSyncResponse { Success { resource_id: ResponseId, status: common_enums::AttemptStatus, connector_response_reference_id: Option<String>, amount: Option<MinorUnit>, }, Error { code: String, message: String, reason: Option<String>, status_code: u16, amount: Option<MinorUnit>, }, } impl CaptureSyncResponse { pub fn get_amount_captured(&self) -> Option<MinorUnit> { match self { Self::Success { amount, .. } | Self::Error { amount, .. } => *amount, } } pub fn get_connector_response_reference_id(&self) -> Option<String> { match self { Self::Success { connector_response_reference_id, .. } => connector_response_reference_id.clone(), Self::Error { .. } => None, } } } impl PaymentsResponseData { pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>> { match self { Self::TransactionResponse { connector_metadata, .. } | Self::PreProcessingResponse { connector_metadata, .. } => connector_metadata.clone().map(masking::Secret::new), _ => None, } } pub fn get_network_transaction_id(&self) -> Option<String> { match self { Self::TransactionResponse { network_txn_id, .. } => network_txn_id.clone(), _ => None, } } pub fn get_connector_transaction_id( &self, ) -> Result<String, error_stack::Report<ApiErrorResponse>> { match self { Self::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(txn_id), .. } => Ok(txn_id.to_string()), _ => Err(ApiErrorResponse::MissingRequiredField { field_name: "ConnectorTransactionId", } .into()), } } pub fn merge_transaction_responses( auth_response: &Self, capture_response: &Self, ) -> Result<Self, error_stack::Report<ApiErrorResponse>> { match (auth_response, capture_response) { ( Self::TransactionResponse { resource_id: _, redirection_data: auth_redirection_data, mandate_reference: auth_mandate_reference, connector_metadata: auth_connector_metadata, network_txn_id: auth_network_txn_id, connector_response_reference_id: auth_connector_response_reference_id, incremental_authorization_allowed: auth_incremental_auth_allowed, charges: auth_charges, }, Self::TransactionResponse { resource_id: capture_resource_id, redirection_data: capture_redirection_data, mandate_reference: capture_mandate_reference, connector_metadata: capture_connector_metadata, network_txn_id: capture_network_txn_id, connector_response_reference_id: capture_connector_response_reference_id, incremental_authorization_allowed: capture_incremental_auth_allowed, charges: capture_charges, }, ) => Ok(Self::TransactionResponse { resource_id: capture_resource_id.clone(), redirection_data: Box::new( capture_redirection_data .clone() .or_else(|| *auth_redirection_data.clone()), ), mandate_reference: Box::new( auth_mandate_reference .clone() .or_else(|| *capture_mandate_reference.clone()), ), connector_metadata: capture_connector_metadata .clone() .or(auth_connector_metadata.clone()), network_txn_id: capture_network_txn_id .clone() .or(auth_network_txn_id.clone()), connector_response_reference_id: capture_connector_response_reference_id .clone() .or(auth_connector_response_reference_id.clone()), incremental_authorization_allowed: (*capture_incremental_auth_allowed) .or(*auth_incremental_auth_allowed), charges: auth_charges.clone().or(capture_charges.clone()), }), _ => Err(ApiErrorResponse::NotSupported { message: "Invalid Flow ".to_owned(), } .into()), } } #[cfg(feature = "v2")] pub fn get_updated_connector_token_details( &self, original_connector_mandate_request_reference_id: Option<String>, ) -> Option<diesel_models::ConnectorTokenDetails> { if let Self::TransactionResponse { mandate_reference, .. } = self { mandate_reference.clone().map(|mandate_ref| { let connector_mandate_id = mandate_ref.connector_mandate_id; let connector_mandate_request_reference_id = mandate_ref .connector_mandate_request_reference_id .or(original_connector_mandate_request_reference_id); diesel_models::ConnectorTokenDetails { connector_mandate_id, connector_token_request_reference_id: connector_mandate_request_reference_id, } }) } else { None } } } #[derive(Debug, Clone, Serialize)] pub enum PreprocessingResponseId { PreProcessingId(String), ConnectorTransactionId(String), } #[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)] pub enum RedirectForm { Form { endpoint: String, method: Method, form_fields: HashMap<String, String>, }, Html { html_data: String, }, BarclaycardAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, BarclaycardConsumerAuth { access_token: String, step_up_url: String, }, BlueSnap { payment_fields_token: String, // payment-field-token }, CybersourceAuthSetup { access_token: String, ddc_url: String, reference_id: String, }, CybersourceConsumerAuth { access_token: String, step_up_url: String, }, DeutschebankThreeDSChallengeFlow { acs_url: String, creq: String, }, Payme, Braintree { client_token: String, card_token: String, bin: String, acs_url: String, }, Nmi { amount: String, currency: common_enums::Currency, public_key: masking::Secret<String>, customer_vault_id: String, order_id: String, }, Mifinity { initialization_token: String, }, WorldpayDDCForm { endpoint: url::Url, method: Method, form_fields: HashMap<String, String>, collection_id: Option<String>, }, } impl From<(url::Url, Method)> for RedirectForm { fn from((mut redirect_url, method): (url::Url, Method)) -> Self { let form_fields = HashMap::from_iter( redirect_url .query_pairs() .map(|(key, value)| (key.to_string(), value.to_string())), ); // Do not include query params in the endpoint redirect_url.set_query(None); Self::Form { endpoint: redirect_url.to_string(), method, form_fields, } } } impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm { fn from(redirect_form: RedirectForm) -> Self { match redirect_form { RedirectForm::Form { endpoint, method, form_fields, } => Self::Form { endpoint, method, form_fields, }, RedirectForm::Html { html_data } => Self::Html { html_data }, RedirectForm::BarclaycardAuthSetup { access_token, ddc_url, reference_id, } => Self::BarclaycardAuthSetup { access_token, ddc_url, reference_id, }, RedirectForm::BarclaycardConsumerAuth { access_token, step_up_url, } => Self::BarclaycardConsumerAuth { access_token, step_up_url, }, RedirectForm::BlueSnap { payment_fields_token, } => Self::BlueSnap { payment_fields_token, }, RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => Self::CybersourceAuthSetup { access_token, ddc_url, reference_id, }, RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => Self::CybersourceConsumerAuth { access_token, step_up_url, }, RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } } RedirectForm::Payme => Self::Payme, RedirectForm::Braintree { client_token, card_token, bin, acs_url, } => Self::Braintree { client_token, card_token, bin, acs_url, }, RedirectForm::Nmi { amount, currency, public_key, customer_vault_id, order_id, } => Self::Nmi { amount, currency, public_key, customer_vault_id, order_id, }, RedirectForm::Mifinity { initialization_token, } => Self::Mifinity { initialization_token, }, RedirectForm::WorldpayDDCForm { endpoint, method, form_fields, collection_id, } => Self::WorldpayDDCForm { endpoint: common_utils::types::Url::wrap(endpoint), method, form_fields, collection_id, }, } } } impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm { fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self { match redirect_form { diesel_models::payment_attempt::RedirectForm::Form { endpoint, method, form_fields, } => Self::Form { endpoint, method, form_fields, }, diesel_models::payment_attempt::RedirectForm::Html { html_data } => { Self::Html { html_data } } diesel_models::payment_attempt::RedirectForm::BarclaycardAuthSetup { access_token, ddc_url, reference_id, } => Self::BarclaycardAuthSetup { access_token, ddc_url, reference_id, }, diesel_models::payment_attempt::RedirectForm::BarclaycardConsumerAuth { access_token, step_up_url, } => Self::BarclaycardConsumerAuth { access_token, step_up_url, }, diesel_models::payment_attempt::RedirectForm::BlueSnap { payment_fields_token, } => Self::BlueSnap { payment_fields_token, }, diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => Self::CybersourceAuthSetup { access_token, ddc_url, reference_id, }, diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => Self::CybersourceConsumerAuth { access_token, step_up_url, }, diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } } diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme, diesel_models::payment_attempt::RedirectForm::Braintree { client_token, card_token, bin, acs_url, } => Self::Braintree { client_token, card_token, bin, acs_url, }, diesel_models::payment_attempt::RedirectForm::Nmi { amount, currency, public_key, customer_vault_id, order_id, } => Self::Nmi { amount, currency, public_key, customer_vault_id, order_id, }, diesel_models::payment_attempt::RedirectForm::Mifinity { initialization_token, } => Self::Mifinity { initialization_token, }, diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm { endpoint, method, form_fields, collection_id, } => Self::WorldpayDDCForm { endpoint: endpoint.into_inner(), method, form_fields, collection_id, }, } } } #[derive(Default, Clone, Debug)] pub struct UploadFileResponse { pub provider_file_id: String, } #[derive(Clone, Debug)] pub struct RetrieveFileResponse { pub file_data: Vec<u8>, } #[cfg(feature = "payouts")] #[derive(Clone, Debug, Default)] pub struct PayoutsResponseData { pub status: Option<common_enums::PayoutStatus>, pub connector_payout_id: Option<String>, pub payout_eligible: Option<bool>, pub should_add_next_step_to_process_tracker: bool, pub error_code: Option<String>, pub error_message: Option<String>, pub payout_connector_metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)] pub struct VerifyWebhookSourceResponseData { pub verify_webhook_status: VerifyWebhookStatus, } #[derive(Debug, Clone)] pub enum VerifyWebhookStatus { SourceVerified, SourceNotVerified, } #[derive(Debug, Clone)] pub struct MandateRevokeResponseData { pub mandate_status: common_enums::MandateStatus, } #[derive(Debug, Clone)] pub enum AuthenticationResponseData { PreAuthVersionCallResponse { maximum_supported_3ds_version: common_utils::types::SemanticVersion, }, PreAuthThreeDsMethodCallResponse { threeds_server_transaction_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, connector_metadata: Option<serde_json::Value>, }, PreAuthNResponse { threeds_server_transaction_id: String, maximum_supported_3ds_version: common_utils::types::SemanticVersion, connector_authentication_id: String, three_ds_method_data: Option<String>, three_ds_method_url: Option<String>, message_version: common_utils::types::SemanticVersion, connector_metadata: Option<serde_json::Value>, directory_server_id: Option<String>, }, AuthNResponse { authn_flow_type: AuthNFlowType, authentication_value: Option<masking::Secret<String>>, trans_status: common_enums::TransactionStatus, connector_metadata: Option<serde_json::Value>, ds_trans_id: Option<String>, eci: Option<String>, challenge_code: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, message_extension: Option<pii::SecretSerdeValue>, }, PostAuthNResponse { trans_status: common_enums::TransactionStatus, authentication_value: Option<masking::Secret<String>>, eci: Option<String>, challenge_cancel: Option<String>, challenge_code_reason: Option<String>, }, } #[derive(Debug, Clone)] pub struct CompleteAuthorizeRedirectResponse { pub params: Option<masking::Secret<String>>, pub payload: Option<pii::SecretSerdeValue>, } /// Represents details of a payment method. #[derive(Debug, Clone)] pub struct PaymentMethodDetails { /// Indicates whether mandates are supported by this payment method. pub mandates: common_enums::FeatureStatus, /// Indicates whether refund is supported by this payment method. pub refunds: common_enums::FeatureStatus, /// List of supported capture methods pub supported_capture_methods: Vec<common_enums::CaptureMethod>, /// Payment method specific features pub specific_features: Option<api_models::feature_matrix::PaymentMethodSpecificFeatures>, } /// list of payment method types and metadata related to them pub type PaymentMethodTypeMetadata = HashMap<common_enums::PaymentMethodType, PaymentMethodDetails>; /// list of payment methods, payment method types and metadata related to them pub type SupportedPaymentMethods = HashMap<common_enums::PaymentMethod, PaymentMethodTypeMetadata>; #[derive(Debug, Clone)] pub struct ConnectorInfo { /// Display name of the Connector pub display_name: &'static str, /// Description of the connector. pub description: &'static str, /// Connector Type pub connector_type: common_enums::HyperswitchConnectorCategory, /// Integration status of the connector pub integration_status: common_enums::ConnectorIntegrationStatus, } pub trait SupportedPaymentMethodsExt { fn add( &mut self, payment_method: common_enums::PaymentMethod, payment_method_type: common_enums::PaymentMethodType, payment_method_details: PaymentMethodDetails, ); } impl SupportedPaymentMethodsExt for SupportedPaymentMethods { fn add( &mut self, payment_method: common_enums::PaymentMethod, payment_method_type: common_enums::PaymentMethodType, payment_method_details: PaymentMethodDetails, ) { if let Some(payment_method_data) = self.get_mut(&payment_method) { payment_method_data.insert(payment_method_type, payment_method_details); } else { let mut payment_method_type_metadata = PaymentMethodTypeMetadata::new(); payment_method_type_metadata.insert(payment_method_type, payment_method_details); self.insert(payment_method, payment_method_type_metadata); } } } #[derive(Debug, Clone)] pub enum VaultResponseData { ExternalVaultCreateResponse { session_id: masking::Secret<String>, client_secret: masking::Secret<String>, }, ExternalVaultInsertResponse { connector_vault_id: String, fingerprint_id: String, }, ExternalVaultRetrieveResponse { vault_data: PaymentMethodVaultingData, }, ExternalVaultDeleteResponse { connector_vault_id: String, }, } impl Default for VaultResponseData { fn default() -> Self { Self::ExternalVaultInsertResponse { connector_vault_id: String::new(), fingerprint_id: String::new(), } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/router_response_types.rs", "file_size": 24429, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-1477336632470821225
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/mandates.rs // File size: 17479 bytes use std::collections::HashMap; use api_models::payments::{ MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType, }; use common_enums::Currency; use common_types::payments as common_payments_types; use common_utils::{ date_time, errors::{CustomResult, ParsingError}, pii, types::MinorUnit, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::router_data::RecurringMandatePaymentData; #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct MandateDetails { pub update_mandate_id: Option<String>, } impl From<MandateDetails> for diesel_models::enums::MandateDetails { fn from(value: MandateDetails) -> Self { Self { update_mandate_id: value.update_mandate_id, } } } impl From<diesel_models::enums::MandateDetails> for MandateDetails { fn from(value: diesel_models::enums::MandateDetails) -> Self { Self { update_mandate_id: value.update_mandate_id, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { SingleUse(MandateAmountData), MultiUse(Option<MandateAmountData>), } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: MinorUnit, pub currency: Currency, pub start_date: Option<PrimitiveDateTime>, pub end_date: Option<PrimitiveDateTime>, pub metadata: Option<pii::SecretSerdeValue>, } // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateDataType>, } impl From<MandateType> for MandateDataType { fn from(mandate_type: MandateType) -> Self { match mandate_type { MandateType::SingleUse(mandate_amount_data) => { Self::SingleUse(mandate_amount_data.into()) } MandateType::MultiUse(mandate_amount_data) => { Self::MultiUse(mandate_amount_data.map(|d| d.into())) } } } } impl From<MandateDataType> for diesel_models::enums::MandateDataType { fn from(value: MandateDataType) -> Self { match value { MandateDataType::SingleUse(data) => Self::SingleUse(data.into()), MandateDataType::MultiUse(None) => Self::MultiUse(None), MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), } } } impl From<diesel_models::enums::MandateDataType> for MandateDataType { fn from(value: diesel_models::enums::MandateDataType) -> Self { use diesel_models::enums::MandateDataType as DieselMandateDataType; match value { DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()), DieselMandateDataType::MultiUse(None) => Self::MultiUse(None), DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())), } } } impl From<ApiMandateAmountData> for MandateAmountData { fn from(value: ApiMandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<MandateAmountData> for diesel_models::enums::MandateAmountData { fn from(value: MandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<diesel_models::enums::MandateAmountData> for MandateAmountData { fn from(value: diesel_models::enums::MandateAmountData) -> Self { Self { amount: value.amount, currency: value.currency, start_date: value.start_date, end_date: value.end_date, metadata: value.metadata, } } } impl From<ApiMandateData> for MandateData { fn from(value: ApiMandateData) -> Self { Self { customer_acceptance: value.customer_acceptance, mandate_type: value.mandate_type.map(|d| d.into()), update_mandate_id: value.update_mandate_id, } } } impl MandateAmountData { pub fn get_end_date( &self, format: date_time::DateFormat, ) -> error_stack::Result<Option<String>, ParsingError> { self.end_date .map(|date| { date_time::format_date(date, format) .change_context(ParsingError::DateTimeParsingError) }) .transpose() } pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<Currency>, pub mandate_metadata: Option<pii::SecretSerdeValue>, pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>, pub connector_mandate_request_reference_id: Option<String>, } #[cfg(feature = "v1")] impl From<&PaymentsMandateReferenceRecord> for RecurringMandatePaymentData { fn from(mandate_reference_record: &PaymentsMandateReferenceRecord) -> Self { Self { payment_method_type: mandate_reference_record.payment_method_type, original_payment_authorized_amount: mandate_reference_record .original_payment_authorized_amount, original_payment_authorized_currency: mandate_reference_record .original_payment_authorized_currency, mandate_metadata: mandate_reference_record.mandate_metadata.clone(), } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorTokenReferenceRecord { pub connector_token: String, pub payment_method_subtype: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<MinorUnit>, pub original_payment_authorized_currency: Option<Currency>, pub metadata: Option<pii::SecretSerdeValue>, pub connector_token_status: common_enums::ConnectorTokenStatus, pub connector_token_request_reference_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PayoutsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); impl std::ops::Deref for PayoutsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for PayoutsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsTokenReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>, ); #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[cfg(feature = "v1")] impl std::ops::Deref for PaymentsMandateReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v1")] impl std::ops::DerefMut for PaymentsMandateReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v2")] impl std::ops::Deref for PaymentsTokenReference { type Target = HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>; fn deref(&self) -> &Self::Target { &self.0 } } #[cfg(feature = "v2")] impl std::ops::DerefMut for PaymentsTokenReference { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsTokenReference>, pub payouts: Option<PayoutsMandateReference>, } impl CommonMandateReference { 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) } #[cfg(feature = "v2")] /// Insert a new payment token reference for the given connector_id 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)); } } } } impl From<diesel_models::CommonMandateReference> for CommonMandateReference { fn from(value: diesel_models::CommonMandateReference) -> Self { Self { payments: value.payments.map(|payments| payments.into()), payouts: value.payouts.map(|payouts| payouts.into()), } } } impl From<CommonMandateReference> for diesel_models::CommonMandateReference { fn from(value: CommonMandateReference) -> Self { Self { payments: value.payments.map(|payments| payments.into()), payouts: value.payouts.map(|payouts| payouts.into()), } } } impl From<diesel_models::PayoutsMandateReference> for PayoutsMandateReference { fn from(value: diesel_models::PayoutsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } impl From<PayoutsMandateReference> for diesel_models::PayoutsMandateReference { fn from(value: PayoutsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v1")] impl From<diesel_models::PaymentsMandateReference> for PaymentsMandateReference { fn from(value: diesel_models::PaymentsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v1")] impl From<PaymentsMandateReference> for diesel_models::PaymentsMandateReference { fn from(value: PaymentsMandateReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v2")] impl From<diesel_models::PaymentsTokenReference> for PaymentsTokenReference { fn from(value: diesel_models::PaymentsTokenReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } #[cfg(feature = "v2")] impl From<PaymentsTokenReference> for diesel_models::PaymentsTokenReference { fn from(value: PaymentsTokenReference) -> Self { Self( value .0 .into_iter() .map(|(key, record)| (key, record.into())) .collect(), ) } } impl From<diesel_models::PayoutsMandateReferenceRecord> for PayoutsMandateReferenceRecord { fn from(value: diesel_models::PayoutsMandateReferenceRecord) -> Self { Self { transfer_method_id: value.transfer_method_id, } } } impl From<PayoutsMandateReferenceRecord> for diesel_models::PayoutsMandateReferenceRecord { fn from(value: PayoutsMandateReferenceRecord) -> Self { Self { transfer_method_id: value.transfer_method_id, } } } #[cfg(feature = "v2")] impl From<diesel_models::ConnectorTokenReferenceRecord> for ConnectorTokenReferenceRecord { fn from(value: diesel_models::ConnectorTokenReferenceRecord) -> Self { let diesel_models::ConnectorTokenReferenceRecord { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } = value; Self { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } } } #[cfg(feature = "v1")] impl From<diesel_models::PaymentsMandateReferenceRecord> for PaymentsMandateReferenceRecord { fn from(value: diesel_models::PaymentsMandateReferenceRecord) -> Self { Self { connector_mandate_id: value.connector_mandate_id, payment_method_type: value.payment_method_type, original_payment_authorized_amount: value.original_payment_authorized_amount, original_payment_authorized_currency: value.original_payment_authorized_currency, mandate_metadata: value.mandate_metadata, connector_mandate_status: value.connector_mandate_status, connector_mandate_request_reference_id: value.connector_mandate_request_reference_id, } } } #[cfg(feature = "v2")] impl From<ConnectorTokenReferenceRecord> for diesel_models::ConnectorTokenReferenceRecord { fn from(value: ConnectorTokenReferenceRecord) -> Self { let ConnectorTokenReferenceRecord { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } = value; Self { connector_token, payment_method_subtype, original_payment_authorized_amount, original_payment_authorized_currency, metadata, connector_token_status, connector_token_request_reference_id, } } } #[cfg(feature = "v1")] impl From<PaymentsMandateReferenceRecord> for diesel_models::PaymentsMandateReferenceRecord { fn from(value: PaymentsMandateReferenceRecord) -> Self { Self { connector_mandate_id: value.connector_mandate_id, payment_method_type: value.payment_method_type, original_payment_authorized_amount: value.original_payment_authorized_amount, original_payment_authorized_currency: value.original_payment_authorized_currency, mandate_metadata: value.mandate_metadata, connector_mandate_status: value.connector_mandate_status, connector_mandate_request_reference_id: value.connector_mandate_request_reference_id, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/mandates.rs", "file_size": 17479, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_1374605185859014502
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/revenue_recovery.rs // File size: 14411 bytes use api_models::{payments as api_payments, webhooks}; use common_enums::enums as common_enums; use common_types::primitive_wrappers; use common_utils::{id_type, pii, types as util_types}; use time::PrimitiveDateTime; use crate::{ payments, router_response_types::revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, }, ApiModelToDieselModelConvertor, }; /// Recovery payload is unified struct constructed from billing connectors #[derive(Debug)] pub struct RevenueRecoveryAttemptData { /// transaction amount against invoice, accepted in minor unit. pub amount: util_types::MinorUnit, /// currency of the transaction pub currency: common_enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: id_type::PaymentReferenceId, /// transaction id reference at payment connector pub connector_transaction_id: Option<util_types::ConnectorTransactionId>, /// error code sent by billing connector. pub error_code: Option<String>, /// error message sent by billing connector. pub error_message: Option<String>, /// mandate token at payment processor end. pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. pub connector_customer_id: String, /// Payment gateway identifier id at billing processor. pub connector_account_reference_id: String, /// timestamp at which transaction has been created at billing connector pub transaction_created_at: Option<PrimitiveDateTime>, /// transaction status at billing connector equivalent to payment attempt status. pub status: common_enums::AttemptStatus, /// payment method of payment attempt. pub payment_method_type: common_enums::PaymentMethod, /// payment method sub type of the payment attempt. pub payment_method_sub_type: common_enums::PaymentMethodType, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, /// Number of attempts made for an invoice pub retry_count: Option<u16>, /// Time when next invoice will be generated which will be equal to the end time of the current invoice pub invoice_next_billing_time: Option<PrimitiveDateTime>, /// Time at which the invoice created pub invoice_billing_started_at_time: Option<PrimitiveDateTime>, /// stripe specific id used to validate duplicate attempts in revenue recovery flow pub charge_id: Option<String>, /// Additional card details pub card_info: api_payments::AdditionalCardInfo, } /// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors #[derive(Debug, Clone)] pub struct RevenueRecoveryInvoiceData { /// invoice amount at billing connector pub amount: util_types::MinorUnit, /// currency of the amount. pub currency: common_enums::Currency, /// merchant reference id at billing connector. ex: invoice_id pub merchant_reference_id: id_type::PaymentReferenceId, /// billing address id of the invoice pub billing_address: Option<api_payments::Address>, /// Retry count of the invoice pub retry_count: Option<u16>, /// Ending date of the invoice or the Next billing time of the Subscription pub next_billing_at: Option<PrimitiveDateTime>, /// Invoice Starting Time pub billing_started_at: Option<PrimitiveDateTime>, /// metadata of the merchant pub metadata: Option<pii::SecretSerdeValue>, /// Allow partial authorization for this payment pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>, } #[derive(Clone, Debug)] pub struct RecoveryPaymentIntent { pub payment_id: id_type::GlobalPaymentId, pub status: common_enums::IntentStatus, pub feature_metadata: Option<api_payments::FeatureMetadata>, pub merchant_id: id_type::MerchantId, pub merchant_reference_id: Option<id_type::PaymentReferenceId>, pub invoice_amount: util_types::MinorUnit, pub invoice_currency: common_enums::Currency, pub created_at: Option<PrimitiveDateTime>, pub billing_address: Option<api_payments::Address>, } #[derive(Clone, Debug)] pub struct RecoveryPaymentAttempt { pub attempt_id: id_type::GlobalAttemptId, pub attempt_status: common_enums::AttemptStatus, pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>, pub amount: util_types::MinorUnit, pub network_advice_code: Option<String>, pub network_decline_code: Option<String>, pub error_code: Option<String>, pub created_at: PrimitiveDateTime, } impl RecoveryPaymentAttempt { pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> { self.feature_metadata.as_ref().and_then(|metadata| { metadata .revenue_recovery .as_ref() .map(|recovery| recovery.attempt_triggered_by) }) } } impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails { fn from(data: &RevenueRecoveryInvoiceData) -> Self { let amount = api_payments::AmountDetailsSetter { order_amount: data.amount.into(), currency: data.currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, }; Self::new(amount) } } impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest { fn from(data: &RevenueRecoveryInvoiceData) -> Self { let amount_details = api_payments::AmountDetails::from(data); Self { amount_details, merchant_reference_id: Some(data.merchant_reference_id.clone()), routing_algorithm_id: None, // Payments in the revenue recovery flow are always recurring transactions, // so capture method will be always automatic. capture_method: Some(common_enums::CaptureMethod::Automatic), authentication_type: Some(common_enums::AuthenticationType::NoThreeDs), billing: data.billing_address.clone(), shipping: None, customer_id: None, customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent), description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: data.metadata.clone(), connector_metadata: None, feature_metadata: None, payment_link_enabled: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, force_3ds_challenge: None, merchant_connector_details: None, enable_partial_authorization: data.enable_partial_authorization, } } } impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData { fn from(data: &BillingConnectorInvoiceSyncResponse) -> Self { Self { amount: data.amount, currency: data.currency, merchant_reference_id: data.merchant_reference_id.clone(), billing_address: data.billing_address.clone(), retry_count: data.retry_count, next_billing_at: data.ends_at, billing_started_at: data.created_at, metadata: None, enable_partial_authorization: None, } } } impl From<( &BillingConnectorPaymentsSyncResponse, &RevenueRecoveryInvoiceData, )> for RevenueRecoveryAttemptData { fn from( data: ( &BillingConnectorPaymentsSyncResponse, &RevenueRecoveryInvoiceData, ), ) -> Self { let billing_connector_payment_details = data.0; let invoice_details = data.1; Self { amount: billing_connector_payment_details.amount, currency: billing_connector_payment_details.currency, merchant_reference_id: billing_connector_payment_details .merchant_reference_id .clone(), connector_transaction_id: billing_connector_payment_details .connector_transaction_id .clone(), error_code: billing_connector_payment_details.error_code.clone(), error_message: billing_connector_payment_details.error_message.clone(), processor_payment_method_token: billing_connector_payment_details .processor_payment_method_token .clone(), connector_customer_id: billing_connector_payment_details .connector_customer_id .clone(), connector_account_reference_id: billing_connector_payment_details .connector_account_reference_id .clone(), transaction_created_at: billing_connector_payment_details.transaction_created_at, status: billing_connector_payment_details.status, payment_method_type: billing_connector_payment_details.payment_method_type, payment_method_sub_type: billing_connector_payment_details.payment_method_sub_type, network_advice_code: None, network_decline_code: None, network_error_message: None, retry_count: invoice_details.retry_count, invoice_next_billing_time: invoice_details.next_billing_at, charge_id: billing_connector_payment_details.charge_id.clone(), invoice_billing_started_at_time: invoice_details.billing_started_at, card_info: billing_connector_payment_details.card_info.clone(), } } } impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails { fn from(data: &RevenueRecoveryAttemptData) -> Self { Self { net_amount: data.amount, amount_to_capture: None, surcharge_amount: None, tax_on_surcharge: None, amount_capturable: data.amount, shipping_cost: None, order_tax_amount: None, } } } impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> { fn from(data: &RevenueRecoveryAttemptData) -> Self { data.error_code .as_ref() .zip(data.error_message.clone()) .map(|(code, message)| api_payments::RecordAttemptErrorDetails { code: code.to_string(), message: message.to_string(), network_advice_code: data.network_advice_code.clone(), network_decline_code: data.network_decline_code.clone(), network_error_message: data.network_error_message.clone(), }) } } impl From<&payments::PaymentIntent> for RecoveryPaymentIntent { fn from(payment_intent: &payments::PaymentIntent) -> Self { Self { payment_id: payment_intent.id.clone(), status: payment_intent.status, feature_metadata: payment_intent .feature_metadata .clone() .map(|feature_metadata| feature_metadata.convert_back()), merchant_reference_id: payment_intent.merchant_reference_id.clone(), invoice_amount: payment_intent.amount_details.order_amount, invoice_currency: payment_intent.amount_details.currency, billing_address: payment_intent .billing_address .clone() .map(|address| api_payments::Address::from(address.into_inner())), merchant_id: payment_intent.merchant_id.clone(), created_at: Some(payment_intent.created_at), } } } impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt { fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self { Self { attempt_id: payment_attempt.id.clone(), attempt_status: payment_attempt.status, feature_metadata: payment_attempt .feature_metadata .clone() .map( |feature_metadata| api_payments::PaymentAttemptFeatureMetadata { revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| { api_payments::PaymentAttemptRevenueRecoveryData { attempt_triggered_by: recovery.attempt_triggered_by, charge_id: recovery.charge_id, } }), }, ), amount: payment_attempt.amount_details.get_net_amount(), network_advice_code: payment_attempt .error .clone() .and_then(|error| error.network_advice_code), network_decline_code: payment_attempt .error .clone() .and_then(|error| error.network_decline_code), error_code: payment_attempt .error .as_ref() .map(|error| error.code.clone()), created_at: payment_attempt.created_at, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/revenue_recovery.rs", "file_size": 14411, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_4131246301300791890
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/invoice.rs // File size: 12592 bytes use common_utils::{ errors::{CustomResult, ValidationError}, id_type::GenerateId, pii::SecretSerdeValue, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, }, }; use masking::{PeekInterface, Secret}; use utoipa::ToSchema; use crate::merchant_key_store::MerchantKeyStore; #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct Invoice { pub id: common_utils::id_type::InvoiceId, pub subscription_id: common_utils::id_type::SubscriptionId, pub merchant_id: common_utils::id_type::MerchantId, pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub payment_method_id: Option<String>, pub customer_id: common_utils::id_type::CustomerId, pub amount: MinorUnit, pub currency: String, pub status: common_enums::connector_enums::InvoiceStatus, pub provider_name: common_enums::connector_enums::Connector, pub metadata: Option<SecretSerdeValue>, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } #[async_trait::async_trait] impl super::behaviour::Conversion for Invoice { type DstType = diesel_models::invoice::Invoice; type NewDstType = diesel_models::invoice::InvoiceNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let now = common_utils::date_time::now(); Ok(diesel_models::invoice::Invoice { id: self.id, subscription_id: self.subscription_id, merchant_id: self.merchant_id, profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, payment_intent_id: self.payment_intent_id, payment_method_id: self.payment_method_id, customer_id: self.customer_id, amount: self.amount, currency: self.currency.to_string(), status: self.status, provider_name: self.provider_name, metadata: None, created_at: now, modified_at: now, connector_invoice_id: self.connector_invoice_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { id: item.id, subscription_id: item.subscription_id, merchant_id: item.merchant_id, profile_id: item.profile_id, merchant_connector_id: item.merchant_connector_id, payment_intent_id: item.payment_intent_id, payment_method_id: item.payment_method_id, customer_id: item.customer_id, amount: item.amount, currency: item.currency, status: item.status, provider_name: item.provider_name, metadata: item.metadata, connector_invoice_id: item.connector_invoice_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::invoice::InvoiceNew::new( self.subscription_id, self.merchant_id, self.profile_id, self.merchant_connector_id, self.payment_intent_id, self.payment_method_id, self.customer_id, self.amount, self.currency.to_string(), self.status, self.provider_name, None, self.connector_invoice_id, )) } } impl Invoice { #[allow(clippy::too_many_arguments)] pub fn to_invoice( subscription_id: common_utils::id_type::SubscriptionId, merchant_id: common_utils::id_type::MerchantId, profile_id: common_utils::id_type::ProfileId, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, payment_intent_id: Option<common_utils::id_type::PaymentId>, payment_method_id: Option<String>, customer_id: common_utils::id_type::CustomerId, amount: MinorUnit, currency: String, status: common_enums::connector_enums::InvoiceStatus, provider_name: common_enums::connector_enums::Connector, metadata: Option<SecretSerdeValue>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { Self { id: common_utils::id_type::InvoiceId::generate(), subscription_id, merchant_id, profile_id, merchant_connector_id, payment_intent_id, payment_method_id, customer_id, amount, currency: currency.to_string(), status, provider_name, metadata, connector_invoice_id, } } } #[async_trait::async_trait] pub trait InvoiceInterface { type Error; async fn insert_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_new: Invoice, ) -> CustomResult<Invoice, Self::Error>; async fn find_invoice_by_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, ) -> CustomResult<Invoice, Self::Error>; async fn update_invoice_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, invoice_id: String, data: InvoiceUpdate, ) -> CustomResult<Invoice, Self::Error>; async fn get_latest_invoice_for_subscription( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, ) -> CustomResult<Invoice, Self::Error>; async fn find_invoice_by_subscription_id_connector_invoice_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_id: String, connector_invoice_id: common_utils::id_type::InvoiceId, ) -> CustomResult<Option<Invoice>, Self::Error>; } pub struct InvoiceUpdate { pub status: Option<common_enums::connector_enums::InvoiceStatus>, pub payment_method_id: Option<String>, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, pub modified_at: time::PrimitiveDateTime, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub amount: Option<MinorUnit>, pub currency: Option<String>, } #[derive(Debug, Clone)] pub struct AmountAndCurrencyUpdate { pub amount: MinorUnit, pub currency: String, } #[derive(Debug, Clone)] pub struct ConnectorAndStatusUpdate { pub connector_invoice_id: common_utils::id_type::InvoiceId, pub status: common_enums::connector_enums::InvoiceStatus, } #[derive(Debug, Clone)] pub struct PaymentAndStatusUpdate { pub payment_method_id: Option<Secret<String>>, pub payment_intent_id: Option<common_utils::id_type::PaymentId>, pub status: common_enums::connector_enums::InvoiceStatus, pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>, } /// Enum-based invoice update request for different scenarios #[derive(Debug, Clone)] pub enum InvoiceUpdateRequest { /// Update amount and currency Amount(AmountAndCurrencyUpdate), /// Update connector invoice ID and status Connector(ConnectorAndStatusUpdate), /// Update payment details along with status PaymentStatus(PaymentAndStatusUpdate), } impl InvoiceUpdateRequest { /// Create an amount and currency update request pub fn update_amount_and_currency(amount: MinorUnit, currency: String) -> Self { Self::Amount(AmountAndCurrencyUpdate { amount, currency }) } /// Create a connector invoice ID and status update request pub fn update_connector_and_status( connector_invoice_id: common_utils::id_type::InvoiceId, status: common_enums::connector_enums::InvoiceStatus, ) -> Self { Self::Connector(ConnectorAndStatusUpdate { connector_invoice_id, status, }) } /// Create a combined payment and status update request pub fn update_payment_and_status( payment_method_id: Option<Secret<String>>, payment_intent_id: Option<common_utils::id_type::PaymentId>, status: common_enums::connector_enums::InvoiceStatus, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, ) -> Self { Self::PaymentStatus(PaymentAndStatusUpdate { payment_method_id, payment_intent_id, status, connector_invoice_id, }) } } impl From<InvoiceUpdateRequest> for InvoiceUpdate { fn from(request: InvoiceUpdateRequest) -> Self { let now = common_utils::date_time::now(); match request { InvoiceUpdateRequest::Amount(update) => Self { status: None, payment_method_id: None, connector_invoice_id: None, modified_at: now, payment_intent_id: None, amount: Some(update.amount), currency: Some(update.currency), }, InvoiceUpdateRequest::Connector(update) => Self { status: Some(update.status), payment_method_id: None, connector_invoice_id: Some(update.connector_invoice_id), modified_at: now, payment_intent_id: None, amount: None, currency: None, }, InvoiceUpdateRequest::PaymentStatus(update) => Self { status: Some(update.status), payment_method_id: update .payment_method_id .as_ref() .map(|id| id.peek()) .cloned(), connector_invoice_id: update.connector_invoice_id, modified_at: now, payment_intent_id: update.payment_intent_id, amount: None, currency: None, }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for InvoiceUpdate { type DstType = diesel_models::invoice::InvoiceUpdate; type NewDstType = diesel_models::invoice::InvoiceUpdate; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::invoice::InvoiceUpdate { status: self.status, payment_method_id: self.payment_method_id, connector_invoice_id: self.connector_invoice_id, modified_at: self.modified_at, payment_intent_id: self.payment_intent_id, amount: self.amount, currency: self.currency, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { status: item.status, payment_method_id: item.payment_method_id, connector_invoice_id: item.connector_invoice_id, modified_at: item.modified_at, payment_intent_id: item.payment_intent_id, amount: item.amount, currency: item.currency, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::invoice::InvoiceUpdate { status: self.status, payment_method_id: self.payment_method_id, connector_invoice_id: self.connector_invoice_id, modified_at: self.modified_at, payment_intent_id: self.payment_intent_id, amount: self.amount, currency: self.currency, }) } } impl InvoiceUpdate { pub fn new( payment_method_id: Option<String>, status: Option<common_enums::connector_enums::InvoiceStatus>, connector_invoice_id: Option<common_utils::id_type::InvoiceId>, payment_intent_id: Option<common_utils::id_type::PaymentId>, amount: Option<MinorUnit>, currency: Option<String>, ) -> Self { Self { status, payment_method_id, connector_invoice_id, modified_at: common_utils::date_time::now(), payment_intent_id, amount, currency, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/invoice.rs", "file_size": 12592, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-4106817757083272893
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/bulk_tokenization.rs // File size: 12446 bytes use api_models::{payment_methods as payment_methods_api, payments as payments_api}; use cards::CardNumber; use common_enums as enums; use common_utils::{ errors, ext_traits::OptionExt, id_type, pii, transformers::{ForeignFrom, ForeignTryFrom}, }; use error_stack::report; use crate::{ address::{Address, AddressDetails, PhoneDetails}, router_request_types::CustomerDetails, }; #[derive(Debug)] pub struct CardNetworkTokenizeRequest { pub data: TokenizeDataRequest, pub customer: CustomerDetails, pub billing: Option<Address>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_issuer: Option<String>, } #[derive(Debug)] pub enum TokenizeDataRequest { Card(TokenizeCardRequest), ExistingPaymentMethod(TokenizePaymentMethodRequest), } #[derive(Clone, Debug)] pub struct TokenizeCardRequest { pub raw_card_number: CardNumber, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_cvc: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_issuing_country: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_issuer: Option<String>, pub card_type: Option<payment_methods_api::CardType>, } #[derive(Clone, Debug)] pub struct TokenizePaymentMethodRequest { pub payment_method_id: String, pub card_cvc: Option<masking::Secret<String>>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct CardNetworkTokenizeRecord { // Card details pub raw_card_number: Option<CardNumber>, pub card_expiry_month: Option<masking::Secret<String>>, pub card_expiry_year: Option<masking::Secret<String>>, pub card_cvc: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_issuing_country: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_issuer: Option<String>, pub card_type: Option<payment_methods_api::CardType>, // Payment method details pub payment_method_id: Option<String>, pub payment_method_type: Option<payment_methods_api::CardType>, pub payment_method_issuer: Option<String>, // Customer details pub customer_id: id_type::CustomerId, #[serde(rename = "name")] pub customer_name: Option<masking::Secret<String>>, #[serde(rename = "email")] pub customer_email: Option<pii::Email>, #[serde(rename = "phone")] pub customer_phone: Option<masking::Secret<String>>, #[serde(rename = "phone_country_code")] pub customer_phone_country_code: Option<String>, #[serde(rename = "tax_registration_id")] pub customer_tax_registration_id: Option<masking::Secret<String>>, // Billing details pub billing_address_city: Option<String>, pub billing_address_country: Option<enums::CountryAlpha2>, pub billing_address_line1: Option<masking::Secret<String>>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub billing_address_zip: Option<masking::Secret<String>>, pub billing_address_state: Option<masking::Secret<String>>, pub billing_address_first_name: Option<masking::Secret<String>>, pub billing_address_last_name: Option<masking::Secret<String>>, pub billing_phone_number: Option<masking::Secret<String>>, pub billing_phone_country_code: Option<String>, pub billing_email: Option<pii::Email>, // Other details pub line_number: Option<u64>, pub merchant_id: Option<id_type::MerchantId>, } impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails { fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { Self { id: record.customer_id.clone(), name: record.customer_name.clone(), email: record.customer_email.clone(), phone: record.customer_phone.clone(), phone_country_code: record.customer_phone_country_code.clone(), tax_registration_id: record.customer_tax_registration_id.clone(), } } } impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address { fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { Self { address: Some(payments_api::AddressDetails { first_name: record.billing_address_first_name.clone(), last_name: record.billing_address_last_name.clone(), line1: record.billing_address_line1.clone(), line2: record.billing_address_line2.clone(), line3: record.billing_address_line3.clone(), city: record.billing_address_city.clone(), zip: record.billing_address_zip.clone(), state: record.billing_address_state.clone(), country: record.billing_address_country, origin_zip: None, }), phone: Some(payments_api::PhoneDetails { number: record.billing_phone_number.clone(), country_code: record.billing_phone_country_code.clone(), }), email: record.billing_email.clone(), } } } impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> { let billing = Some(payments_api::Address::foreign_from(&record)); let customer = payments_api::CustomerDetails::foreign_from(&record); let merchant_id = record.merchant_id.get_required_value("merchant_id")?; match ( record.raw_card_number, record.card_expiry_month, record.card_expiry_year, record.payment_method_id, ) { (Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => { Ok(Self { merchant_id, data: payment_methods_api::TokenizeDataRequest::Card( payment_methods_api::TokenizeCardRequest { raw_card_number, card_expiry_month, card_expiry_year, card_cvc: record.card_cvc, card_holder_name: record.card_holder_name, nick_name: record.nick_name, card_issuing_country: record.card_issuing_country, card_network: record.card_network, card_issuer: record.card_issuer, card_type: record.card_type.clone(), }, ), billing, customer, metadata: None, payment_method_issuer: record.payment_method_issuer, }) } (None, None, None, Some(payment_method_id)) => Ok(Self { merchant_id, data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod( payment_methods_api::TokenizePaymentMethodRequest { payment_method_id, card_cvc: record.card_cvc, }, ), billing, customer, metadata: None, payment_method_issuer: record.payment_method_issuer, }), _ => Err(report!(errors::ValidationError::InvalidValue { message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string() })), } } } impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail { fn foreign_from(card: &TokenizeCardRequest) -> Self { Self { card_number: masking::Secret::new(card.raw_card_number.get_card_no()), card_exp_month: card.card_expiry_month.clone(), card_exp_year: card.card_expiry_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), card_issuing_country: card.card_issuing_country.clone(), card_network: card.card_network.clone(), card_issuer: card.card_issuer.clone(), card_type: card .card_type .as_ref() .map(|card_type| card_type.to_string()), } } } impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> { Ok(Self { id: customer.customer_id.get_required_value("customer_id")?, name: customer.name, email: customer.email, phone: customer.phone, phone_country_code: customer.phone_country_code, tax_registration_id: customer.tax_registration_id, }) } } impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest { fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self { Self { data: TokenizeDataRequest::foreign_from(req.data), customer: CustomerDetails::foreign_from(req.customer), billing: req.billing.map(ForeignFrom::foreign_from), metadata: req.metadata, payment_method_issuer: req.payment_method_issuer, } } } impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest { fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self { match req { payment_methods_api::TokenizeDataRequest::Card(card) => { Self::Card(TokenizeCardRequest { raw_card_number: card.raw_card_number, card_expiry_month: card.card_expiry_month, card_expiry_year: card.card_expiry_year, card_cvc: card.card_cvc, card_holder_name: card.card_holder_name, nick_name: card.nick_name, card_issuing_country: card.card_issuing_country, card_network: card.card_network, card_issuer: card.card_issuer, card_type: card.card_type, }) } payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => { Self::ExistingPaymentMethod(TokenizePaymentMethodRequest { payment_method_id: pm.payment_method_id, card_cvc: pm.card_cvc, }) } } } } impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails { fn foreign_from(req: payments_api::CustomerDetails) -> Self { Self { customer_id: Some(req.id), name: req.name, email: req.email, phone: req.phone, phone_country_code: req.phone_country_code, tax_registration_id: req.tax_registration_id, } } } impl ForeignFrom<payments_api::Address> for Address { fn foreign_from(req: payments_api::Address) -> Self { Self { address: req.address.map(ForeignFrom::foreign_from), phone: req.phone.map(ForeignFrom::foreign_from), email: req.email, } } } impl ForeignFrom<payments_api::AddressDetails> for AddressDetails { fn foreign_from(req: payments_api::AddressDetails) -> Self { Self { city: req.city, country: req.country, line1: req.line1, line2: req.line2, line3: req.line3, zip: req.zip, state: req.state, first_name: req.first_name, last_name: req.last_name, origin_zip: req.origin_zip, } } } impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails { fn foreign_from(req: payments_api::PhoneDetails) -> Self { Self { number: req.number, country_code: req.country_code, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/bulk_tokenization.rs", "file_size": 12446, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-2597158958520288136
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/relay.rs // File size: 10440 bytes use common_enums::enums; use common_utils::{ self, errors::{CustomResult, ValidationError}, id_type::{self, GenerateId}, pii, types::{keymanager, MinorUnit}, }; use diesel_models::relay::RelayUpdateInternal; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{router_data::ErrorResponse, router_response_types}; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Relay { pub id: id_type::RelayId, pub connector_resource_id: String, pub connector_id: id_type::MerchantConnectorAccountId, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub relay_type: enums::RelayType, pub request_data: Option<RelayData>, pub status: enums::RelayStatus, pub connector_reference_id: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub response_data: Option<pii::SecretSerdeValue>, } impl Relay { pub fn new( relay_request: &api_models::relay::RelayRequest, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> Self { let relay_id = id_type::RelayId::generate(); Self { id: relay_id.clone(), connector_resource_id: relay_request.connector_resource_id.clone(), connector_id: relay_request.connector_id.clone(), profile_id: profile_id.clone(), merchant_id: merchant_id.clone(), relay_type: common_enums::RelayType::Refund, request_data: relay_request.data.clone().map(From::from), status: common_enums::RelayStatus::Created, connector_reference_id: None, error_code: None, error_message: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), response_data: None, } } } impl From<api_models::relay::RelayData> for RelayData { fn from(relay: api_models::relay::RelayData) -> Self { match relay { api_models::relay::RelayData::Refund(relay_refund_request) => { Self::Refund(RelayRefundData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } } } } impl From<api_models::relay::RelayRefundRequestData> for RelayRefundData { fn from(relay: api_models::relay::RelayRefundRequestData) -> Self { Self { amount: relay.amount, currency: relay.currency, reason: relay.reason, } } } impl RelayUpdate { pub fn from( response: Result<router_response_types::RefundsResponseData, ErrorResponse>, ) -> Self { match response { Err(error) => Self::ErrorUpdate { error_code: error.code, error_message: error.reason.unwrap_or(error.message), status: common_enums::RelayStatus::Failure, }, Ok(response) => Self::StatusUpdate { connector_reference_id: Some(response.connector_refund_id), status: common_enums::RelayStatus::from(response.refund_status), }, } } } impl From<RelayData> for api_models::relay::RelayData { fn from(relay: RelayData) -> Self { match relay { RelayData::Refund(relay_refund_request) => { Self::Refund(api_models::relay::RelayRefundRequestData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } } } } impl From<Relay> for api_models::relay::RelayResponse { fn from(value: Relay) -> Self { let error = value .error_code .zip(value.error_message) .map( |(error_code, error_message)| api_models::relay::RelayError { code: error_code, message: error_message, }, ); let data = value.request_data.map(|relay_data| match relay_data { RelayData::Refund(relay_refund_request) => { api_models::relay::RelayData::Refund(api_models::relay::RelayRefundRequestData { amount: relay_refund_request.amount, currency: relay_refund_request.currency, reason: relay_refund_request.reason, }) } }); Self { id: value.id, status: value.status, error, connector_resource_id: value.connector_resource_id, connector_id: value.connector_id, profile_id: value.profile_id, relay_type: value.relay_type, data, connector_reference_id: value.connector_reference_id, } } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case", untagged)] pub enum RelayData { Refund(RelayRefundData), } #[derive(Debug, Clone, Deserialize, Serialize)] pub struct RelayRefundData { pub amount: MinorUnit, pub currency: enums::Currency, pub reason: Option<String>, } #[derive(Debug)] pub enum RelayUpdate { ErrorUpdate { error_code: String, error_message: String, status: enums::RelayStatus, }, StatusUpdate { connector_reference_id: Option<String>, status: common_enums::RelayStatus, }, } impl From<RelayUpdate> for RelayUpdateInternal { fn from(value: RelayUpdate) -> Self { match value { RelayUpdate::ErrorUpdate { error_code, error_message, status, } => Self { error_code: Some(error_code), error_message: Some(error_message), connector_reference_id: None, status: Some(status), modified_at: common_utils::date_time::now(), }, RelayUpdate::StatusUpdate { connector_reference_id, status, } => Self { connector_reference_id, status: Some(status), error_code: None, error_message: None, modified_at: common_utils::date_time::now(), }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for Relay { type DstType = diesel_models::relay::Relay; type NewDstType = diesel_models::relay::RelayNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::relay::Relay { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } async fn convert_back( _state: &keymanager::KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> { Ok(Self { id: item.id, connector_resource_id: item.connector_resource_id, connector_id: item.connector_id, profile_id: item.profile_id, merchant_id: item.merchant_id, relay_type: enums::RelayType::Refund, request_data: item .request_data .map(|data| { serde_json::from_value(data.expose()).change_context( ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }, ) }) .transpose()?, status: item.status, connector_reference_id: item.connector_reference_id, error_code: item.error_code, error_message: item.error_message, created_at: item.created_at, modified_at: item.modified_at, response_data: item.response_data, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::relay::RelayNew { id: self.id, connector_resource_id: self.connector_resource_id, connector_id: self.connector_id, profile_id: self.profile_id, merchant_id: self.merchant_id, relay_type: self.relay_type, request_data: self .request_data .map(|data| { serde_json::to_value(data).change_context(ValidationError::InvalidValue { message: "Failed while decrypting business profile data".to_string(), }) }) .transpose()? .map(Secret::new), status: self.status, connector_reference_id: self.connector_reference_id, error_code: self.error_code, error_message: self.error_message, created_at: self.created_at, modified_at: self.modified_at, response_data: self.response_data, }) } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/relay.rs", "file_size": 10440, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-1415057300689413599
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/types.rs // File size: 10100 bytes pub use diesel_models::types::OrderDetailsWithAmount; use crate::{ router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData}, router_data_v2::{self, RouterDataV2}, router_flow_types::{ mandate_revoke::MandateRevoke, revenue_recovery::InvoiceRecordBack, subscriptions::{ GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans, SubscriptionCreate, }, AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation, Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, Execute, ExtendAuthorization, ExternalVaultProxy, GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing, RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, subscriptions::{ GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest, GetSubscriptionPlansRequest, SubscriptionCreateRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData, ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, subscriptions::{ GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse, GetSubscriptionPlansResponse, SubscriptionCreateResponse, }, GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, VaultResponseData, VerifyWebhookSourceResponseData, }, }; #[cfg(feature = "payouts")] pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData}; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPreAuthenticateRouterData = RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>; pub type PaymentsAuthenticateRouterData = RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>; pub type PaymentsPostAuthenticateRouterData = RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type AccessTokenAuthenticationRouterData = RouterData< AccessTokenAuthentication, AccessTokenAuthenticationRequestData, AccessTokenAuthenticationResponse, >; pub type PaymentsGiftCardBalanceCheckRouterData = RouterData< GiftCardBalanceCheck, GiftCardBalanceCheckRequestData, GiftCardBalanceCheckResponseData, >; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type UasPostAuthenticationRouterData = RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasPreAuthenticationRouterData = RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>; pub type UasAuthenticationConfirmationRouterData = RouterData< AuthenticationConfirmation, UasConfirmationRequestData, UasAuthenticationResponseData, >; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; pub type InvoiceRecordBackRouterData = RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>; pub type GetSubscriptionPlansRouterData = RouterData<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>; pub type GetSubscriptionEstimateRouterData = RouterData< GetSubscriptionEstimate, GetSubscriptionEstimateRequest, GetSubscriptionEstimateResponse, >; pub type UasAuthenticationRouterData = RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>; pub type BillingConnectorPaymentsSyncRouterData = RouterData< BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterData = RouterData< BillingConnectorInvoiceSync, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorInvoiceSyncRouterDataV2 = RouterDataV2< BillingConnectorInvoiceSync, router_data_v2::flow_common_types::BillingConnectorInvoiceSyncFlowData, BillingConnectorInvoiceSyncRequest, BillingConnectorInvoiceSyncResponse, >; pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2< BillingConnectorPaymentsSync, router_data_v2::flow_common_types::BillingConnectorPaymentsSyncFlowData, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse, >; pub type InvoiceRecordBackRouterDataV2 = RouterDataV2< InvoiceRecordBack, router_data_v2::flow_common_types::InvoiceRecordBackData, InvoiceRecordBackRequest, InvoiceRecordBackResponse, >; pub type GetSubscriptionPlanPricesRouterData = RouterData< GetSubscriptionPlanPrices, GetSubscriptionPlanPricesRequest, GetSubscriptionPlanPricesResponse, >; pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>; pub type VaultRouterDataV2<F> = RouterDataV2< F, router_data_v2::flow_common_types::VaultConnectorFlowData, VaultRequestData, VaultResponseData, >; pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2< ExternalVaultProxy, router_data_v2::flow_common_types::ExternalVaultProxyFlowData, ExternalVaultProxyPaymentsData, PaymentsResponseData, >; pub type SubscriptionCreateRouterData = RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>;
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/types.rs", "file_size": 10100, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_2744224804307599317
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/subscription.rs // File size: 9869 bytes use common_utils::{ errors::{CustomResult, ValidationError}, events::ApiEventMetric, generate_id_with_default_len, pii::SecretSerdeValue, types::keymanager::{self, KeyManagerState}, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; use time::PrimitiveDateTime; use crate::{errors::api_error_response::ApiErrorResponse, merchant_key_store::MerchantKeyStore}; const SECRET_SPLIT: &str = "_secret"; #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ClientSecret(String); impl ClientSecret { pub fn new(secret: String) -> Self { Self(secret) } pub fn get_subscription_id(&self) -> error_stack::Result<String, ApiErrorResponse> { let sub_id = self .0 .split(SECRET_SPLIT) .next() .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "client_secret", }) .attach_printable("Failed to extract subscription_id from client_secret")?; Ok(sub_id.to_string()) } } impl std::fmt::Display for ClientSecret { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl ApiEventMetric for ClientSecret {} impl From<api_models::subscription::ClientSecret> for ClientSecret { fn from(api_secret: api_models::subscription::ClientSecret) -> Self { Self::new(api_secret.as_str().to_string()) } } impl From<ClientSecret> for api_models::subscription::ClientSecret { fn from(domain_secret: ClientSecret) -> Self { Self::new(domain_secret.to_string()) } } #[derive(Clone, Debug, serde::Serialize)] pub struct Subscription { pub id: common_utils::id_type::SubscriptionId, pub status: String, pub billing_processor: Option<String>, pub payment_method_id: Option<String>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub client_secret: Option<String>, pub connector_subscription_id: Option<String>, pub merchant_id: common_utils::id_type::MerchantId, pub customer_id: common_utils::id_type::CustomerId, pub metadata: Option<SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub modified_at: PrimitiveDateTime, pub profile_id: common_utils::id_type::ProfileId, pub merchant_reference_id: Option<String>, pub plan_id: Option<String>, pub item_price_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize)] pub enum SubscriptionStatus { Active, Created, InActive, Pending, Trial, Paused, Unpaid, Onetime, Cancelled, Failed, } impl std::fmt::Display for SubscriptionStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Active => write!(f, "Active"), Self::Created => write!(f, "Created"), Self::InActive => write!(f, "InActive"), Self::Pending => write!(f, "Pending"), Self::Trial => write!(f, "Trial"), Self::Paused => write!(f, "Paused"), Self::Unpaid => write!(f, "Unpaid"), Self::Onetime => write!(f, "Onetime"), Self::Cancelled => write!(f, "Cancelled"), Self::Failed => write!(f, "Failed"), } } } impl Subscription { pub fn generate_and_set_client_secret(&mut self) -> Secret<String> { let client_secret = generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr())); self.client_secret = Some(client_secret.clone()); Secret::new(client_secret) } } #[async_trait::async_trait] impl super::behaviour::Conversion for Subscription { type DstType = diesel_models::subscription::Subscription; type NewDstType = diesel_models::subscription::SubscriptionNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let now = common_utils::date_time::now(); Ok(diesel_models::subscription::Subscription { id: self.id, status: self.status, billing_processor: self.billing_processor, payment_method_id: self.payment_method_id, merchant_connector_id: self.merchant_connector_id, client_secret: self.client_secret, connector_subscription_id: self.connector_subscription_id, merchant_id: self.merchant_id, customer_id: self.customer_id, metadata: self.metadata.map(|m| m.expose()), created_at: now, modified_at: now, profile_id: self.profile_id, merchant_reference_id: self.merchant_reference_id, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { id: item.id, status: item.status, billing_processor: item.billing_processor, payment_method_id: item.payment_method_id, merchant_connector_id: item.merchant_connector_id, client_secret: item.client_secret, connector_subscription_id: item.connector_subscription_id, merchant_id: item.merchant_id, customer_id: item.customer_id, metadata: item.metadata.map(SecretSerdeValue::new), created_at: item.created_at, modified_at: item.modified_at, profile_id: item.profile_id, merchant_reference_id: item.merchant_reference_id, plan_id: item.plan_id, item_price_id: item.item_price_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionNew::new( self.id, self.status, self.billing_processor, self.payment_method_id, self.merchant_connector_id, self.client_secret, self.connector_subscription_id, self.merchant_id, self.customer_id, self.metadata, self.profile_id, self.merchant_reference_id, self.plan_id, self.item_price_id, )) } } #[async_trait::async_trait] pub trait SubscriptionInterface { type Error; async fn insert_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, subscription_new: Subscription, ) -> CustomResult<Subscription, Self::Error>; async fn find_by_merchant_id_subscription_id( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, ) -> CustomResult<Subscription, Self::Error>; async fn update_subscription_entry( &self, state: &KeyManagerState, key_store: &MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, subscription_id: String, data: SubscriptionUpdate, ) -> CustomResult<Subscription, Self::Error>; } pub struct SubscriptionUpdate { pub connector_subscription_id: Option<String>, pub payment_method_id: Option<String>, pub status: Option<String>, pub modified_at: PrimitiveDateTime, pub plan_id: Option<String>, pub item_price_id: Option<String>, } impl SubscriptionUpdate { pub fn new( connector_subscription_id: Option<String>, payment_method_id: Option<Secret<String>>, status: Option<String>, plan_id: Option<String>, item_price_id: Option<String>, ) -> Self { Self { connector_subscription_id, payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()), status, modified_at: common_utils::date_time::now(), plan_id, item_price_id, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for SubscriptionUpdate { type DstType = diesel_models::subscription::SubscriptionUpdate; type NewDstType = diesel_models::subscription::SubscriptionUpdate; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionUpdate { connector_subscription_id: self.connector_subscription_id, payment_method_id: self.payment_method_id, status: self.status, modified_at: self.modified_at, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } async fn convert_back( _state: &KeyManagerState, item: Self::DstType, _key: &Secret<Vec<u8>>, _key_manager_identifier: keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { Ok(Self { connector_subscription_id: item.connector_subscription_id, payment_method_id: item.payment_method_id, status: item.status, modified_at: item.modified_at, plan_id: item.plan_id, item_price_id: item.item_price_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::subscription::SubscriptionUpdate { connector_subscription_id: self.connector_subscription_id, payment_method_id: self.payment_method_id, status: self.status, modified_at: self.modified_at, plan_id: self.plan_id, item_price_id: self.item_price_id, }) } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/subscription.rs", "file_size": 9869, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-7214889085368462814
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/payouts/payouts.rs // File size: 8964 bytes use common_enums as storage_enums; use common_utils::{id_type, pii, types::MinorUnit}; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; use super::payout_attempt::PayoutAttempt; #[cfg(feature = "olap")] use super::PayoutFetchConstraints; #[async_trait::async_trait] pub trait PayoutsInterface { type Error; async fn insert_payout( &self, _payout: PayoutsNew, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn update_payout( &self, _this: &Payouts, _payout: PayoutsUpdate, _payout_attempt: &PayoutAttempt, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Payouts, Self::Error>; async fn find_optional_payout_by_merchant_id_payout_id( &self, _merchant_id: &id_type::MerchantId, _payout_id: &id_type::PayoutId, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Option<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, _merchant_id: &id_type::MerchantId, _filters: &PayoutFetchConstraints, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result< Vec<( Payouts, PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, Self::Error, >; #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &id_type::MerchantId, _time_range: &common_utils::types::TimeRange, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, Self::Error>; #[cfg(feature = "olap")] #[allow(clippy::too_many_arguments)] async fn get_total_count_of_filtered_payouts( &self, _merchant_id: &id_type::MerchantId, _active_payout_ids: &[id_type::PayoutId], _connector: Option<Vec<api_models::enums::PayoutConnectors>>, _currency: Option<Vec<storage_enums::Currency>>, _status: Option<Vec<storage_enums::PayoutStatus>>, _payout_method: Option<Vec<storage_enums::PayoutType>>, ) -> error_stack::Result<i64, Self::Error>; #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, _merchant_id: &id_type::MerchantId, _constraints: &PayoutFetchConstraints, ) -> error_stack::Result<Vec<id_type::PayoutId>, Self::Error>; } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Payouts { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct PayoutsNew { pub payout_id: id_type::PayoutId, pub merchant_id: id_type::MerchantId, pub customer_id: Option<id_type::CustomerId>, pub address_id: Option<String>, pub payout_type: Option<storage_enums::PayoutType>, pub payout_method_id: Option<String>, pub amount: MinorUnit, pub destination_currency: storage_enums::Currency, pub source_currency: storage_enums::Currency, pub description: Option<String>, pub recurring: bool, pub auto_fulfill: bool, pub return_url: Option<String>, pub entity_type: storage_enums::PayoutEntityType, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, pub attempt_count: i16, pub profile_id: id_type::ProfileId, pub status: storage_enums::PayoutStatus, pub confirm: Option<bool>, pub payout_link_id: Option<String>, pub client_secret: Option<String>, pub priority: Option<storage_enums::PayoutSendPriority>, } #[derive(Debug, Serialize, Deserialize)] pub enum PayoutsUpdate { Update { amount: MinorUnit, destination_currency: storage_enums::Currency, source_currency: storage_enums::Currency, description: Option<String>, recurring: bool, auto_fulfill: bool, return_url: Option<String>, entity_type: storage_enums::PayoutEntityType, metadata: Option<pii::SecretSerdeValue>, profile_id: Option<id_type::ProfileId>, status: Option<storage_enums::PayoutStatus>, confirm: Option<bool>, payout_type: Option<storage_enums::PayoutType>, address_id: Option<String>, customer_id: Option<id_type::CustomerId>, }, PayoutMethodIdUpdate { payout_method_id: String, }, RecurringUpdate { recurring: bool, }, AttemptCountUpdate { attempt_count: i16, }, StatusUpdate { status: storage_enums::PayoutStatus, }, } #[derive(Clone, Debug, Default)] pub struct PayoutsUpdateInternal { pub amount: Option<MinorUnit>, pub destination_currency: Option<storage_enums::Currency>, pub source_currency: Option<storage_enums::Currency>, pub description: Option<String>, pub recurring: Option<bool>, pub auto_fulfill: Option<bool>, pub return_url: Option<String>, pub entity_type: Option<storage_enums::PayoutEntityType>, pub metadata: Option<pii::SecretSerdeValue>, pub payout_method_id: Option<String>, pub profile_id: Option<id_type::ProfileId>, pub status: Option<storage_enums::PayoutStatus>, pub attempt_count: Option<i16>, pub confirm: Option<bool>, pub payout_type: Option<common_enums::PayoutType>, pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, } impl From<PayoutsUpdate> for PayoutsUpdateInternal { 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() }, } } }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/payouts/payouts.rs", "file_size": 8964, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_hyperswitch_domain_models_-6235428715713616719
clm
file
// Repository: hyperswitch // Crate: hyperswitch_domain_models // File: crates/hyperswitch_domain_models/src/connector_endpoints.rs // File size: 8818 bytes //! Configs interface use common_enums::{connector_enums, ApplicationError}; use common_utils::errors::CustomResult; use masking::Secret; use router_derive; use serde::Deserialize; use crate::errors::api_error_response; // struct Connectors #[allow(missing_docs, missing_debug_implementations)] #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct Connectors { pub aci: ConnectorParams, pub authipay: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub affirm: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub archipel: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub barclaycard: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub blackhawknetwork: ConnectorParams, pub calida: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub breadpay: ConnectorParams, pub cashtocode: ConnectorParams, pub celero: ConnectorParams, pub chargebee: ConnectorParams, pub checkbook: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub custombilling: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub dwolla: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub finix: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub flexiti: ConnectorParams, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub gigadat: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub hyperswitch_vault: ConnectorParams, pub hyperwallet: ConnectorParams, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub cardinal: NoParams, pub katapult: ConnectorParams, pub klarna: ConnectorParams, pub loonio: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub mpgs: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub nordea: ConnectorParams, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payload: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paysafe: ConnectorParams, pub paystack: ConnectorParams, pub paytm: ConnectorParams, pub payu: ConnectorParams, pub peachpayments: ConnectorParams, pub phonepe: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub santander: ConnectorParams, pub shift4: ConnectorParams, pub sift: ConnectorParams, pub silverflow: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub tesouro: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub tokenex: ConnectorParams, pub tokenio: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub trustpayments: ConnectorParams, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub vgs: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub worldpayvantiv: ConnectorParamsWithThreeUrls, pub worldpayxml: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, } impl Connectors { pub fn get_connector_params( &self, connector: connector_enums::Connector, ) -> CustomResult<ConnectorParams, api_error_response::ApiErrorResponse> { match connector { connector_enums::Connector::Recurly => Ok(self.recurly.clone()), connector_enums::Connector::Stripebilling => Ok(self.stripebilling.clone()), connector_enums::Connector::Chargebee => Ok(self.chargebee.clone()), _ => Err(api_error_response::ApiErrorResponse::IncorrectConnectorNameGiven.into()), } } } /// struct ConnectorParams #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParams { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, } ///struct No Param for connectors with no params #[derive(Debug, Deserialize, Clone, Default)] pub struct NoParams; impl NoParams { /// function to satisfy connector param validation macro pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> { Ok(()) } } /// struct ConnectorParamsWithKeys #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithKeys { /// base url pub base_url: String, /// api key pub api_key: Secret<String>, /// merchant ID pub merchant_id: Secret<String>, } /// struct ConnectorParamsWithModeType #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithModeType { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: Option<String>, /// Can take values like Test or Live for Noon pub key_mode: String, } /// struct ConnectorParamsWithMoreUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithMoreUrls { /// base url pub base_url: String, /// base url for bank redirects pub base_url_bank_redirects: String, } /// struct ConnectorParamsWithFileUploadUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithFileUploadUrl { /// base url pub base_url: String, /// base url for file upload pub base_url_file_upload: String, } /// struct ConnectorParamsWithThreeBaseUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct AdyenParamsWithThreeBaseUrls { /// base url pub base_url: String, /// secondary base url #[cfg(feature = "payouts")] pub payout_base_url: String, /// third base url pub dispute_base_url: String, } /// struct ConnectorParamsWithSecondaryBaseUrl #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithSecondaryBaseUrl { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, } /// struct ConnectorParamsWithThreeUrls #[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)] #[serde(default)] pub struct ConnectorParamsWithThreeUrls { /// base url pub base_url: String, /// secondary base url pub secondary_base_url: String, /// third base url pub third_base_url: String, }
{ "crate": "hyperswitch_domain_models", "file": "crates/hyperswitch_domain_models/src/connector_endpoints.rs", "file_size": 8818, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-7391380729044586041
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types/transformers.rs // File size: 96624 bytes use actix_web::http::header::HeaderMap; use api_models::{ cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods, payments, routing::ConnectorSelection, }; use common_utils::{ consts::X_HS_LATENCY, crypto::Encryptable, ext_traits::{Encode, StringExt, ValueExt}, fp_utils::when, pii, types::ConnectorTransactionIdTrait, }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::payments::payment_intent::CustomerData; use masking::{ExposeInterface, PeekInterface, Secret}; use super::domain; #[cfg(feature = "v2")] use crate::db::storage::revenue_recovery_redis_operation; use crate::{ core::errors, headers::{ ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI, X_REFERENCE_ID, }, services::authentication::get_header_value_by_key, types::{ self as router_types, api::{self as api_types, routing as routing_types}, storage, }, }; pub trait ForeignInto<T> { fn foreign_into(self) -> T; } pub trait ForeignTryInto<T> { type Error; fn foreign_try_into(self) -> Result<T, Self::Error>; } pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } pub trait ForeignTryFrom<F>: Sized { type Error; fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } impl<F, T> ForeignInto<T> for F where T: ForeignFrom<F>, { fn foreign_into(self) -> T { T::foreign_from(self) } } impl<F, T> ForeignTryInto<T> for F where T: ForeignTryFrom<F>, { type Error = <T as ForeignTryFrom<F>>::Error; fn foreign_try_into(self) -> Result<T, Self::Error> { T::foreign_try_from(self) } } impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType { fn foreign_from(item: api_models::refunds::RefundType) -> Self { match item { api_models::refunds::RefundType::Instant => Self::InstantRefund, api_models::refunds::RefundType::Scheduled => Self::RegularRefund, } } } #[cfg(feature = "v1")] impl ForeignFrom<( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, )> for payment_methods::PaymentMethodResponse { fn foreign_from( (card_details, item): ( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, ), ) -> Self { Self { merchant_id: item.merchant_id.to_owned(), customer_id: Some(item.customer_id.to_owned()), payment_method_id: item.get_id().clone(), payment_method: item.get_payment_method_type(), payment_method_type: item.get_payment_method_subtype(), card: card_details, recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: None, metadata: item.metadata, created: Some(item.created_at), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: None, client_secret: item.client_secret, } } } #[cfg(feature = "v2")] impl ForeignFrom<( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, )> for payment_methods::PaymentMethodResponse { fn foreign_from( (card_details, item): ( Option<payment_methods::CardDetailFromLocker>, domain::PaymentMethod, ), ) -> Self { todo!() } } // TODO: remove this usage in v1 code impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus { fn foreign_from(s: storage_enums::AttemptStatus) -> Self { Self::from(s) } } impl ForeignTryFrom<storage_enums::AttemptStatus> for storage_enums::CaptureStatus { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( attempt_status: storage_enums::AttemptStatus, ) -> errors::RouterResult<Self> { match attempt_status { storage_enums::AttemptStatus::Charged | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::IntegrityFailure => Ok(Self::Charged), storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::CaptureInitiated => Ok(Self::Pending), storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::CaptureFailed => Ok(Self::Failed), storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::VoidedPostCharge | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::AutoRefunded | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending | storage_enums::AttemptStatus::PartiallyAuthorized | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Expired => { Err(errors::ApiErrorResponse::PreconditionFailed { message: "AttemptStatus must be one of these for multiple partial captures [Charged, PartialCharged, Pending, CaptureInitiated, Failure, CaptureFailed]".into(), }.into()) } } } } impl ForeignFrom<payments::MandateType> for storage_enums::MandateDataType { fn foreign_from(from: payments::MandateType) -> Self { match from { payments::MandateType::SingleUse(inner) => Self::SingleUse(inner.foreign_into()), payments::MandateType::MultiUse(inner) => { Self::MultiUse(inner.map(ForeignInto::foreign_into)) } } } } impl ForeignFrom<storage_enums::MandateDataType> for payments::MandateType { fn foreign_from(from: storage_enums::MandateDataType) -> Self { match from { storage_enums::MandateDataType::SingleUse(inner) => { Self::SingleUse(inner.foreign_into()) } storage_enums::MandateDataType::MultiUse(inner) => { Self::MultiUse(inner.map(ForeignInto::foreign_into)) } } } } impl ForeignFrom<storage_enums::MandateAmountData> for payments::MandateAmountData { fn foreign_from(from: storage_enums::MandateAmountData) -> Self { Self { amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, metadata: from.metadata, } } } // TODO: remove foreign from since this conversion won't be needed in the router crate once data models is treated as a single & primary source of truth for structure information impl ForeignFrom<payments::MandateData> for hyperswitch_domain_models::mandates::MandateData { fn foreign_from(d: payments::MandateData) -> Self { Self { customer_acceptance: d.customer_acceptance, mandate_type: d.mandate_type.map(|d| match d { payments::MandateType::MultiUse(Some(i)) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }, )) } payments::MandateType::SingleUse(i) => { hyperswitch_domain_models::mandates::MandateDataType::SingleUse( hyperswitch_domain_models::mandates::MandateAmountData { amount: i.amount, currency: i.currency, start_date: i.start_date, end_date: i.end_date, metadata: i.metadata, }, ) } payments::MandateType::MultiUse(None) => { hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) } }), update_mandate_id: d.update_mandate_id, } } } impl ForeignFrom<payments::MandateAmountData> for storage_enums::MandateAmountData { fn foreign_from(from: payments::MandateAmountData) -> Self { Self { amount: from.amount, currency: from.currency, start_date: from.start_date, end_date: from.end_date, metadata: from.metadata, } } } impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { fn foreign_from(payment_method_type: api_enums::PaymentMethodType) -> Self { match payment_method_type { api_enums::PaymentMethodType::AmazonPay | api_enums::PaymentMethodType::Paysera | api_enums::PaymentMethodType::Skrill | api_enums::PaymentMethodType::ApplePay | api_enums::PaymentMethodType::GooglePay | api_enums::PaymentMethodType::Paypal | api_enums::PaymentMethodType::AliPay | api_enums::PaymentMethodType::AliPayHk | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps | api_enums::PaymentMethodType::TouchNGo | api_enums::PaymentMethodType::Swish | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::Momo | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Venmo | api_enums::PaymentMethodType::Mifinity | api_enums::PaymentMethodType::RevolutPay | api_enums::PaymentMethodType::Bluecode => Self::Wallet, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay | api_enums::PaymentMethodType::Klarna | api_enums::PaymentMethodType::Flexiti | api_enums::PaymentMethodType::PayBright | api_enums::PaymentMethodType::Atome | api_enums::PaymentMethodType::Walley | api_enums::PaymentMethodType::Breadpay => Self::PayLater, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik | api_enums::PaymentMethodType::LocalBankRedirect | api_enums::PaymentMethodType::OnlineBankingThailand | api_enums::PaymentMethodType::OnlineBankingCzechRepublic | api_enums::PaymentMethodType::OnlineBankingFinland | api_enums::PaymentMethodType::OnlineBankingFpx | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::OpenBankingUk | api_enums::PaymentMethodType::OpenBankingPIS | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac => Self::BankRedirect, api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent | api_enums::PaymentMethodType::UpiQr => Self::Upi, api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa | api_enums::PaymentMethodType::SepaGuarenteedDebit | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Becs => Self::BankDebit, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { Self::Card } #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Self::Card, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward => Self::Reward, api_enums::PaymentMethodType::Boleto | api_enums::PaymentMethodType::Efecty | api_enums::PaymentMethodType::PagoEfectivo | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::SevenEleven | api_enums::PaymentMethodType::Lawson | api_enums::PaymentMethodType::MiniStop | api_enums::PaymentMethodType::FamilyMart | api_enums::PaymentMethodType::Seicomart | api_enums::PaymentMethodType::PayEasy | api_enums::PaymentMethodType::RedPagos => Self::Voucher, api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::Multibanco | api_enums::PaymentMethodType::PermataBankTransfer | api_enums::PaymentMethodType::BcaBankTransfer | api_enums::PaymentMethodType::BniVa | api_enums::PaymentMethodType::BriVa | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::InstantBankTransfer | api_enums::PaymentMethodType::InstantBankTransferFinland | api_enums::PaymentMethodType::InstantBankTransferPoland | api_enums::PaymentMethodType::SepaBankTransfer | api_enums::PaymentMethodType::IndonesianBankTransfer | api_enums::PaymentMethodType::Pix => Self::BankTransfer, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard | api_enums::PaymentMethodType::BhnCardNetwork => Self::GiftCard, api_enums::PaymentMethodType::Benefit | api_enums::PaymentMethodType::Knet | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect => Self::CardRedirect, api_enums::PaymentMethodType::Fps | api_enums::PaymentMethodType::DuitNow | api_enums::PaymentMethodType::PromptPay | api_enums::PaymentMethodType::VietQr => Self::RealTimePayment, api_enums::PaymentMethodType::DirectCarrierBilling => Self::MobilePayment, } } } impl ForeignTryFrom<payments::PaymentMethodData> for api_enums::PaymentMethod { type Error = errors::ApiErrorResponse; fn foreign_try_from( payment_method_data: payments::PaymentMethodData, ) -> Result<Self, Self::Error> { match payment_method_data { payments::PaymentMethodData::Card(..) | payments::PaymentMethodData::CardToken(..) => { Ok(Self::Card) } payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit), payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer), payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto), payments::PaymentMethodData::Reward => Ok(Self::Reward), payments::PaymentMethodData::RealTimePayment(..) => Ok(Self::RealTimePayment), payments::PaymentMethodData::Upi(..) => Ok(Self::Upi), payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher), payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard), payments::PaymentMethodData::CardRedirect(..) => Ok(Self::CardRedirect), payments::PaymentMethodData::OpenBanking(..) => Ok(Self::OpenBanking), payments::PaymentMethodData::MobilePayment(..) => Ok(Self::MobilePayment), payments::PaymentMethodData::MandatePayment => { Err(errors::ApiErrorResponse::InvalidRequestData { message: ("Mandate payments cannot have payment_method_data field".to_string()), }) } } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::RefundStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } #[cfg(feature = "payouts")] impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::PayoutSuccess => Ok(Self::Success), api_models::webhooks::IncomingWebhookEvent::PayoutFailure => Ok(Self::Failed), api_models::webhooks::IncomingWebhookEvent::PayoutCancelled => Ok(Self::Cancelled), api_models::webhooks::IncomingWebhookEvent::PayoutProcessing => Ok(Self::Pending), api_models::webhooks::IncomingWebhookEvent::PayoutCreated => Ok(Self::Initiated), api_models::webhooks::IncomingWebhookEvent::PayoutExpired => Ok(Self::Expired), api_models::webhooks::IncomingWebhookEvent::PayoutReversed => Ok(Self::Reversed), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::MandateStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::MandateActive => Ok(Self::Active), api_models::webhooks::IncomingWebhookEvent::MandateRevoked => Ok(Self::Revoked), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event_type", }), } } } impl ForeignFrom<storage::Config> for api_types::Config { fn foreign_from(config: storage::Config) -> Self { Self { key: config.key, value: config.config, } } } impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate { fn foreign_from(config: &api_types::ConfigUpdate) -> Self { Self::Update { config: Some(config.value.clone()), } } } impl From<&domain::Address> for hyperswitch_domain_models::address::Address { fn from(address: &domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() && address.line1.is_none() && address.line2.is_none() && address.line3.is_none() && address.state.is_none() && address.country.is_none() && address.zip.is_none() && address.first_name.is_none() && address.last_name.is_none() { None } else { Some(hyperswitch_domain_models::address::AddressDetails { city: address.city.clone(), country: address.country, line1: address.line1.clone().map(Encryptable::into_inner), line2: address.line2.clone().map(Encryptable::into_inner), line3: address.line3.clone().map(Encryptable::into_inner), state: address.state.clone().map(Encryptable::into_inner), zip: address.zip.clone().map(Encryptable::into_inner), first_name: address.first_name.clone().map(Encryptable::into_inner), last_name: address.last_name.clone().map(Encryptable::into_inner), origin_zip: address.origin_zip.clone().map(Encryptable::into_inner), }) }; // If all the fields of phone are none, then pass the phone as None let phone_details = if address.phone_number.is_none() && address.country_code.is_none() { None } else { Some(hyperswitch_domain_models::address::PhoneDetails { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), }) }; Self { address: address_details, phone: phone_details, email: address.email.clone().map(pii::Email::from), } } } impl ForeignFrom<domain::Address> for api_types::Address { fn foreign_from(address: domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() && address.line1.is_none() && address.line2.is_none() && address.line3.is_none() && address.state.is_none() && address.country.is_none() && address.zip.is_none() && address.first_name.is_none() && address.last_name.is_none() { None } else { Some(api_types::AddressDetails { city: address.city.clone(), country: address.country, line1: address.line1.clone().map(Encryptable::into_inner), line2: address.line2.clone().map(Encryptable::into_inner), line3: address.line3.clone().map(Encryptable::into_inner), state: address.state.clone().map(Encryptable::into_inner), zip: address.zip.clone().map(Encryptable::into_inner), first_name: address.first_name.clone().map(Encryptable::into_inner), last_name: address.last_name.clone().map(Encryptable::into_inner), origin_zip: address.origin_zip.clone().map(Encryptable::into_inner), }) }; // If all the fields of phone are none, then pass the phone as None let phone_details = if address.phone_number.is_none() && address.country_code.is_none() { None } else { Some(api_types::PhoneDetails { number: address.phone_number.clone().map(Encryptable::into_inner), country_code: address.country_code.clone(), }) }; Self { address: address_details, phone: phone_details, email: address.email.clone().map(pii::Email::from), } } } impl ForeignFrom<( diesel_models::api_keys::ApiKey, crate::core::api_keys::PlaintextApiKey, )> for api_models::api_keys::CreateApiKeyResponse { fn foreign_from( item: ( diesel_models::api_keys::ApiKey, crate::core::api_keys::PlaintextApiKey, ), ) -> Self { use masking::StrongSecret; let (api_key, plaintext_api_key) = item; Self { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, api_key: StrongSecret::from(plaintext_api_key.peek().to_owned()), created: api_key.created_at, expiration: api_key.expires_at.into(), } } } impl ForeignFrom<diesel_models::api_keys::ApiKey> for api_models::api_keys::RetrieveApiKeyResponse { fn foreign_from(api_key: diesel_models::api_keys::ApiKey) -> Self { Self { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, prefix: api_key.prefix.into(), created: api_key.created_at, expiration: api_key.expires_at.into(), } } } impl ForeignFrom<api_models::api_keys::UpdateApiKeyRequest> for diesel_models::api_keys::ApiKeyUpdate { fn foreign_from(api_key: api_models::api_keys::UpdateApiKeyRequest) -> Self { Self::Update { name: api_key.name, description: api_key.description, expires_at: api_key.expiration.map(Into::into), last_used: None, } } } impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::DisputeStatus { type Error = errors::ValidationError; fn foreign_try_from( value: api_models::webhooks::IncomingWebhookEvent, ) -> Result<Self, Self::Error> { match value { api_models::webhooks::IncomingWebhookEvent::DisputeOpened => Ok(Self::DisputeOpened), api_models::webhooks::IncomingWebhookEvent::DisputeExpired => Ok(Self::DisputeExpired), api_models::webhooks::IncomingWebhookEvent::DisputeAccepted => { Ok(Self::DisputeAccepted) } api_models::webhooks::IncomingWebhookEvent::DisputeCancelled => { Ok(Self::DisputeCancelled) } api_models::webhooks::IncomingWebhookEvent::DisputeChallenged => { Ok(Self::DisputeChallenged) } api_models::webhooks::IncomingWebhookEvent::DisputeWon => Ok(Self::DisputeWon), api_models::webhooks::IncomingWebhookEvent::DisputeLost => Ok(Self::DisputeLost), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "incoming_webhook_event", }), } } } impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse { fn foreign_from(dispute: storage::Dispute) -> Self { Self { dispute_id: dispute.dispute_id, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, amount: dispute.amount, currency: dispute.dispute_currency.unwrap_or( dispute .currency .to_uppercase() .parse_enum("Currency") .unwrap_or_default(), ), dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, connector: dispute.connector, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: dispute.created_at, profile_id: dispute.profile_id, merchant_connector_id: dispute.merchant_connector_id, } } } impl ForeignFrom<storage::Authorization> for payments::IncrementalAuthorizationResponse { fn foreign_from(authorization: storage::Authorization) -> Self { Self { authorization_id: authorization.authorization_id, amount: authorization.amount, status: authorization.status, error_code: authorization.error_code, error_message: authorization.error_message, previously_authorized_amount: authorization.previously_authorized_amount, } } } impl ForeignFrom< &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, > for payments::ExternalAuthenticationDetailsResponse { fn foreign_from( authn_store: &hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore, ) -> Self { let authn_data = &authn_store.authentication; let version = authn_data .maximum_supported_version .as_ref() .map(|version| version.to_string()); Self { authentication_flow: authn_data.authentication_type, electronic_commerce_indicator: authn_data.eci.clone(), status: authn_data.authentication_status, ds_transaction_id: authn_data.threeds_server_transaction_id.clone(), version, error_code: authn_data.error_code.clone(), error_message: authn_data.error_message.clone(), } } } impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponsePaymentsRetrieve { fn foreign_from(dispute: storage::Dispute) -> Self { Self { dispute_id: dispute.dispute_id, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: dispute.created_at, } } } impl ForeignFrom<storage::FileMetadata> for api_models::files::FileMetadataResponse { fn foreign_from(file_metadata: storage::FileMetadata) -> Self { Self { file_id: file_metadata.file_id, file_name: file_metadata.file_name, file_size: file_metadata.file_size, file_type: file_metadata.file_type, available: file_metadata.available, } } } impl ForeignFrom<diesel_models::cards_info::CardInfo> for api_models::cards_info::CardInfoResponse { fn foreign_from(item: diesel_models::cards_info::CardInfo) -> Self { Self { card_iin: item.card_iin, card_type: item.card_type, card_sub_type: item.card_subtype, card_network: item.card_network.map(|x| x.to_string()), card_issuer: item.card_issuer, card_issuing_country: item.card_issuing_country, } } } impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorListResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { #[cfg(feature = "v1")] let payment_methods_enabled = match item.payment_methods_enabled { Some(secret_val) => { let val = secret_val .into_iter() .map(|secret| secret.expose()) .collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(errors::ApiErrorResponse::InternalServerError)? } None => None, }; let frm_configs = match item.frm_configs { Some(frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; #[cfg(feature = "v1")] let response = Self { connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, merchant_connector_id: item.merchant_connector_id, test_mode: item.test_mode, disabled: item.disabled, payment_methods_enabled, business_country: item.business_country, business_label: item.business_label, business_sub_label: item.business_sub_label, frm_configs, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, }; #[cfg(feature = "v2")] let response = Self { id: item.id, connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, disabled: item.disabled, payment_methods_enabled: item.payment_methods_enabled, frm_configs, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, }; Ok(response) } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { let payment_methods_enabled = match item.payment_methods_enabled.clone() { Some(secret_val) => { let val = secret_val .into_iter() .map(|secret| secret.expose()) .collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(errors::ApiErrorResponse::InternalServerError)? } None => None, }; let frm_configs = match item.frm_configs { Some(ref frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; // parse the connector_account_details into ConnectorAuthType let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType = item.connector_account_details .clone() .into_inner() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // get the masked keys from the ConnectorAuthType and encode it to secret value let masked_connector_account_details = Secret::new( connector_account_details .get_masked_keys() .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode ConnectorAuthType")?, ); #[cfg(feature = "v2")] let response = Self { id: item.get_id(), connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, connector_account_details: masked_connector_account_details, disabled: item.disabled, payment_methods_enabled, metadata: item.metadata, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, }; #[cfg(feature = "v1")] let response = Self { connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, merchant_connector_id: item.merchant_connector_id, connector_account_details: masked_connector_account_details, test_mode: item.test_mode, disabled: item.disabled, payment_methods_enabled, metadata: item.metadata, business_country: item.business_country, business_label: item.business_label, business_sub_label: item.business_sub_label, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, }; Ok(response) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantConnectorResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: domain::MerchantConnectorAccount) -> Result<Self, Self::Error> { let frm_configs = match item.frm_configs { Some(ref frm_value) => { let configs_for_frm : Vec<api_models::admin::FrmConfigs> = frm_value .iter() .map(|config| { config .peek() .clone() .parse_value("FrmConfigs") .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "frm_configs".to_string(), expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","payment_method_types": [{"payment_method_type": "credit","card_networks": ["Visa"],"flow": "pre","action": "cancel_txn"}]}]}]"#.to_string(), }) }) .collect::<Result<Vec<_>, _>>()?; Some(configs_for_frm) } None => None, }; // parse the connector_account_details into ConnectorAuthType let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType = item.connector_account_details .clone() .into_inner() .parse_value("ConnectorAuthType") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while parsing value for ConnectorAuthType")?; // get the masked keys from the ConnectorAuthType and encode it to secret value let masked_connector_account_details = Secret::new( connector_account_details .get_masked_keys() .encode_to_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode ConnectorAuthType")?, ); let feature_metadata = item.feature_metadata.as_ref().map(|metadata| { api_models::admin::MerchantConnectorAccountFeatureMetadata::foreign_from(metadata) }); let response = Self { id: item.get_id(), connector_type: item.connector_type, connector_name: item.connector_name, connector_label: item.connector_label, connector_account_details: masked_connector_account_details, disabled: item.disabled, payment_methods_enabled: item.payment_methods_enabled, metadata: item.metadata, frm_configs, connector_webhook_details: item .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .attach_printable("Unable to deserialize connector_webhook_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, status: item.status, additional_merchant_data: item .additional_merchant_data .map(|data| { let data = data.into_inner(); serde_json::Value::parse_value::<router_types::AdditionalMerchantData>( data.expose(), "AdditionalMerchantData", ) .attach_printable("Unable to deserialize additional_merchant_data") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), connector_wallets_details: item .connector_wallets_details .map(|data| { data.into_inner() .expose() .parse_value::<api_models::admin::ConnectorWalletDetails>( "ConnectorWalletDetails", ) .attach_printable("Unable to deserialize connector_wallets_details") .change_context(errors::ApiErrorResponse::InternalServerError) }) .transpose()?, feature_metadata, }; Ok(response) } } #[cfg(feature = "v1")] impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self { let connector_transaction_id = payment_attempt .get_connector_payment_id() .map(ToString::to_string); Self { attempt_id: payment_attempt.attempt_id, status: payment_attempt.status, amount: payment_attempt.net_amount.get_order_amount(), order_tax_amount: payment_attempt.net_amount.get_order_tax_amount(), currency: payment_attempt.currency, connector: payment_attempt.connector, error_message: payment_attempt.error_reason, payment_method: payment_attempt.payment_method, connector_transaction_id, capture_method: payment_attempt.capture_method, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt.created_at, modified_at: payment_attempt.modified_at, cancellation_reason: payment_attempt.cancellation_reason, mandate_id: payment_attempt.mandate_id, error_code: payment_attempt.error_code, payment_token: payment_attempt.payment_token, connector_metadata: payment_attempt.connector_metadata, payment_experience: payment_attempt.payment_experience, payment_method_type: payment_attempt.payment_method_type, reference_id: payment_attempt.connector_response_reference_id, unified_code: payment_attempt.unified_code, unified_message: payment_attempt.unified_message, client_source: payment_attempt.client_source, client_version: payment_attempt.client_version, } } } impl ForeignFrom<storage::Capture> for payments::CaptureResponse { fn foreign_from(capture: storage::Capture) -> Self { let connector_capture_id = capture.get_optional_connector_transaction_id().cloned(); Self { capture_id: capture.capture_id, status: capture.status, amount: capture.amount, currency: capture.currency, connector: capture.connector, authorized_attempt_id: capture.authorized_attempt_id, connector_capture_id, capture_sequence: capture.capture_sequence, error_message: capture.error_message, error_code: capture.error_code, error_reason: capture.error_reason, reference_id: capture.connector_response_reference_id, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(bank) => Self::foreign_from(bank), api_models::payouts::PayoutMethodData::Card(_) => Self::Debit, api_models::payouts::PayoutMethodData::Wallet(wallet) => Self::foreign_from(wallet), api_models::payouts::PayoutMethodData::BankRedirect(bank_redirect) => { Self::foreign_from(bank_redirect) } } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::Bank> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::Bank) -> Self { match value { api_models::payouts::Bank::Ach(_) => Self::Ach, api_models::payouts::Bank::Bacs(_) => Self::Bacs, api_models::payouts::Bank::Sepa(_) => Self::SepaBankTransfer, api_models::payouts::Bank::Pix(_) => Self::Pix, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::Wallet> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::Wallet) -> Self { match value { api_models::payouts::Wallet::Paypal(_) => Self::Paypal, api_models::payouts::Wallet::Venmo(_) => Self::Venmo, api_models::payouts::Wallet::ApplePayDecrypt(_) => Self::ApplePay, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::BankRedirect> for api_enums::PaymentMethodType { fn foreign_from(value: &api_models::payouts::BankRedirect) -> Self { match value { api_models::payouts::BankRedirect::Interac(_) => Self::Interac, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_enums::PaymentMethod { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(_) => Self::BankTransfer, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect, } } } #[cfg(feature = "payouts")] impl ForeignFrom<&api_models::payouts::PayoutMethodData> for api_models::enums::PayoutType { fn foreign_from(value: &api_models::payouts::PayoutMethodData) -> Self { match value { api_models::payouts::PayoutMethodData::Bank(_) => Self::Bank, api_models::payouts::PayoutMethodData::Card(_) => Self::Card, api_models::payouts::PayoutMethodData::Wallet(_) => Self::Wallet, api_models::payouts::PayoutMethodData::BankRedirect(_) => Self::BankRedirect, } } } #[cfg(feature = "payouts")] impl ForeignFrom<api_models::enums::PayoutType> for api_enums::PaymentMethod { fn foreign_from(value: api_models::enums::PayoutType) -> Self { match value { api_models::enums::PayoutType::Bank => Self::BankTransfer, api_models::enums::PayoutType::Card => Self::Card, api_models::enums::PayoutType::Wallet => Self::Wallet, api_models::enums::PayoutType::BankRedirect => Self::BankRedirect, } } } #[cfg(feature = "payouts")] impl ForeignTryFrom<api_enums::PaymentMethod> for api_models::enums::PayoutType { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(value: api_enums::PaymentMethod) -> Result<Self, Self::Error> { match value { api_enums::PaymentMethod::Card => Ok(Self::Card), api_enums::PaymentMethod::BankTransfer => Ok(Self::Bank), api_enums::PaymentMethod::Wallet => Ok(Self::Wallet), _ => Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("PaymentMethod {value:?} is not supported for payouts"), }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert PaymentMethod to PayoutType"), } } } #[cfg(feature = "v1")] impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { let payment_confirm_source: Option<api_enums::PaymentSource> = get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)? .map(|source| { source .to_owned() .parse_enum("PaymentSource") .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header" .into(), }) .attach_printable( "Failed while paring PaymentConfirmSource header value to enum", ) }) .transpose()?; when( payment_confirm_source.is_some_and(|payment_confirm_source| { payment_confirm_source.is_for_internal_use_only() }), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header".into(), })) }, )?; let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string()); let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers) .map(|value| value == Some("true")) .unwrap_or(false); let client_source = get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string()); let client_version = get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); let browser_name_str = get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string()); let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| { browser_name .parse_enum("BrowserName") .unwrap_or(api_enums::BrowserName::Unknown) }); let x_client_platform_str = get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string()); let x_client_platform: Option<api_enums::ClientPlatform> = x_client_platform_str.map(|x_client_platform| { x_client_platform .parse_enum("ClientPlatform") .unwrap_or(api_enums::ClientPlatform::Unknown) }); let x_merchant_domain = get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); let x_app_id = get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string()); let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); let x_reference_id = get_header_value_by_key(X_REFERENCE_ID.into(), headers)?.map(|val| val.to_string()); Ok(Self { payment_confirm_source, client_source, client_version, x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, x_merchant_domain, locale, x_app_id, x_redirect_uri, x_reference_id, }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<&HeaderMap> for hyperswitch_domain_models::payments::HeaderPayload { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { use std::str::FromStr; use crate::headers::X_CLIENT_SECRET; let payment_confirm_source: Option<api_enums::PaymentSource> = get_header_value_by_key(X_PAYMENT_CONFIRM_SOURCE.into(), headers)? .map(|source| { source .to_owned() .parse_enum("PaymentSource") .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header" .into(), }) .attach_printable( "Failed while paring PaymentConfirmSource header value to enum", ) }) .transpose()?; when( payment_confirm_source.is_some_and(|payment_confirm_source| { payment_confirm_source.is_for_internal_use_only() }), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid data received in payment_confirm_source header".into(), })) }, )?; let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)?.map(|val| val.to_string()); let x_hs_latency = get_header_value_by_key(X_HS_LATENCY.into(), headers) .map(|value| value == Some("true")) .unwrap_or(false); let client_source = get_header_value_by_key(X_CLIENT_SOURCE.into(), headers)?.map(|val| val.to_string()); let client_version = get_header_value_by_key(X_CLIENT_VERSION.into(), headers)?.map(|val| val.to_string()); let browser_name_str = get_header_value_by_key(BROWSER_NAME.into(), headers)?.map(|val| val.to_string()); let browser_name: Option<api_enums::BrowserName> = browser_name_str.map(|browser_name| { browser_name .parse_enum("BrowserName") .unwrap_or(api_enums::BrowserName::Unknown) }); let x_client_platform_str = get_header_value_by_key(X_CLIENT_PLATFORM.into(), headers)?.map(|val| val.to_string()); let x_client_platform: Option<api_enums::ClientPlatform> = x_client_platform_str.map(|x_client_platform| { x_client_platform .parse_enum("ClientPlatform") .unwrap_or(api_enums::ClientPlatform::Unknown) }); let x_merchant_domain = get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); let x_app_id = get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string()); let x_redirect_uri = get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); let x_reference_id = get_header_value_by_key(X_REFERENCE_ID.into(), headers)?.map(|val| val.to_string()); Ok(Self { payment_confirm_source, // client_source, // client_version, x_hs_latency: Some(x_hs_latency), browser_name, x_client_platform, x_merchant_domain, locale, x_app_id, x_redirect_uri, x_reference_id, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<( Option<&storage::PaymentAttempt>, Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, )> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( value: ( Option<&storage::PaymentAttempt>, Option<&storage::PaymentIntent>, Option<&domain::Address>, Option<&domain::Address>, Option<&domain::Customer>, ), ) -> Result<Self, Self::Error> { let (payment_attempt, payment_intent, shipping, billing, customer) = value; // Populating the dynamic fields directly, for the cases where we have customer details stored in // Payment Intent let customer_details_from_pi = payment_intent .and_then(|payment_intent| payment_intent.customer_details.clone()) .map(|customer_details| { customer_details .into_inner() .peek() .clone() .parse_value::<CustomerData>("CustomerData") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_details", }) .attach_printable("Failed to parse customer_details") }) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "customer_details", })?; let mut billing_address = billing .map(hyperswitch_domain_models::address::Address::from) .map(api_types::Address::from); // This change is to fix a merchant integration // If billing.email is not passed by the merchant, and if the customer email is present, then use the `customer.email` as the billing email if let Some(billing_address) = &mut billing_address { billing_address.email = billing_address.email.clone().or_else(|| { customer .and_then(|cust| { cust.email .as_ref() .map(|email| pii::Email::from(email.clone())) }) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)) }); } else { billing_address = Some(payments::Address { email: customer .and_then(|cust| { cust.email .as_ref() .map(|email| pii::Email::from(email.clone())) }) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)), ..Default::default() }); } Ok(Self { currency: payment_attempt.map(|pa| pa.currency.unwrap_or_default()), shipping: shipping .map(hyperswitch_domain_models::address::Address::from) .map(api_types::Address::from), billing: billing_address, amount: payment_attempt .map(|pa| api_types::Amount::from(pa.net_amount.get_order_amount())), email: customer .and_then(|cust| cust.email.as_ref().map(|em| pii::Email::from(em.clone()))) .or(customer_details_from_pi.clone().and_then(|cd| cd.email)), phone: customer .and_then(|cust| cust.phone.as_ref().map(|p| p.clone().into_inner())) .or(customer_details_from_pi.clone().and_then(|cd| cd.phone)), name: customer .and_then(|cust| cust.name.as_ref().map(|n| n.clone().into_inner())) .or(customer_details_from_pi.clone().and_then(|cd| cd.name)), ..Self::default() }) } } impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)> for payments::RetrievePaymentLinkResponse { fn foreign_from( (payment_link_config, status): (storage::PaymentLink, payments::PaymentLinkStatus), ) -> Self { Self { payment_link_id: payment_link_config.payment_link_id, merchant_id: payment_link_config.merchant_id, link_to_pay: payment_link_config.link_to_pay, amount: payment_link_config.amount, created_at: payment_link_config.created_at, expiry: payment_link_config.fulfilment_time, description: payment_link_config.description, currency: payment_link_config.currency, status, secure_link: payment_link_config.secure_link, } } } impl From<domain::Address> for payments::AddressDetails { fn from(addr: domain::Address) -> Self { Self { city: addr.city, country: addr.country, line1: addr.line1.map(Encryptable::into_inner), line2: addr.line2.map(Encryptable::into_inner), line3: addr.line3.map(Encryptable::into_inner), zip: addr.zip.map(Encryptable::into_inner), state: addr.state.map(Encryptable::into_inner), first_name: addr.first_name.map(Encryptable::into_inner), last_name: addr.last_name.map(Encryptable::into_inner), origin_zip: addr.origin_zip.map(Encryptable::into_inner), } } } impl ForeignFrom<ConnectorSelection> for routing_types::StaticRoutingAlgorithm { fn foreign_from(value: ConnectorSelection) -> Self { match value { ConnectorSelection::Priority(connectors) => Self::Priority(connectors), ConnectorSelection::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl ForeignFrom<api_models::organization::OrganizationNew> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationNew) -> Self { Self::new(item.org_id, item.org_type, item.org_name) } } impl ForeignFrom<api_models::organization::OrganizationCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationCreateRequest) -> Self { // Create a new organization with a standard type by default let org_new = api_models::organization::OrganizationNew::new( common_enums::OrganizationType::Standard, None, ); let api_models::organization::OrganizationCreateRequest { organization_name, organization_details, metadata, } = item; let mut org_new_db = Self::new(org_new.org_id, org_new.org_type, Some(organization_name)); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db } } impl ForeignFrom<gsm_api_types::GsmCreateRequest> for hyperswitch_domain_models::gsm::GatewayStatusMap { fn foreign_from(value: gsm_api_types::GsmCreateRequest) -> Self { let inferred_feature_data = common_types::domain::GsmFeatureData::foreign_from(&value); Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, status: value.status, router_error: value.router_error, unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, feature_data: value.feature_data.unwrap_or(inferred_feature_data), feature: value.feature.unwrap_or(api_enums::GsmFeature::Retry), } } } impl ForeignFrom<&gsm_api_types::GsmCreateRequest> for common_types::domain::GsmFeatureData { fn foreign_from(value: &gsm_api_types::GsmCreateRequest) -> Self { // Defaulting alternate_network_possible to false as it is provided only in the Retry feature // If the retry feature is not used, we assume alternate network as false let alternate_network_possible = false; match value.feature { Some(api_enums::GsmFeature::Retry) | None => { Self::Retry(common_types::domain::RetryFeatureData { step_up_possible: value.step_up_possible, clear_pan_possible: value.clear_pan_possible, alternate_network_possible, decision: value.decision, }) } } } } impl ForeignFrom<( &gsm_api_types::GsmUpdateRequest, hyperswitch_domain_models::gsm::GatewayStatusMap, )> for (api_enums::GsmFeature, common_types::domain::GsmFeatureData) { fn foreign_from( (gsm_update_request, gsm_db_record): ( &gsm_api_types::GsmUpdateRequest, hyperswitch_domain_models::gsm::GatewayStatusMap, ), ) -> Self { let gsm_db_record_inferred_feature = match gsm_db_record.feature_data.get_decision() { api_enums::GsmDecision::Retry | api_enums::GsmDecision::DoDefault => { api_enums::GsmFeature::Retry } }; let gsm_feature = gsm_update_request .feature .unwrap_or(gsm_db_record_inferred_feature); match gsm_feature { api_enums::GsmFeature::Retry => { let gsm_db_record_retry_feature_data = gsm_db_record.feature_data.get_retry_feature_data(); let retry_feature_data = common_types::domain::GsmFeatureData::Retry( common_types::domain::RetryFeatureData { step_up_possible: gsm_update_request .step_up_possible .or(gsm_db_record_retry_feature_data .clone() .map(|data| data.step_up_possible)) .unwrap_or_default(), clear_pan_possible: gsm_update_request .clear_pan_possible .or(gsm_db_record_retry_feature_data .clone() .map(|data| data.clear_pan_possible)) .unwrap_or_default(), alternate_network_possible: gsm_db_record_retry_feature_data .map(|data| data.alternate_network_possible) .unwrap_or_default(), decision: gsm_update_request .decision .or(Some(gsm_db_record.feature_data.get_decision())) .unwrap_or_default(), }, ); (api_enums::GsmFeature::Retry, retry_feature_data) } } } } impl ForeignFrom<hyperswitch_domain_models::gsm::GatewayStatusMap> for gsm_api_types::GsmResponse { fn foreign_from(value: hyperswitch_domain_models::gsm::GatewayStatusMap) -> Self { Self { connector: value.connector.to_string(), flow: value.flow, sub_flow: value.sub_flow, code: value.code, message: value.message, decision: value.feature_data.get_decision(), status: value.status, router_error: value.router_error, step_up_possible: value .feature_data .get_retry_feature_data() .map(|data| data.is_step_up_possible()) .unwrap_or(false), unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, clear_pan_possible: value .feature_data .get_retry_feature_data() .map(|data| data.is_clear_pan_possible()) .unwrap_or(false), feature_data: Some(value.feature_data), feature: value.feature, } } } #[cfg(feature = "v2")] impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse { fn foreign_from(_customer: &domain::Customer) -> Self { todo!() } } #[cfg(feature = "v1")] impl ForeignFrom<&domain::Customer> for payments::CustomerDetailsResponse { fn foreign_from(customer: &domain::Customer) -> Self { Self { id: Some(customer.customer_id.clone()), name: customer .name .as_ref() .map(|name| name.get_inner().to_owned()), email: customer.email.clone().map(Into::into), phone: customer .phone .as_ref() .map(|phone| phone.get_inner().to_owned()), phone_country_code: customer.phone_country_code.clone(), } } } #[cfg(feature = "olap")] impl ForeignTryFrom<api_types::webhook_events::EventListConstraints> for api_types::webhook_events::EventListConstraintsInternal { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( item: api_types::webhook_events::EventListConstraints, ) -> Result<Self, Self::Error> { if item.object_id.is_some() && (item.created_after.is_some() || item.created_before.is_some() || item.limit.is_some() || item.offset.is_some() || item.event_classes.is_some() || item.event_types.is_some()) { return Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "Either only `object_id` must be specified, or one or more of \ `created_after`, `created_before`, `limit`, `offset`, `event_classes` and `event_types` must be specified" .to_string() })); } match item.object_id { Some(object_id) => Ok(Self::ObjectIdFilter { object_id }), None => Ok(Self::GenericFilter { created_after: item.created_after, created_before: item.created_before, limit: item.limit.map(i64::from), offset: item.offset.map(i64::from), event_classes: item.event_classes, event_types: item.event_types, is_delivered: item.is_delivered, }), } } } #[cfg(feature = "olap")] impl TryFrom<domain::Event> for api_models::webhook_events::EventListItemResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with merchant_id, business_profile_id // and initial_attempt_id populated. // We cannot retrieve events with only some of these fields populated. let merchant_id = item .merchant_id .get_required_value("merchant_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let profile_id = item .business_profile_id .get_required_value("business_profile_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; let initial_attempt_id = item .initial_attempt_id .get_required_value("initial_attempt_id") .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(Self { event_id: item.event_id, merchant_id, profile_id, object_id: item.primary_object_id, event_type: item.event_type, event_class: item.event_class, is_delivery_successful: item.is_overall_delivery_successful, initial_attempt_id, created: item.created_at, }) } } #[cfg(feature = "olap")] impl TryFrom<domain::Event> for api_models::webhook_events::EventRetrieveResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: domain::Event) -> Result<Self, Self::Error> { use crate::utils::OptionExt; // We only allow retrieving events with all required fields in `EventListItemResponse`, and // `request` and `response` populated. // We cannot retrieve events with only some of these fields populated. let event_information = api_models::webhook_events::EventListItemResponse::try_from(item.clone())?; let request = item .request .get_required_value("request") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookRequestContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event request information")?; let response = item .response .get_required_value("response") .change_context(errors::ApiErrorResponse::InternalServerError)? .peek() .parse_struct("OutgoingWebhookResponseContent") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse webhook event response information")?; Ok(Self { event_information, request, response, delivery_attempt: item.delivery_attempt, }) } } impl ForeignFrom<api_models::admin::AuthenticationConnectorDetails> for diesel_models::business_profile::AuthenticationConnectorDetails { fn foreign_from(item: api_models::admin::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } } impl ForeignFrom<diesel_models::business_profile::AuthenticationConnectorDetails> for api_models::admin::AuthenticationConnectorDetails { fn foreign_from(item: diesel_models::business_profile::AuthenticationConnectorDetails) -> Self { Self { authentication_connectors: item.authentication_connectors, three_ds_requestor_url: item.three_ds_requestor_url, three_ds_requestor_app_url: item.three_ds_requestor_app_url, } } } impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails> for diesel_models::business_profile::ExternalVaultConnectorDetails { fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self { Self { vault_connector_id: item.vault_connector_id, vault_sdk: item.vault_sdk, } } } impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails> for api_models::admin::ExternalVaultConnectorDetails { fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self { Self { vault_connector_id: item.vault_connector_id, vault_sdk: item.vault_sdk, } } } impl ForeignFrom<api_models::admin::CardTestingGuardConfig> for diesel_models::business_profile::CardTestingGuardConfig { fn foreign_from(item: api_models::admin::CardTestingGuardConfig) -> Self { Self { is_card_ip_blocking_enabled: match item.card_ip_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, card_ip_blocking_threshold: item.card_ip_blocking_threshold, is_guest_user_card_blocking_enabled: match item.guest_user_card_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold, is_customer_id_blocking_enabled: match item.customer_id_blocking_status { api_models::admin::CardTestingGuardStatus::Enabled => true, api_models::admin::CardTestingGuardStatus::Disabled => false, }, customer_id_blocking_threshold: item.customer_id_blocking_threshold, card_testing_guard_expiry: item.card_testing_guard_expiry, } } } impl ForeignFrom<diesel_models::business_profile::CardTestingGuardConfig> for api_models::admin::CardTestingGuardConfig { fn foreign_from(item: diesel_models::business_profile::CardTestingGuardConfig) -> Self { Self { card_ip_blocking_status: match item.is_card_ip_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, card_ip_blocking_threshold: item.card_ip_blocking_threshold, guest_user_card_blocking_status: match item.is_guest_user_card_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, guest_user_card_blocking_threshold: item.guest_user_card_blocking_threshold, customer_id_blocking_status: match item.is_customer_id_blocking_enabled { true => api_models::admin::CardTestingGuardStatus::Enabled, false => api_models::admin::CardTestingGuardStatus::Disabled, }, customer_id_blocking_threshold: item.customer_id_blocking_threshold, card_testing_guard_expiry: item.card_testing_guard_expiry, } } } impl ForeignFrom<api_models::admin::WebhookDetails> for diesel_models::business_profile::WebhookDetails { fn foreign_from(item: api_models::admin::WebhookDetails) -> Self { Self { webhook_version: item.webhook_version, webhook_username: item.webhook_username, webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, payment_failed_enabled: item.payment_failed_enabled, payment_succeeded_enabled: item.payment_succeeded_enabled, payment_statuses_enabled: item.payment_statuses_enabled, refund_statuses_enabled: item.refund_statuses_enabled, payout_statuses_enabled: item.payout_statuses_enabled, multiple_webhooks_list: None, } } } impl ForeignFrom<diesel_models::business_profile::WebhookDetails> for api_models::admin::WebhookDetails { fn foreign_from(item: diesel_models::business_profile::WebhookDetails) -> Self { Self { webhook_version: item.webhook_version, webhook_username: item.webhook_username, webhook_password: item.webhook_password, webhook_url: item.webhook_url, payment_created_enabled: item.payment_created_enabled, payment_failed_enabled: item.payment_failed_enabled, payment_succeeded_enabled: item.payment_succeeded_enabled, payment_statuses_enabled: item.payment_statuses_enabled, refund_statuses_enabled: item.refund_statuses_enabled, payout_statuses_enabled: item.payout_statuses_enabled, } } } impl ForeignFrom<api_models::admin::BusinessPaymentLinkConfig> for diesel_models::business_profile::BusinessPaymentLinkConfig { fn foreign_from(item: api_models::admin::BusinessPaymentLinkConfig) -> Self { Self { domain_name: item.domain_name, default_config: item.default_config.map(ForeignInto::foreign_into), business_specific_configs: item.business_specific_configs.map(|map| { map.into_iter() .map(|(k, v)| (k, v.foreign_into())) .collect() }), allowed_domains: item.allowed_domains, branding_visibility: item.branding_visibility, } } } impl ForeignFrom<diesel_models::business_profile::BusinessPaymentLinkConfig> for api_models::admin::BusinessPaymentLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessPaymentLinkConfig) -> Self { Self { domain_name: item.domain_name, default_config: item.default_config.map(ForeignInto::foreign_into), business_specific_configs: item.business_specific_configs.map(|map| { map.into_iter() .map(|(k, v)| (k, v.foreign_into())) .collect() }), allowed_domains: item.allowed_domains, branding_visibility: item.branding_visibility, } } } impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest> for diesel_models::business_profile::PaymentLinkConfigRequest { fn foreign_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, details_layout: item.details_layout, background_image: item .background_image .map(|background_image| background_image.foreign_into()), payment_button_text: item.payment_button_text, skip_status_screen: item.skip_status_screen, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, payment_form_header_text: item.payment_form_header_text, payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } } impl ForeignFrom<diesel_models::business_profile::PaymentLinkConfigRequest> for api_models::admin::PaymentLinkConfigRequest { fn foreign_from(item: diesel_models::business_profile::PaymentLinkConfigRequest) -> Self { Self { theme: item.theme, logo: item.logo, seller_name: item.seller_name, sdk_layout: item.sdk_layout, display_sdk_only: item.display_sdk_only, enabled_saved_payment_method: item.enabled_saved_payment_method, hide_card_nickname_field: item.hide_card_nickname_field, show_card_form_by_default: item.show_card_form_by_default, transaction_details: None, details_layout: item.details_layout, background_image: item .background_image .map(|background_image| background_image.foreign_into()), payment_button_text: item.payment_button_text, skip_status_screen: item.skip_status_screen, custom_message_for_card_terms: item.custom_message_for_card_terms, payment_button_colour: item.payment_button_colour, background_colour: item.background_colour, payment_button_text_colour: item.payment_button_text_colour, sdk_ui_rules: item.sdk_ui_rules, payment_link_ui_rules: item.payment_link_ui_rules, enable_button_only_on_form_ready: item.enable_button_only_on_form_ready, payment_form_header_text: item.payment_form_header_text, payment_form_label_type: item.payment_form_label_type, show_card_terms: item.show_card_terms, is_setup_mandate_flow: item.is_setup_mandate_flow, color_icon_card_cvc_error: item.color_icon_card_cvc_error, } } } impl ForeignFrom<diesel_models::business_profile::PaymentLinkBackgroundImageConfig> for api_models::admin::PaymentLinkBackgroundImageConfig { fn foreign_from( item: diesel_models::business_profile::PaymentLinkBackgroundImageConfig, ) -> Self { Self { url: item.url, position: item.position, size: item.size, } } } impl ForeignFrom<api_models::admin::PaymentLinkBackgroundImageConfig> for diesel_models::business_profile::PaymentLinkBackgroundImageConfig { fn foreign_from(item: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self { Self { url: item.url, position: item.position, size: item.size, } } } impl ForeignFrom<api_models::admin::BusinessPayoutLinkConfig> for diesel_models::business_profile::BusinessPayoutLinkConfig { fn foreign_from(item: api_models::admin::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } } impl ForeignFrom<diesel_models::business_profile::BusinessPayoutLinkConfig> for api_models::admin::BusinessPayoutLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } } impl ForeignFrom<api_models::admin::BusinessGenericLinkConfig> for diesel_models::business_profile::BusinessGenericLinkConfig { fn foreign_from(item: api_models::admin::BusinessGenericLinkConfig) -> Self { Self { domain_name: item.domain_name, allowed_domains: item.allowed_domains, ui_config: item.ui_config, } } } impl ForeignFrom<diesel_models::business_profile::BusinessGenericLinkConfig> for api_models::admin::BusinessGenericLinkConfig { fn foreign_from(item: diesel_models::business_profile::BusinessGenericLinkConfig) -> Self { Self { domain_name: item.domain_name, allowed_domains: item.allowed_domains, ui_config: item.ui_config, } } } impl ForeignFrom<card_info_types::CardInfoCreateRequest> for storage::CardInfo { fn foreign_from(value: card_info_types::CardInfoCreateRequest) -> Self { Self { card_iin: value.card_iin, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_subtype: value.card_subtype, card_issuing_country: value.card_issuing_country, bank_code_id: value.bank_code_id, bank_code: value.bank_code, country_code: value.country_code, date_created: common_utils::date_time::now(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: value.last_updated_provider, } } } impl ForeignFrom<card_info_types::CardInfoUpdateRequest> for storage::CardInfo { fn foreign_from(value: card_info_types::CardInfoUpdateRequest) -> Self { Self { card_iin: value.card_iin, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_subtype: value.card_subtype, card_issuing_country: value.card_issuing_country, bank_code_id: value.bank_code_id, bank_code: value.bank_code, country_code: value.country_code, date_created: common_utils::date_time::now(), last_updated: Some(common_utils::date_time::now()), last_updated_provider: value.last_updated_provider, } } } #[cfg(feature = "v2")] impl ForeignFrom<&revenue_recovery_redis_operation::PaymentProcessorTokenStatus> for payments::AdditionalCardInfo { fn foreign_from(value: &revenue_recovery_redis_operation::PaymentProcessorTokenStatus) -> Self { let card_info = &value.payment_processor_token_details; // TODO! All other card info fields needs to be populated in redis. Self { card_issuer: card_info.card_issuer.to_owned(), card_network: card_info.card_network.to_owned(), card_type: card_info.card_type.to_owned(), card_issuing_country: None, bank_code: None, last4: card_info.last_four_digits.to_owned(), card_isin: None, card_extended_bin: None, card_exp_month: card_info.expiry_month.to_owned(), card_exp_year: card_info.expiry_year.to_owned(), card_holder_name: None, payment_checks: None, authentication_data: None, is_regulated: None, signature_network: None, } } }
{ "crate": "router", "file": "crates/router/src/types/transformers.rs", "file_size": 96624, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_9219182696538314524
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/tokenization.rs // File size: 86976 bytes use std::collections::HashMap; use ::payment_methods::controller::PaymentMethodsController; #[cfg(feature = "v1")] use api_models::payment_methods::PaymentMethodsData; use api_models::{ payment_methods::PaymentMethodDataWalletInfo, payments::ConnectorMandateReferenceId, }; use common_enums::{ConnectorMandateStatus, PaymentMethod}; use common_types::callback_mapper::CallbackMapperData; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, Encode, ValueExt}, id_type, metrics::utils::record_operation_time, pii, }; use diesel_models::business_profile::ExternalVaultConnectorDetails; use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ callback_mapper::CallbackMapper, mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord}, payment_method_data, }; use masking::{ExposeInterface, Secret}; use router_env::{instrument, tracing}; use super::helpers; #[cfg(feature = "v1")] use crate::core::payment_methods::vault_payment_method_external_v1; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods::{ self, cards::{create_encrypted_data, PmCards}, network_tokenization, }, payments, }, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, payment_methods as pm_types, storage::enums as storage_enums, }, utils::{generate_id, OptionExt}, }; #[cfg(feature = "v1")] async fn save_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, business_profile: &domain::Profile, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { match &business_profile.external_vault_details { domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => { logger::info!("External vault is enabled, using vault_payment_method_external_v1"); Box::pin(save_in_locker_external( state, merchant_context, payment_method_request, card_detail, external_vault_details, )) .await } domain::ExternalVaultDetails::Skip => { // Use internal vault (locker) save_in_locker_internal(state, merchant_context, payment_method_request, card_detail) .await } } } pub struct SavePaymentMethodData<Req> { request: Req, response: Result<types::PaymentsResponseData, types::ErrorResponse>, payment_method_token: Option<types::PaymentMethodToken>, payment_method: PaymentMethod, attempt_status: common_enums::AttemptStatus, } impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>> for SavePaymentMethodData<Req> { fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self { Self { request: router_data.request.clone(), response: router_data.response.clone(), payment_method_token: router_data.payment_method_token.clone(), payment_method: router_data.payment_method, attempt_status: router_data.status, } } } pub struct SavePaymentMethodDataResponse { pub payment_method_id: Option<String>, pub payment_method_status: Option<common_enums::PaymentMethodStatus>, pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn save_payment_method<FData>( state: &SessionState, connector_name: String, save_payment_method_data: SavePaymentMethodData<FData>, customer_id: Option<id_type::CustomerId>, merchant_context: &domain::MerchantContext, payment_method_type: Option<storage_enums::PaymentMethodType>, billing_name: Option<Secret<String>>, payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, business_profile: &domain::Profile, mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, payment_method_info: Option<domain::PaymentMethod>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { let mut pm_status = None; let cards = PmCards { state, merchant_context, }; match save_payment_method_data.response { Ok(responses) => { let db = &*state.store; let token_store = state .conf .tokenization .0 .get(&connector_name.to_string()) .map(|token_filter| token_filter.long_lived_token) .unwrap_or(false); let network_transaction_id = match &responses { types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => { network_txn_id.clone() } _ => None, }; let network_transaction_id = if save_payment_method_data.request.get_setup_future_usage() == Some(storage_enums::FutureUsage::OffSession) { if network_transaction_id.is_some() { network_transaction_id } else { logger::info!("Skip storing network transaction id"); None } } else { None }; let connector_token = if token_store { let tokens = save_payment_method_data .payment_method_token .to_owned() .get_required_value("payment_token")?; let token = match tokens { types::PaymentMethodToken::Token(connector_token) => connector_token.expose(), types::PaymentMethodToken::ApplePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Apple Pay Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::PazeDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Paze Decrypt token is not supported".to_string(), })? } types::PaymentMethodToken::GooglePayDecrypt(_) => { Err(errors::ApiErrorResponse::NotSupported { message: "Google Pay Decrypt token is not supported".to_string(), })? } }; Some((connector_name, token)) } else { None }; let mandate_data_customer_acceptance = save_payment_method_data .request .get_setup_mandate_details() .and_then(|mandate_data| mandate_data.customer_acceptance.clone()); let customer_acceptance = save_payment_method_data .request .get_customer_acceptance() .or(mandate_data_customer_acceptance.clone()) .map(|ca| ca.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = match responses { types::PaymentsResponseData::TransactionResponse { mandate_reference, .. } => { if let Some(ref mandate_ref) = *mandate_reference { ( mandate_ref.connector_mandate_id.clone(), mandate_ref.mandate_metadata.clone(), mandate_ref.connector_mandate_request_reference_id.clone(), ) } else { (None, None, None) } } _ => (None, None, None), }; let pm_id = if customer_acceptance.is_some() { let payment_method_data = save_payment_method_data.request.get_payment_method_data(); let payment_method_create_request = payment_methods::get_payment_method_create_request( Some(&payment_method_data), Some(save_payment_method_data.payment_method), payment_method_type, &customer_id.clone(), billing_name, payment_method_billing_address, ) .await?; let payment_methods_data = &save_payment_method_data.request.get_payment_method_data(); let co_badged_card_data = payment_methods_data.get_co_badged_card_data(); let customer_id = customer_id.to_owned().get_required_value("customer_id")?; let merchant_id = merchant_context.get_merchant_account().get_id(); let is_network_tokenization_enabled = business_profile.is_network_tokenization_enabled; let ( (mut resp, duplication_check, network_token_requestor_ref_id), network_token_resp, ) = if !state.conf.locker.locker_enabled { let (res, dc) = skip_saving_card_in_locker( merchant_context, payment_method_create_request.to_owned(), ) .await?; ((res, dc, None), None) } else { let payment_method_status = common_enums::PaymentMethodStatus::from( save_payment_method_data.attempt_status, ); pm_status = Some(payment_method_status); save_card_and_network_token_in_locker( state, customer_id.clone(), payment_method_status, payment_method_data.clone(), vault_operation, payment_method_info, merchant_context, payment_method_create_request.clone(), is_network_tokenization_enabled, business_profile, ) .await? }; let network_token_locker_id = match network_token_resp { Some(ref token_resp) => { if network_token_requestor_ref_id.is_some() { Some(token_resp.payment_method_id.clone()) } else { None } } None => None, }; let optional_pm_details = match (resp.card.as_ref(), payment_method_data) { (Some(card), _) => Some(PaymentMethodsData::Card( CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)), )), ( _, domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(applepay)), ) => Some(PaymentMethodsData::WalletDetails( PaymentMethodDataWalletInfo::from(applepay), )), ( _, domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)), ) => Some(PaymentMethodsData::WalletDetails( PaymentMethodDataWalletInfo::from(googlepay), )), _ => None, }; let key_manager_state = state.into(); let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = optional_pm_details .async_map(|pm| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; let pm_network_token_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = match network_token_resp { Some(token_resp) => { let pm_token_details = token_resp.card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), None, ))) }); pm_token_details .async_map(|pm_card| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm_card, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")? } None => None, }; let encrypted_payment_method_billing_address: Option< Encryptable<Secret<serde_json::Value>>, > = payment_method_billing_address .async_map(|address| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), address.clone(), ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method billing address")?; let mut payment_method_id = resp.payment_method_id.clone(); let mut locker_id = None; let (external_vault_details, vault_type) = match &business_profile.external_vault_details{ hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => { (Some(external_vault_connector_details), Some(common_enums::VaultType::External)) }, hyperswitch_domain_models::business_profile::ExternalVaultDetails::Skip => (None, Some(common_enums::VaultType::Internal)), }; let external_vault_mca_id = external_vault_details .map(|connector_details| connector_details.vault_connector_id.clone()); let vault_source_details = domain::PaymentMethodVaultSourceDetails::try_from(( vault_type, external_vault_mca_id, )) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to create vault source details")?; match duplication_check { Some(duplication_check) => match duplication_check { payment_methods::transformers::DataDuplicationCheck::Duplicated => { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context .get_merchant_account() .storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id.clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; match payment_method { Ok(pm) => { let pm_metadata = create_payment_method_metadata( pm.metadata.as_ref(), connector_token, )?; payment_methods::cards::update_payment_method_metadata_and_last_used( state, merchant_context.get_merchant_key_store(), db, pm.clone(), pm_metadata, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Err(err) => { if err.current_context().is_db_not_found() { let pm_metadata = create_payment_method_metadata(None, connector_token)?; cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() }) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable("Error while finding payment method") }?; } }; } payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { if let Some(card) = payment_method_create_request.card.clone() { let payment_method = { let existing_pm_by_pmid = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context.get_merchant_account().storage_scheme, ) .await; if let Err(err) = existing_pm_by_pmid { if err.current_context().is_db_not_found() { locker_id = Some(payment_method_id.clone()); let existing_pm_by_locker_id = db .find_payment_method_by_locker_id( &(state.into()), merchant_context.get_merchant_key_store(), &payment_method_id, merchant_context .get_merchant_account() .storage_scheme, ) .await; match &existing_pm_by_locker_id { Ok(pm) => { payment_method_id .clone_from(&pm.payment_method_id); } Err(_) => { payment_method_id = generate_id(consts::ID_LENGTH, "pm") } }; existing_pm_by_locker_id } else { Err(err) } } else { existing_pm_by_pmid } }; resp.payment_method_id = payment_method_id; let existing_pm = match payment_method { Ok(pm) => { let mandate_details = pm .connector_mandate_details .clone() .map(|val| { val.parse_value::<PaymentsMandateReference>( "PaymentsMandateReference", ) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; if let Some((mandate_details, merchant_connector_id)) = mandate_details.zip(merchant_connector_id) { let connector_mandate_details = update_connector_mandate_details_status( merchant_connector_id, mandate_details, ConnectorMandateStatus::Inactive, )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, merchant_context.get_merchant_key_store(), db, pm.clone(), connector_mandate_details, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } Ok(pm) } Err(err) => { if err.current_context().is_db_not_found() { cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, resp.metadata.clone().map(|val| val.expose()), customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network.map(|card_network| { card_network.to_string() }) }), network_token_requestor_ref_id, network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Error while finding payment method", ) } } }?; cards .delete_card_from_locker( &customer_id, merchant_id, existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ) .await?; let add_card_resp = cards .add_card_hs( payment_method_create_request, &card, &customer_id, api::enums::LockerChoice::HyperswitchCardVault, Some( existing_pm .locker_id .as_ref() .unwrap_or(&existing_pm.payment_method_id), ), ) .await; if let Err(err) = add_card_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), merchant_context.get_merchant_key_store(), merchant_id, &resp.payment_method_id, ) .await .to_not_found_response( errors::ApiErrorResponse::PaymentMethodNotFound, )?; Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed while updating card metadata changes", ))? }; let existing_pm_data = cards .get_card_details_without_locker_fallback(&existing_pm) .await?; // scheme should be updated in case of co-badged cards let card_scheme = card .card_network .clone() .map(|card_network| card_network.to_string()) .or(existing_pm_data.scheme.clone()); let updated_card = Some(CardDetailFromLocker { scheme: card_scheme.clone(), last4_digits: Some(card.card_number.get_last4()), issuer_country: card .card_issuing_country .or(existing_pm_data.issuer_country), card_isin: Some(card.card_number.get_card_isin()), card_number: Some(card.card_number), expiry_month: Some(card.card_exp_month), expiry_year: Some(card.card_exp_year), card_token: None, card_fingerprint: None, card_holder_name: card .card_holder_name .or(existing_pm_data.card_holder_name), nick_name: card.nick_name.or(existing_pm_data.nick_name), card_network: card .card_network .or(existing_pm_data.card_network), card_issuer: card.card_issuer.or(existing_pm_data.card_issuer), card_type: card.card_type.or(existing_pm_data.card_type), saved_to_locker: true, }); let updated_pmd = updated_card.as_ref().map(|card| { PaymentMethodsData::Card(CardDetailsPaymentMethod::from(( card.clone(), co_badged_card_data, ))) }); let pm_data_encrypted: Option< Encryptable<Secret<serde_json::Value>>, > = updated_pmd .async_map(|pmd| { create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pmd, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt payment method data")?; payment_methods::cards::update_payment_method_and_last_used( state, merchant_context.get_merchant_key_store(), db, existing_pm, pm_data_encrypted.map(Into::into), merchant_context.get_merchant_account().storage_scheme, card_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; } } }, None => { let customer_saved_pm_option = if payment_method_type .map(|payment_method_type_value| { payment_method_type_value .should_check_for_customer_saved_payment_method_type() }) .unwrap_or(false) { match state .store .find_payment_method_by_customer_id_merchant_id_list( &(state.into()), merchant_context.get_merchant_key_store(), &customer_id, merchant_id, None, ) .await { Ok(customer_payment_methods) => Ok(customer_payment_methods .iter() .find(|payment_method| { payment_method.get_payment_method_subtype() == payment_method_type }) .cloned()), Err(error) => { if error.current_context().is_db_not_found() { Ok(None) } else { Err(error) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "failed to find payment methods for a customer", ) } } } } else { Ok(None) }?; if let Some(customer_saved_pm) = customer_saved_pm_option { payment_methods::cards::update_last_used_at( &customer_saved_pm, state, merchant_context.get_merchant_account().storage_scheme, merchant_context.get_merchant_key_store(), ) .await .map_err(|e| { logger::error!("Failed to update last used at: {:?}", e); }) .ok(); resp.payment_method_id = customer_saved_pm.payment_method_id; } else { let pm_metadata = create_payment_method_metadata(None, connector_token)?; locker_id = resp.payment_method.and_then(|pm| { if pm == PaymentMethod::Card { Some(resp.payment_method_id) } else { None } }); resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm"); cards .create_payment_method( &payment_method_create_request, &customer_id, &resp.payment_method_id, locker_id, merchant_id, pm_metadata, customer_acceptance, pm_data_encrypted, None, pm_status, network_transaction_id, encrypted_payment_method_billing_address, resp.card.and_then(|card| { card.card_network .map(|card_network| card_network.to_string()) }), network_token_requestor_ref_id.clone(), network_token_locker_id, pm_network_token_data_encrypted, Some(vault_source_details), ) .await?; match network_token_requestor_ref_id { Some(network_token_requestor_ref_id) => { //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks let callback_mapper_data = CallbackMapperData::NetworkTokenWebhook { merchant_id: merchant_context .get_merchant_account() .get_id() .clone(), customer_id, payment_method_id: resp.payment_method_id.clone(), }; let callback_mapper = CallbackMapper::new( network_token_requestor_ref_id, common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID, callback_mapper_data, common_utils::date_time::now(), common_utils::date_time::now(), ); db.insert_call_back_mapper(callback_mapper) .await .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "Failed to insert in Callback Mapper table", )?; } None => { logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion"); } }; }; } } Some(resp.payment_method_id) } else { None }; // check if there needs to be a config if yes then remove it to a different place let connector_mandate_reference_id = if connector_mandate_id.is_some() { if let Some(ref mut record) = original_connector_mandate_reference_id { record.update( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, ); Some(record.clone()) } else { Some(ConnectorMandateReferenceId::new( connector_mandate_id, None, None, mandate_metadata, connector_mandate_request_reference_id, )) } } else { None }; Ok(SavePaymentMethodDataResponse { payment_method_id: pm_id, payment_method_status: pm_status, connector_mandate_reference_id, }) } Err(_) => Ok(SavePaymentMethodDataResponse { payment_method_id: None, payment_method_status: None, connector_mandate_reference_id: None, }), } } #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn save_payment_method<FData>( _state: &SessionState, _connector_name: String, _save_payment_method_data: SavePaymentMethodData<FData>, _customer_id: Option<id_type::CustomerId>, _merchant_context: &domain::MerchantContext, _payment_method_type: Option<storage_enums::PaymentMethodType>, _billing_name: Option<Secret<String>>, _payment_method_billing_address: Option<&api::Address>, _business_profile: &domain::Profile, _connector_mandate_request_reference_id: Option<String>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, { todo!() } #[cfg(feature = "v1")] pub async fn pre_payment_tokenization( state: &SessionState, customer_id: id_type::CustomerId, card: &payment_method_data::Card, ) -> RouterResult<(Option<pm_types::TokenResponse>, Option<String>)> { let network_tokenization_supported_card_networks = &state .conf .network_tokenization_supported_card_networks .card_networks; if card .card_network .as_ref() .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { let optional_card_cvc = Some(card.card_cvc.clone()); let card_detail = payment_method_data::CardDetail::from(card); match network_tokenization::make_card_network_tokenization_request( state, &card_detail, optional_card_cvc, &customer_id, ) .await { Ok((_token_response, network_token_requestor_ref_id)) => { let network_tokenization_service = &state.conf.network_tokenization_service; match ( network_token_requestor_ref_id.clone(), network_tokenization_service, ) { (Some(token_ref), Some(network_tokenization_service)) => { let network_token = record_operation_time( async { network_tokenization::get_network_token( state, customer_id, token_ref, network_tokenization_service.get_inner(), ) .await }, &metrics::FETCH_NETWORK_TOKEN_TIME, &[], ) .await; match network_token { Ok(token_response) => { Ok((Some(token_response), network_token_requestor_ref_id.clone())) } _ => { logger::error!( "Error while fetching token from tokenization service" ); Ok((None, network_token_requestor_ref_id.clone())) } } } (Some(token_ref), _) => Ok((None, Some(token_ref))), _ => Ok((None, None)), } } Err(err) => { logger::error!("Failed to tokenize card: {:?}", err); Ok((None, None)) //None will be returned in case of error when calling network tokenization service } } } else { Ok((None, None)) //None will be returned in case of unsupported card network. } } #[cfg(feature = "v1")] async fn skip_saving_card_in_locker( merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = payment_method_request .clone() .customer_id .clone() .get_required_value("customer_id")?; let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let last4_digits = payment_method_request .card .clone() .map(|c| c.card_number.get_last4()); let card_isin = payment_method_request .card .clone() .map(|c| c.card_number.get_card_isin()); match payment_method_request.card.clone() { Some(card) => { let card_detail = CardDetailFromLocker { scheme: None, issuer_country: card.card_issuing_country.clone(), last4_digits: last4_digits.clone(), card_number: None, expiry_month: Some(card.card_exp_month.clone()), expiry_year: Some(card.card_exp_year), card_token: None, card_holder_name: card.card_holder_name.clone(), card_fingerprint: None, nick_name: None, card_isin: card_isin.clone(), card_issuer: card.card_issuer.clone(), card_network: card.card_network.clone(), card_type: card.card_type.clone(), saved_to_locker: false, }; let pm_resp = api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), customer_id: Some(customer_id), payment_method_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: Some(card_detail), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), metadata: None, created: Some(common_utils::date_time::now()), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((pm_resp, None)) } None => { let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } } #[cfg(feature = "v2")] async fn skip_saving_card_in_locker( merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { todo!() } #[cfg(feature = "v1")] pub async fn save_in_locker_internal( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { payment_method_request.validate()?; let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; match (payment_method_request.card.clone(), card_detail) { (_, Some(card)) | (Some(card), _) => Box::pin( PmCards { state, merchant_context, } .add_card_to_locker(payment_method_request, &card, &customer_id, None), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed"), _ => { let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.clone(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, #[cfg(feature = "payouts")] bank_transfer: None, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } } #[cfg(feature = "v1")] pub async fn save_in_locker_external( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, card_detail: Option<api::CardDetail>, external_vault_connector_details: &ExternalVaultConnectorDetails, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; // For external vault, we need to convert the card data to PaymentMethodVaultingData if let Some(card) = card_detail { let payment_method_vaulting_data = hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card.clone()); let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone(); let key_manager_state = &state.into(); let merchant_connector_account_details = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &external_vault_mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: external_vault_mca_id.get_string_repr().to_string(), })?; // Call vault_payment_method_external_v1 let vault_response = vault_payment_method_external_v1( state, &payment_method_vaulting_data, merchant_context.get_merchant_account(), merchant_connector_account_details, ) .await?; let payment_method_id = vault_response.vault_id.to_string().to_owned(); let card_detail = CardDetailFromLocker::from(card); let pm_resp = api::PaymentMethodResponse { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: Some(customer_id), payment_method_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, card: Some(card_detail), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), metadata: None, created: Some(common_utils::date_time::now()), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((pm_resp, None)) } else { //Similar implementation is done for save in locker internal let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), customer_id: Some(customer_id), payment_method_id: pm_id, payment_method: payment_method_request.payment_method, payment_method_type: payment_method_request.payment_method_type, #[cfg(feature = "payouts")] bank_transfer: None, card: None, metadata: None, created: Some(common_utils::date_time::now()), recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] last_used_at: Some(common_utils::date_time::now()), client_secret: None, }; Ok((payment_method_response, None)) } } #[cfg(feature = "v2")] pub async fn save_in_locker_internal( _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, )> { todo!() } #[cfg(feature = "v2")] pub async fn save_network_token_in_locker( _state: &SessionState, _merchant_context: &domain::MerchantContext, _card_data: &domain::Card, _payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, )> { todo!() } #[cfg(feature = "v1")] pub async fn save_network_token_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, card_data: &payment_method_data::Card, network_token_data: Option<api::CardDetail>, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, )> { let customer_id = payment_method_request .customer_id .clone() .get_required_value("customer_id")?; let network_tokenization_supported_card_networks = &state .conf .network_tokenization_supported_card_networks .card_networks; match network_token_data { Some(nt_data) => { let (res, dc) = Box::pin( PmCards { state, merchant_context, } .add_card_to_locker( payment_method_request, &nt_data, &customer_id, None, ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token Failed")?; Ok((Some(res), dc, None)) } None => { if card_data .card_network .as_ref() .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { let optional_card_cvc = Some(card_data.card_cvc.clone()); match network_tokenization::make_card_network_tokenization_request( state, &domain::CardDetail::from(card_data), optional_card_cvc, &customer_id, ) .await { Ok((token_response, network_token_requestor_ref_id)) => { // Only proceed if the tokenization was successful let network_token_data = api::CardDetail { card_number: token_response.token.clone(), card_exp_month: token_response.token_expiry_month.clone(), card_exp_year: token_response.token_expiry_year.clone(), card_holder_name: None, nick_name: None, card_issuing_country: None, card_network: Some(token_response.card_brand.clone()), card_issuer: None, card_type: None, }; let (res, dc) = Box::pin( PmCards { state, merchant_context, } .add_card_to_locker( payment_method_request, &network_token_data, &customer_id, None, ), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token Failed")?; Ok((Some(res), dc, network_token_requestor_ref_id)) } Err(err) => { logger::error!("Failed to tokenize card: {:?}", err); Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service } } } else { Ok((None, None, None)) //None will be returned in case of unsupported card network. } } } } pub fn handle_tokenization_response<F, Req>( resp: &mut types::RouterData<F, Req, types::PaymentsResponseData>, ) { let response = resp.response.clone(); if let Err(err) = response { if let Some(secret_metadata) = &err.connector_metadata { let metadata = secret_metadata.clone().expose(); if let Some(token) = metadata .get("payment_method_token") .and_then(|t| t.as_str()) { resp.response = Ok(types::PaymentsResponseData::TokenizationResponse { token: token.to_string(), }); } } } } pub fn create_payment_method_metadata( metadata: Option<&pii::SecretSerdeValue>, connector_token: Option<(String, String)>, ) -> RouterResult<Option<serde_json::Value>> { let mut meta = match metadata { None => serde_json::Map::new(), Some(meta) => { let metadata = meta.clone().expose(); let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata .parse_value("Map<String, Value>") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse the metadata")?; existing_metadata } }; Ok(connector_token.and_then(|connector_and_token| { meta.insert( connector_and_token.0, serde_json::Value::String(connector_and_token.1), ) })) } pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, pm_token_request_data: types::PaymentMethodTokenizationData, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult> { if should_continue_payment { match tokenization_action { payments::TokenizationAction::TokenizeInConnector => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let pm_token_response_data: Result< types::PaymentsResponseData, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let pm_token_router_data = helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( router_data.clone(), pm_token_request_data, pm_token_response_data, ); router_data .request .set_session_token(pm_token_router_data.session_token.clone()); let mut resp = services::execute_connector_processing_step( state, connector_integration, &pm_token_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; // checks for metadata in the ErrorResponse, if present bypasses it and constructs an Ok response handle_tokenization_response(&mut resp); metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("payment_method", router_data.payment_method.to_string()), ), ); let payment_token_resp = resp.response.map(|res| { if let types::PaymentsResponseData::TokenizationResponse { token } = res { Some(token) } else { None } }); Ok(types::PaymentMethodTokenResult { payment_method_token_result: payment_token_resp, is_payment_method_tokenization_performed: true, connector_response: resp.connector_response.clone(), }) } _ => Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }), } } else { logger::debug!("Skipping connector tokenization based on should_continue_payment flag"); Ok(types::PaymentMethodTokenResult { payment_method_token_result: Ok(None), is_payment_method_tokenization_performed: false, connector_response: None, }) } } pub fn update_router_data_with_payment_method_token_result<F: Clone, T>( payment_method_token_result: types::PaymentMethodTokenResult, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, is_retry_payment: bool, should_continue_further: bool, ) -> bool { if payment_method_token_result.is_payment_method_tokenization_performed { match payment_method_token_result.payment_method_token_result { Ok(pm_token_result) => { router_data.payment_method_token = pm_token_result.map(|pm_token| { hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new( pm_token, )) }); if router_data.connector_response.is_none() { router_data.connector_response = payment_method_token_result.connector_response.clone(); } true } Err(err) => { if is_retry_payment { router_data.response = Err(err); false } else { logger::debug!(payment_method_tokenization_error=?err); true } } } } else { should_continue_further } } #[cfg(feature = "v1")] pub fn add_connector_mandate_details_in_payment_method( payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, mandate_metadata: Option<Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, ) -> Option<CommonMandateReference> { let mut mandate_details = HashMap::new(); if let Some((mca_id, connector_mandate_id)) = merchant_connector_id.clone().zip(connector_mandate_id) { mandate_details.insert( mca_id, PaymentsMandateReferenceRecord { connector_mandate_id, payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata, connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id, }, ); Some(CommonMandateReference { payments: Some(PaymentsMandateReference(mandate_details)), payouts: None, }) } else { None } } #[allow(clippy::too_many_arguments)] #[cfg(feature = "v1")] pub fn update_connector_mandate_details( mandate_details: Option<CommonMandateReference>, payment_method_type: Option<storage_enums::PaymentMethodType>, authorized_amount: Option<i64>, authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, mandate_metadata: Option<Secret<serde_json::Value>>, connector_mandate_request_reference_id: Option<String>, ) -> RouterResult<Option<CommonMandateReference>> { let mandate_reference = match mandate_details .as_ref() .and_then(|common_mandate| common_mandate.payments.clone()) { Some(mut payment_mandate_reference) => { if let Some((mca_id, connector_mandate_id)) = merchant_connector_id.clone().zip(connector_mandate_id) { let updated_record = PaymentsMandateReferenceRecord { connector_mandate_id: connector_mandate_id.clone(), payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata: mandate_metadata.clone(), connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id: connector_mandate_request_reference_id .clone(), }; payment_mandate_reference .entry(mca_id) .and_modify(|pm| *pm = updated_record) .or_insert(PaymentsMandateReferenceRecord { connector_mandate_id, payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, mandate_metadata: mandate_metadata.clone(), connector_mandate_status: Some(ConnectorMandateStatus::Active), connector_mandate_request_reference_id, }); let payout_data = mandate_details.and_then(|common_mandate| common_mandate.payouts); Some(CommonMandateReference { payments: Some(payment_mandate_reference), payouts: payout_data, }) } else { None } } None => add_connector_mandate_details_in_payment_method( payment_method_type, authorized_amount, authorized_currency, merchant_connector_id, connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id, ), }; Ok(mandate_reference) } #[cfg(feature = "v1")] pub fn update_connector_mandate_details_status( merchant_connector_id: id_type::MerchantConnectorAccountId, mut payment_mandate_reference: PaymentsMandateReference, status: ConnectorMandateStatus, ) -> RouterResult<Option<CommonMandateReference>> { let mandate_reference = { payment_mandate_reference .entry(merchant_connector_id) .and_modify(|pm| { let update_rec = PaymentsMandateReferenceRecord { connector_mandate_id: pm.connector_mandate_id.clone(), payment_method_type: pm.payment_method_type, original_payment_authorized_amount: pm.original_payment_authorized_amount, original_payment_authorized_currency: pm.original_payment_authorized_currency, mandate_metadata: pm.mandate_metadata.clone(), connector_mandate_status: Some(status), connector_mandate_request_reference_id: pm .connector_mandate_request_reference_id .clone(), }; *pm = update_rec }); Some(payment_mandate_reference) }; Ok(Some(CommonMandateReference { payments: mandate_reference, payouts: None, })) } #[cfg(feature = "v2")] pub async fn add_token_for_payment_method( router_data: &mut types::RouterData< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, >, payment_method_data_request: types::PaymentMethodTokenizationData, state: SessionState, merchant_connector_account_details: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, ) -> RouterResult<types::PspTokenResult> { let connector_id = merchant_connector_account_details.id.clone(); let connector_data = api::ConnectorData::get_connector_by_name( &(state.conf.connectors), &merchant_connector_account_details .connector_name .to_string(), api::GetToken::Connector, Some(connector_id.clone()), )?; let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > = connector_data.connector.get_connector_integration(); let payment_method_token_response_data_type: Result< types::PaymentsResponseData, types::ErrorResponse, > = Err(types::ErrorResponse::default()); let payment_method_token_router_data = helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>( router_data.clone(), payment_method_data_request.clone(), payment_method_token_response_data_type, ); let connector_integration_response = services::execute_connector_processing_step( &state, connector_integration, &payment_method_token_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_payment_failed_response()?; let payment_token_response = connector_integration_response.response.map(|res| { if let types::PaymentsResponseData::TokenizationResponse { token } = res { Ok(token) } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get token from connector") } }); match payment_token_response { Ok(token) => Ok(types::PspTokenResult { token: Ok(token?) }), Err(error_response) => Ok(types::PspTokenResult { token: Err(error_response), }), } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn save_card_and_network_token_in_locker( state: &SessionState, customer_id: id_type::CustomerId, payment_method_status: common_enums::PaymentMethodStatus, payment_method_data: domain::PaymentMethodData, vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, payment_method_info: Option<domain::PaymentMethod>, merchant_context: &domain::MerchantContext, payment_method_create_request: api::PaymentMethodCreate, is_network_tokenization_enabled: bool, business_profile: &domain::Profile, ) -> RouterResult<( ( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, Option<String>, ), Option<api_models::payment_methods::PaymentMethodResponse>, )> { let network_token_requestor_reference_id = payment_method_info .and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone()); match vault_operation { Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardData(card)) => { let card_data = api::CardDetail::from(card.card_data.clone()); if let (Some(nt_ref_id), Some(tokenization_service)) = ( card.network_token_req_ref_id.clone(), &state.conf.network_tokenization_service, ) { let _ = record_operation_time( async { network_tokenization::delete_network_token_from_tokenization_service( state, nt_ref_id.clone(), &customer_id, tokenization_service.get_inner(), ) .await }, &metrics::DELETE_NETWORK_TOKEN_TIME, &[], ) .await; } let (res, dc) = Box::pin(save_in_locker( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), business_profile, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; Ok(((res, dc, None), None)) } Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardAndNetworkTokenData( save_card_and_network_token_data, )) => { let card_data = api::CardDetail::from(save_card_and_network_token_data.card_data.clone()); let network_token_data = api::CardDetail::from( save_card_and_network_token_data .network_token .network_token_data .clone(), ); if payment_method_status == common_enums::PaymentMethodStatus::Active { let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker( state, merchant_context, &save_card_and_network_token_data.card_data, Some(network_token_data), payment_method_create_request.clone(), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Network Token In Locker Failed")?; Ok(( (res, dc, network_token_requestor_reference_id), network_token_resp, )) } else { if let (Some(nt_ref_id), Some(tokenization_service)) = ( network_token_requestor_reference_id.clone(), &state.conf.network_tokenization_service, ) { let _ = record_operation_time( async { network_tokenization::delete_network_token_from_tokenization_service( state, nt_ref_id.clone(), &customer_id, tokenization_service.get_inner(), ) .await }, &metrics::DELETE_NETWORK_TOKEN_TIME, &[], ) .await; } let (res, dc) = Box::pin(save_in_locker_internal( state, merchant_context, payment_method_create_request.to_owned(), Some(card_data), )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; Ok(((res, dc, None), None)) } } _ => { let card_data = payment_method_create_request.card.clone(); let (res, dc) = Box::pin(save_in_locker( state, merchant_context, payment_method_create_request.to_owned(), card_data, business_profile, )) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card In Locker Failed")?; if is_network_tokenization_enabled { match &payment_method_data { domain::PaymentMethodData::Card(card) => { let ( network_token_resp, _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice network_token_requestor_ref_id, ) = Box::pin(save_network_token_in_locker( state, merchant_context, card, None, payment_method_create_request.clone(), )) .await?; Ok(( (res, dc, network_token_requestor_ref_id), network_token_resp, )) } _ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods } } else { Ok(((res, dc, None), None)) } } } }
{ "crate": "router", "file": "crates/router/src/core/payments/tokenization.rs", "file_size": 86976, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-7829879502373524080
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payment_methods/vault.rs // File size: 84482 bytes use common_enums::PaymentMethodType; #[cfg(feature = "v2")] use common_utils::request; use common_utils::{ crypto::{DecodeMessage, EncodeMessage, GcmAes256}, ext_traits::{BytesExt, Encode}, generate_id_with_default_len, id_type, pii::Email, }; use error_stack::{report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::router_flow_types::{ ExternalVaultDeleteFlow, ExternalVaultRetrieveFlow, }; use hyperswitch_domain_models::{ router_data_v2::flow_common_types::VaultConnectorFlowData, types::VaultRouterData, }; use masking::PeekInterface; use router_env::{instrument, tracing}; use scheduler::{types::process_data, utils as process_tracker_utils}; #[cfg(feature = "payouts")] use crate::types::api::payouts; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, CustomResult, RouterResult}, payments, utils as core_utils, }, db, logger, routes::{self, metrics}, services::{self, connector_integration_interface::RouterDataConversion}, types::{ self, api, domain, storage::{self, enums}, }, utils::StringExt, }; #[cfg(feature = "v2")] use crate::{ core::{ errors::StorageErrorExt, payment_methods::{transformers as pm_transforms, utils}, payments::{self as payments_core, helpers as payment_helpers}, }, headers, settings, types::payment_methods as pm_types, utils::{ext_traits::OptionExt, ConnectorResponseExt}, }; const VAULT_SERVICE_NAME: &str = "CARD"; pub struct SupplementaryVaultData { pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } pub trait Vaultable: Sized { fn get_value1( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError>; fn get_value2( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { Ok(String::new()) } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError>; } impl Vaultable for domain::Card { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = domain::TokenizedCardValue1 { card_number: self.card_number.peek().clone(), exp_year: self.card_exp_year.peek().clone(), exp_month: self.card_exp_month.peek().clone(), nickname: self.nick_name.as_ref().map(|name| name.peek().clone()), card_last_four: None, card_token: None, card_holder_name: self.card_holder_name.clone(), }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value1") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = domain::TokenizedCardValue2 { card_security_code: Some(self.card_cvc.peek().clone()), card_fingerprint: None, external_id: None, customer_id, payment_method_id: None, }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: domain::TokenizedCardValue1 = value1 .parse_struct("TokenizedCardValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into card value1")?; let value2: domain::TokenizedCardValue2 = value2 .parse_struct("TokenizedCardValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into card value2")?; let card = Self { card_number: cards::CardNumber::try_from(value1.card_number) .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Invalid card number format from the mock locker")?, card_exp_month: value1.exp_month.into(), card_exp_year: value1.exp_year.into(), card_cvc: value2.card_security_code.unwrap_or_default().into(), card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: value1.nickname.map(masking::Secret::new), card_holder_name: value1.card_holder_name, co_badged_card_data: None, }; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: value2.payment_method_id, }; Ok((card, supp_data)) } } impl Vaultable for domain::BankTransferData { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = domain::TokenizedBankTransferValue1 { data: self.to_owned(), }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank transfer data") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = domain::TokenizedBankTransferValue2 { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank transfer supplementary data") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: domain::TokenizedBankTransferValue1 = value1 .parse_struct("TokenizedBankTransferValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into bank transfer data")?; let value2: domain::TokenizedBankTransferValue2 = value2 .parse_struct("TokenizedBankTransferValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into supplementary bank transfer data")?; let bank_transfer_data = value1.data; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((bank_transfer_data, supp_data)) } } impl Vaultable for domain::WalletData { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = domain::TokenizedWalletValue1 { data: self.to_owned(), }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data value1") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = domain::TokenizedWalletValue2 { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: domain::TokenizedWalletValue1 = value1 .parse_struct("TokenizedWalletValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data value1")?; let value2: domain::TokenizedWalletValue2 = value2 .parse_struct("TokenizedWalletValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data value2")?; let wallet = value1.data; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((wallet, supp_data)) } } impl Vaultable for domain::BankRedirectData { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = domain::TokenizedBankRedirectValue1 { data: self.to_owned(), }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank redirect data") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = domain::TokenizedBankRedirectValue2 { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank redirect supplementary data") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: domain::TokenizedBankRedirectValue1 = value1 .parse_struct("TokenizedBankRedirectValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into bank redirect data")?; let value2: domain::TokenizedBankRedirectValue2 = value2 .parse_struct("TokenizedBankRedirectValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into supplementary bank redirect data")?; let bank_transfer_data = value1.data; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((bank_transfer_data, supp_data)) } } impl Vaultable for domain::BankDebitData { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = domain::TokenizedBankDebitValue1 { data: self.to_owned(), }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank debit data") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = domain::TokenizedBankDebitValue2 { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode bank debit supplementary data") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: domain::TokenizedBankDebitValue1 = value1 .parse_struct("TokenizedBankDebitValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into bank debit data")?; let value2: domain::TokenizedBankDebitValue2 = value2 .parse_struct("TokenizedBankDebitValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into supplementary bank debit data")?; let bank_transfer_data = value1.data; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((bank_transfer_data, supp_data)) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum VaultPaymentMethod { Card(String), Wallet(String), BankTransfer(String), BankRedirect(String), BankDebit(String), } impl Vaultable for domain::PaymentMethodData { fn get_value1( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = match self { Self::Card(card) => VaultPaymentMethod::Card(card.get_value1(customer_id)?), Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value1(customer_id)?), Self::BankTransfer(bank_transfer) => { VaultPaymentMethod::BankTransfer(bank_transfer.get_value1(customer_id)?) } Self::BankRedirect(bank_redirect) => { VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?) } Self::BankDebit(bank_debit) => { VaultPaymentMethod::BankDebit(bank_debit.get_value1(customer_id)?) } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported")?, }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payment method value1") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = match self { Self::Card(card) => VaultPaymentMethod::Card(card.get_value2(customer_id)?), Self::Wallet(wallet) => VaultPaymentMethod::Wallet(wallet.get_value2(customer_id)?), Self::BankTransfer(bank_transfer) => { VaultPaymentMethod::BankTransfer(bank_transfer.get_value2(customer_id)?) } Self::BankRedirect(bank_redirect) => { VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?) } Self::BankDebit(bank_debit) => { VaultPaymentMethod::BankDebit(bank_debit.get_value2(customer_id)?) } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported")?, }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payment method value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: VaultPaymentMethod = value1 .parse_struct("PaymentMethodValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into payment method value 1")?; let value2: VaultPaymentMethod = value2 .parse_struct("PaymentMethodValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into payment method value 2")?; match (value1, value2) { (VaultPaymentMethod::Card(mvalue1), VaultPaymentMethod::Card(mvalue2)) => { let (card, supp_data) = domain::Card::from_values(mvalue1, mvalue2)?; Ok((Self::Card(card), supp_data)) } (VaultPaymentMethod::Wallet(mvalue1), VaultPaymentMethod::Wallet(mvalue2)) => { let (wallet, supp_data) = domain::WalletData::from_values(mvalue1, mvalue2)?; Ok((Self::Wallet(wallet), supp_data)) } ( VaultPaymentMethod::BankTransfer(mvalue1), VaultPaymentMethod::BankTransfer(mvalue2), ) => { let (bank_transfer, supp_data) = domain::BankTransferData::from_values(mvalue1, mvalue2)?; Ok((Self::BankTransfer(Box::new(bank_transfer)), supp_data)) } ( VaultPaymentMethod::BankRedirect(mvalue1), VaultPaymentMethod::BankRedirect(mvalue2), ) => { let (bank_redirect, supp_data) = domain::BankRedirectData::from_values(mvalue1, mvalue2)?; Ok((Self::BankRedirect(bank_redirect), supp_data)) } (VaultPaymentMethod::BankDebit(mvalue1), VaultPaymentMethod::BankDebit(mvalue2)) => { let (bank_debit, supp_data) = domain::BankDebitData::from_values(mvalue1, mvalue2)?; Ok((Self::BankDebit(bank_debit), supp_data)) } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported"), } } } #[cfg(feature = "payouts")] impl Vaultable for api::CardPayout { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = api::TokenizedCardValue1 { card_number: self.card_number.peek().clone(), exp_year: self.expiry_year.peek().clone(), exp_month: self.expiry_month.peek().clone(), name_on_card: self.card_holder_name.clone().map(|n| n.peek().to_string()), nickname: None, card_last_four: None, card_token: None, }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value1") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = api::TokenizedCardValue2 { card_security_code: None, card_fingerprint: None, external_id: None, customer_id, payment_method_id: None, }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode card value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: api::TokenizedCardValue1 = value1 .parse_struct("TokenizedCardValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into card value1")?; let value2: api::TokenizedCardValue2 = value2 .parse_struct("TokenizedCardValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into card value2")?; let card = Self { card_number: value1 .card_number .parse() .map_err(|_| errors::VaultError::FetchCardFailed)?, expiry_month: value1.exp_month.into(), expiry_year: value1.exp_year.into(), card_holder_name: value1.name_on_card.map(masking::Secret::new), }; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: value2.payment_method_id, }; Ok((card, supp_data)) } } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletSensitiveValues { pub email: Option<Email>, pub telephone_number: Option<masking::Secret<String>>, pub wallet_id: Option<masking::Secret<String>>, pub wallet_type: PaymentMethodType, pub dpan: Option<cards::CardNumber>, pub expiry_month: Option<masking::Secret<String>>, pub expiry_year: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletInsensitiveValues { pub customer_id: Option<id_type::CustomerId>, } #[cfg(feature = "payouts")] impl Vaultable for api::WalletPayout { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = match self { Self::Paypal(paypal_data) => TokenizedWalletSensitiveValues { email: paypal_data.email.clone(), telephone_number: paypal_data.telephone_number.clone(), wallet_id: paypal_data.paypal_id.clone(), wallet_type: PaymentMethodType::Paypal, dpan: None, expiry_month: None, expiry_year: None, card_holder_name: None, }, Self::Venmo(venmo_data) => TokenizedWalletSensitiveValues { email: None, telephone_number: venmo_data.telephone_number.clone(), wallet_id: None, wallet_type: PaymentMethodType::Venmo, dpan: None, expiry_month: None, expiry_year: None, card_holder_name: None, }, Self::ApplePayDecrypt(apple_pay_decrypt_data) => TokenizedWalletSensitiveValues { email: None, telephone_number: None, wallet_id: None, wallet_type: PaymentMethodType::ApplePay, dpan: Some(apple_pay_decrypt_data.dpan.clone()), expiry_month: Some(apple_pay_decrypt_data.expiry_month.clone()), expiry_year: Some(apple_pay_decrypt_data.expiry_year.clone()), card_holder_name: apple_pay_decrypt_data.card_holder_name.clone(), }, }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data - TokenizedWalletSensitiveValues") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = TokenizedWalletInsensitiveValues { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode data - TokenizedWalletInsensitiveValues") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: TokenizedWalletSensitiveValues = value1 .parse_struct("TokenizedWalletSensitiveValues") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data wallet_sensitive_data")?; let value2: TokenizedWalletInsensitiveValues = value2 .parse_struct("TokenizedWalletInsensitiveValues") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data wallet_insensitive_data")?; let wallet = match value1.wallet_type { PaymentMethodType::Paypal => Self::Paypal(api_models::payouts::Paypal { email: value1.email, telephone_number: value1.telephone_number, paypal_id: value1.wallet_id, }), PaymentMethodType::Venmo => Self::Venmo(api_models::payouts::Venmo { telephone_number: value1.telephone_number, }), PaymentMethodType::ApplePay => { match (value1.dpan, value1.expiry_month, value1.expiry_year) { (Some(dpan), Some(expiry_month), Some(expiry_year)) => { Self::ApplePayDecrypt(api_models::payouts::ApplePayDecrypt { dpan, expiry_month, expiry_year, card_holder_name: value1.card_holder_name, }) } _ => Err(errors::VaultError::ResponseDeserializationFailed)?, } } _ => Err(errors::VaultError::PayoutMethodNotSupported)?, }; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((wallet, supp_data)) } } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankSensitiveValues { pub bank_account_number: Option<masking::Secret<String>>, pub bank_routing_number: Option<masking::Secret<String>>, pub bic: Option<masking::Secret<String>>, pub bank_sort_code: Option<masking::Secret<String>>, pub iban: Option<masking::Secret<String>>, pub pix_key: Option<masking::Secret<String>>, pub tax_id: Option<masking::Secret<String>>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankInsensitiveValues { pub customer_id: Option<id_type::CustomerId>, pub bank_name: Option<String>, pub bank_country_code: Option<api::enums::CountryAlpha2>, pub bank_city: Option<String>, pub bank_branch: Option<String>, } #[cfg(feature = "payouts")] impl Vaultable for api::BankPayout { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let bank_sensitive_data = match self { Self::Ach(b) => TokenizedBankSensitiveValues { bank_account_number: Some(b.bank_account_number.clone()), bank_routing_number: Some(b.bank_routing_number.to_owned()), bic: None, bank_sort_code: None, iban: None, pix_key: None, tax_id: None, }, Self::Bacs(b) => TokenizedBankSensitiveValues { bank_account_number: Some(b.bank_account_number.to_owned()), bank_routing_number: None, bic: None, bank_sort_code: Some(b.bank_sort_code.to_owned()), iban: None, pix_key: None, tax_id: None, }, Self::Sepa(b) => TokenizedBankSensitiveValues { bank_account_number: None, bank_routing_number: None, bic: b.bic.to_owned(), bank_sort_code: None, iban: Some(b.iban.to_owned()), pix_key: None, tax_id: None, }, Self::Pix(bank_details) => TokenizedBankSensitiveValues { bank_account_number: Some(bank_details.bank_account_number.to_owned()), bank_routing_number: None, bic: None, bank_sort_code: None, iban: None, pix_key: Some(bank_details.pix_key.to_owned()), tax_id: bank_details.tax_id.to_owned(), }, }; bank_sensitive_data .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode data - bank_sensitive_data") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let bank_insensitive_data = match self { Self::Ach(b) => TokenizedBankInsensitiveValues { customer_id, bank_name: b.bank_name.to_owned(), bank_country_code: b.bank_country_code.to_owned(), bank_city: b.bank_city.to_owned(), bank_branch: None, }, Self::Bacs(b) => TokenizedBankInsensitiveValues { customer_id, bank_name: b.bank_name.to_owned(), bank_country_code: b.bank_country_code.to_owned(), bank_city: b.bank_city.to_owned(), bank_branch: None, }, Self::Sepa(bank_details) => TokenizedBankInsensitiveValues { customer_id, bank_name: bank_details.bank_name.to_owned(), bank_country_code: bank_details.bank_country_code.to_owned(), bank_city: bank_details.bank_city.to_owned(), bank_branch: None, }, Self::Pix(bank_details) => TokenizedBankInsensitiveValues { customer_id, bank_name: bank_details.bank_name.to_owned(), bank_country_code: None, bank_city: None, bank_branch: bank_details.bank_branch.to_owned(), }, }; bank_insensitive_data .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data bank_insensitive_data") } fn from_values( bank_sensitive_data: String, bank_insensitive_data: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let bank_sensitive_data: TokenizedBankSensitiveValues = bank_sensitive_data .parse_struct("TokenizedBankValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into bank data bank_sensitive_data")?; let bank_insensitive_data: TokenizedBankInsensitiveValues = bank_insensitive_data .parse_struct("TokenizedBankValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data bank_insensitive_data")?; let bank = match ( // ACH + BACS + PIX bank_sensitive_data.bank_account_number.to_owned(), bank_sensitive_data.bank_routing_number.to_owned(), // ACH bank_sensitive_data.bank_sort_code.to_owned(), // BACS // SEPA bank_sensitive_data.iban.to_owned(), bank_sensitive_data.bic, // PIX bank_sensitive_data.pix_key, bank_sensitive_data.tax_id, ) { (Some(ban), Some(brn), None, None, None, None, None) => { Self::Ach(payouts::AchBankTransfer { bank_account_number: ban, bank_routing_number: brn, bank_name: bank_insensitive_data.bank_name, bank_country_code: bank_insensitive_data.bank_country_code, bank_city: bank_insensitive_data.bank_city, }) } (Some(ban), None, Some(bsc), None, None, None, None) => { Self::Bacs(payouts::BacsBankTransfer { bank_account_number: ban, bank_sort_code: bsc, bank_name: bank_insensitive_data.bank_name, bank_country_code: bank_insensitive_data.bank_country_code, bank_city: bank_insensitive_data.bank_city, }) } (None, None, None, Some(iban), bic, None, None) => { Self::Sepa(payouts::SepaBankTransfer { iban, bic, bank_name: bank_insensitive_data.bank_name, bank_country_code: bank_insensitive_data.bank_country_code, bank_city: bank_insensitive_data.bank_city, }) } (Some(ban), None, None, None, None, Some(pix_key), tax_id) => { Self::Pix(payouts::PixBankTransfer { bank_account_number: ban, bank_branch: bank_insensitive_data.bank_branch, bank_name: bank_insensitive_data.bank_name, pix_key, tax_id, }) } _ => Err(errors::VaultError::ResponseDeserializationFailed)?, }; let supp_data = SupplementaryVaultData { customer_id: bank_insensitive_data.customer_id, payment_method_id: None, }; Ok((bank, supp_data)) } } #[cfg(feature = "payouts")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum VaultPayoutMethod { Card(String), Bank(String), Wallet(String), BankRedirect(String), } #[cfg(feature = "payouts")] impl Vaultable for api::PayoutMethodData { fn get_value1( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = match self { Self::Card(card) => VaultPayoutMethod::Card(card.get_value1(customer_id)?), Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value1(customer_id)?), Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value1(customer_id)?), Self::BankRedirect(bank_redirect) => { VaultPayoutMethod::BankRedirect(bank_redirect.get_value1(customer_id)?) } }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payout method value1") } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = match self { Self::Card(card) => VaultPayoutMethod::Card(card.get_value2(customer_id)?), Self::Bank(bank) => VaultPayoutMethod::Bank(bank.get_value2(customer_id)?), Self::Wallet(wallet) => VaultPayoutMethod::Wallet(wallet.get_value2(customer_id)?), Self::BankRedirect(bank_redirect) => { VaultPayoutMethod::BankRedirect(bank_redirect.get_value2(customer_id)?) } }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode payout method value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: VaultPayoutMethod = value1 .parse_struct("VaultMethodValue1") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into vault method value 1")?; let value2: VaultPayoutMethod = value2 .parse_struct("VaultMethodValue2") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into vault method value 2")?; match (value1, value2) { (VaultPayoutMethod::Card(mvalue1), VaultPayoutMethod::Card(mvalue2)) => { let (card, supp_data) = api::CardPayout::from_values(mvalue1, mvalue2)?; Ok((Self::Card(card), supp_data)) } (VaultPayoutMethod::Bank(mvalue1), VaultPayoutMethod::Bank(mvalue2)) => { let (bank, supp_data) = api::BankPayout::from_values(mvalue1, mvalue2)?; Ok((Self::Bank(bank), supp_data)) } (VaultPayoutMethod::Wallet(mvalue1), VaultPayoutMethod::Wallet(mvalue2)) => { let (wallet, supp_data) = api::WalletPayout::from_values(mvalue1, mvalue2)?; Ok((Self::Wallet(wallet), supp_data)) } ( VaultPayoutMethod::BankRedirect(mvalue1), VaultPayoutMethod::BankRedirect(mvalue2), ) => { let (bank_redirect, supp_data) = api::BankRedirectPayout::from_values(mvalue1, mvalue2)?; Ok((Self::BankRedirect(bank_redirect), supp_data)) } _ => Err(errors::VaultError::PayoutMethodNotSupported) .attach_printable("Payout method not supported"), } } } #[cfg(feature = "payouts")] impl Vaultable for api::BankRedirectPayout { fn get_value1( &self, _customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value1 = match self { Self::Interac(interac_data) => TokenizedBankRedirectSensitiveValues { email: interac_data.email.clone(), bank_redirect_type: PaymentMethodType::Interac, }, }; value1 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable( "Failed to encode bank redirect data - TokenizedBankRedirectSensitiveValues", ) } fn get_value2( &self, customer_id: Option<id_type::CustomerId>, ) -> CustomResult<String, errors::VaultError> { let value2 = TokenizedBankRedirectInsensitiveValues { customer_id }; value2 .encode_to_string_of_json() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode wallet data value2") } fn from_values( value1: String, value2: String, ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { let value1: TokenizedBankRedirectSensitiveValues = value1 .parse_struct("TokenizedBankRedirectSensitiveValues") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data value1")?; let value2: TokenizedBankRedirectInsensitiveValues = value2 .parse_struct("TokenizedBankRedirectInsensitiveValues") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Could not deserialize into wallet data value2")?; let bank_redirect = match value1.bank_redirect_type { PaymentMethodType::Interac => Self::Interac(api_models::payouts::Interac { email: value1.email, }), _ => Err(errors::VaultError::PayoutMethodNotSupported) .attach_printable("Payout method not supported")?, }; let supp_data = SupplementaryVaultData { customer_id: value2.customer_id, payment_method_id: None, }; Ok((bank_redirect, supp_data)) } } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectSensitiveValues { pub email: Email, pub bank_redirect_type: PaymentMethodType, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectInsensitiveValues { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct MockTokenizeDBValue { pub value1: String, pub value2: String, } pub struct Vault; impl Vault { #[instrument(skip_all)] pub async fn get_payment_method_data_from_locker( state: &routes::SessionState, lookup_key: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<(Option<domain::PaymentMethodData>, SupplementaryVaultData)> { let de_tokenize = get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?; let (payment_method, customer_id) = domain::PaymentMethodData::from_values(de_tokenize.value1, de_tokenize.value2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing Payment Method from Values")?; Ok((Some(payment_method), customer_id)) } #[instrument(skip_all)] pub async fn store_payment_method_data_in_locker( state: &routes::SessionState, token_id: Option<String>, payment_method: &domain::PaymentMethodData, customer_id: Option<id_type::CustomerId>, pm: enums::PaymentMethod, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<String> { let value1 = payment_method .get_value1(customer_id.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value1 for locker")?; let value2 = payment_method .get_value2(customer_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value12 for locker")?; let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("token")); let lookup_key = create_tokenize( state, value1, Some(value2), lookup_key, merchant_key_store.key.get_inner(), ) .await?; add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?; metrics::TOKENIZED_DATA_COUNT.add(1, &[]); Ok(lookup_key) } #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn get_payout_method_data_from_temporary_locker( state: &routes::SessionState, lookup_key: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<(Option<api::PayoutMethodData>, SupplementaryVaultData)> { let de_tokenize = get_tokenized_data(state, lookup_key, true, merchant_key_store.key.get_inner()).await?; let (payout_method, supp_data) = api::PayoutMethodData::from_values(de_tokenize.value1, de_tokenize.value2) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing Payout Method from Values")?; Ok((Some(payout_method), supp_data)) } #[cfg(feature = "payouts")] #[instrument(skip_all)] pub async fn store_payout_method_data_in_locker( state: &routes::SessionState, token_id: Option<String>, payout_method: &api::PayoutMethodData, customer_id: Option<id_type::CustomerId>, merchant_key_store: &domain::MerchantKeyStore, ) -> RouterResult<String> { let value1 = payout_method .get_value1(customer_id.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value1 for locker")?; let value2 = payout_method .get_value2(customer_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value2 for locker")?; let lookup_key = token_id.unwrap_or_else(|| generate_id_with_default_len("temporary_token")); let lookup_key = create_tokenize( state, value1, Some(value2), lookup_key, merchant_key_store.key.get_inner(), ) .await?; // add_delete_tokenized_data_task(&*state.store, &lookup_key, pm).await?; // scheduler_metrics::TOKENIZED_DATA_COUNT.add(1, &[]); Ok(lookup_key) } #[instrument(skip_all)] pub async fn delete_locker_payment_method_by_lookup_key( state: &routes::SessionState, lookup_key: &Option<String>, ) { if let Some(lookup_key) = lookup_key { delete_tokenized_data(state, lookup_key) .await .map(|_| logger::info!("Card From locker deleted Successfully")) .map_err(|err| logger::error!("Error: Deleting Card From Redis Locker : {:?}", err)) .ok(); } } } //------------------------------------------------TokenizeService------------------------------------------------ #[inline(always)] fn get_redis_locker_key(lookup_key: &str) -> String { format!("{}_{}", consts::LOCKER_REDIS_PREFIX, lookup_key) } #[instrument(skip(state, value1, value2))] pub async fn create_tokenize( state: &routes::SessionState, value1: String, value2: Option<String>, lookup_key: String, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<String> { let redis_key = get_redis_locker_key(lookup_key.as_str()); let func = || async { metrics::CREATED_TOKENIZED_CARD.add(1, &[]); let payload_to_be_encrypted = api::TokenizePayloadRequest { value1: value1.clone(), value2: value2.clone().unwrap_or_default(), lookup_key: lookup_key.clone(), service_name: VAULT_SERVICE_NAME.to_string(), }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode redis temp locker data")?; let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .set_key_if_not_exists_with_expiry( &redis_key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)), ) .await .map(|_| lookup_key.clone()) .inspect_err(|error| { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); logger::error!(?error, "Failed to store tokenized data in Redis"); }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error from redis locker") }; match func().await { Ok(s) => { logger::info!( "Insert payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[instrument(skip(state))] pub async fn get_tokenized_data( state: &routes::SessionState, lookup_key: &str, _should_get_value2: bool, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<api::TokenizePayloadRequest> { let redis_key = get_redis_locker_key(lookup_key); let func = || async { metrics::GET_TOKENIZED_CARD.add(1, &[]); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let response = redis_conn .get_key::<bytes::Bytes>(&redis_key.as_str().into()) .await; match response { Ok(resp) => { let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(resp.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode redis temp locker data")?; let get_response: api::TokenizePayloadRequest = bytes::Bytes::from(decrypted_payload) .parse_struct("TokenizePayloadRequest") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Error getting TokenizePayloadRequest from tokenize response", )?; Ok(get_response) } Err(err) => { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); Err(err).change_context(errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".into(), }) } } }; match func().await { Ok(s) => { logger::info!( "Fetch payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[instrument(skip(state))] pub async fn delete_tokenized_data( state: &routes::SessionState, lookup_key: &str, ) -> RouterResult<()> { let redis_key = get_redis_locker_key(lookup_key); let func = || async { metrics::DELETED_TOKENIZED_CARD.add(1, &[]); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let response = redis_conn.delete_key(&redis_key.as_str().into()).await; match response { Ok(redis_interface::DelReply::KeyDeleted) => Ok(()), Ok(redis_interface::DelReply::KeyNotDeleted) => { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Token invalid or expired") } Err(err) => { metrics::TEMP_LOCKER_FAILURES.add(1, &[]); Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| { format!("Failed to delete from redis locker: {err:?}") }) } } }; match func().await { Ok(s) => { logger::info!( "Delete payload in redis locker successful with lookup key: {:?}", redis_key ); Ok(s) } Err(err) => { logger::error!("Redis Temp locker Failed: {:?}", err); Err(err) } } } #[cfg(feature = "v2")] async fn create_vault_request<R: pm_types::VaultingInterface>( jwekey: &settings::Jwekey, locker: &settings::Locker, payload: Vec<u8>, tenant_id: id_type::TenantId, ) -> CustomResult<request::Request, errors::VaultError> { let private_key = jwekey.vault_private_key.peek().as_bytes(); let jws = services::encryption::jws_sign_payload( &payload, &locker.locker_signing_key_id, private_key, ) .await .change_context(errors::VaultError::RequestEncryptionFailed)?; let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?; let mut url = locker.host.to_owned(); url.push_str(R::get_vaulting_request_url()); let mut request = request::Request::new(services::Method::Post, &url); request.add_header( headers::CONTENT_TYPE, consts::VAULT_HEADER_CONTENT_TYPE.into(), ); request.add_header( headers::X_TENANT_ID, tenant_id.get_string_repr().to_owned().into(), ); request.set_body(request::RequestContent::Json(Box::new(jwe_payload))); Ok(request) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn call_to_vault<V: pm_types::VaultingInterface>( state: &routes::SessionState, payload: Vec<u8>, ) -> CustomResult<String, errors::VaultError> { let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); let request = create_vault_request::<V>(jwekey, locker, payload, state.tenant.tenant_id.to_owned()) .await?; let response = services::call_connector_api(state, request, V::get_vaulting_flow_name()) .await .change_context(errors::VaultError::VaultAPIError); let jwe_body: services::JweBody = response .get_response_inner("JweBody") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to get JweBody from vault response")?; let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload( jwekey, jwe_body, locker.decryption_scheme.clone(), ) .await .change_context(errors::VaultError::ResponseDecryptionFailed) .attach_printable("Error getting decrypted vault response payload")?; Ok(decrypted_payload) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn get_fingerprint_id_from_vault<D: domain::VaultingDataInterface + serde::Serialize>( state: &routes::SessionState, data: &D, key: String, ) -> CustomResult<String, errors::VaultError> { let data = serde_json::to_string(data) .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode Vaulting data to string")?; let payload = pm_types::VaultFingerprintRequest { key, data } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultFingerprintRequest")?; let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let fingerprint_resp: pm_types::VaultFingerprintResponse = resp .parse_struct("VaultFingerprintResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultFingerprintResponse")?; Ok(fingerprint_resp.fingerprint_id) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn add_payment_method_to_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, pmd: &domain::PaymentMethodVaultingData, existing_vault_id: Option<domain::VaultId>, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> { let payload = pm_types::AddVaultRequest { entity_id: customer_id.to_owned(), vault_id: existing_vault_id .unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())), data: pmd, ttl: state.conf.locker.ttl_for_storage_in_secs, } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode AddVaultRequest")?; let resp = call_to_vault::<pm_types::AddVault>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::AddVaultResponse = resp .parse_struct("AddVaultResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into AddVaultResponse")?; Ok(stored_pm_resp) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_internal( state: &routes::SessionState, merchant_context: &domain::MerchantContext, vault_id: &domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> { let payload = pm_types::VaultRetrieveRequest { entity_id: customer_id.to_owned(), vault_id: vault_id.to_owned(), } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultRetrieveRequest")?; let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::VaultRetrieveResponse = resp .parse_struct("VaultRetrieveResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultRetrieveResponse")?; Ok(stored_pm_resp) } #[cfg(all(feature = "v2", feature = "tokenization_v2"))] #[instrument(skip_all)] pub async fn retrieve_value_from_vault( state: &routes::SessionState, request: pm_types::VaultRetrieveRequest, ) -> CustomResult<serde_json::value::Value, errors::VaultError> { let payload = request .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultRetrieveRequest")?; let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_resp: serde_json::Value = resp .parse_struct("VaultRetrieveResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultRetrieveResponse")?; Ok(stored_resp) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, pm: &domain::PaymentMethod, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, ) -> RouterResult<pm_types::VaultRetrieveResponse> { let connector_vault_id = pm .locker_id .clone() .map(|id| id.get_string_repr().to_owned()); let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, None, connector_vault_id, None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault retrieve api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultRetrieveFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_retrieve_payment_method_data::<ExternalVaultRetrieveFlow>( router_data_resp, ) } #[cfg(feature = "v2")] pub fn get_vault_response_for_retrieve_payment_method_data<F>( router_data: VaultRouterData<F>, ) -> RouterResult<pm_types::VaultRetrieveResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => { Ok(pm_types::VaultRetrieveResponse { data: vault_data }) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method")), } } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_using_payment_token( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_token: &String, payment_method_type: &common_enums::PaymentMethod, ) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> { let pm_token_data = utils::retrieve_payment_token_data( state, payment_token.to_string(), Some(payment_method_type), ) .await?; let payment_method_id = match pm_token_data { storage::PaymentTokenData::PermanentCard(card_token_data) => { card_token_data.payment_method_id } storage::PaymentTokenData::TemporaryGeneric(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "TemporaryGeneric Token not implemented".to_string(), ), })? } storage::PaymentTokenData::AuthBankDebit(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "AuthBankDebit Token not implemented".to_string(), ), })? } }; let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_method = db .find_payment_method( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let vault_data = retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault")? .data; Ok((payment_method, vault_data)) } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct TemporaryVaultCvc { card_cvc: masking::Secret<String>, } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn insert_cvc_using_payment_token( state: &routes::SessionState, payment_token: &String, payment_method_data: api_models::payment_methods::PaymentMethodCreateData, payment_method: common_enums::PaymentMethod, fulfillment_time: i64, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<()> { let card_cvc = domain::PaymentMethodVaultingData::try_from(payment_method_data)? .get_card() .and_then(|card| card.card_cvc.clone()); if let Some(card_cvc) = card_cvc { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc"); let payload_to_be_encrypted = TemporaryVaultCvc { card_cvc }; let payload = payload_to_be_encrypted .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError)?; // Encrypt the CVC and store it in Redis let encrypted_payload = GcmAes256 .encode_message(encryption_key.peek().as_ref(), payload.as_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode TemporaryVaultCvc for vault")?; redis_conn .set_key_if_not_exists_with_expiry( &key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(fulfillment_time), ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add token in redis")?; }; Ok(()) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_and_delete_cvc_from_payment_token( state: &routes::SessionState, payment_token: &String, payment_method: common_enums::PaymentMethod, encryption_key: &masking::Secret<Vec<u8>>, ) -> RouterResult<masking::Secret<String>> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let key = format!("pm_token_{payment_token}_{payment_method}_hyperswitch_cvc",); let data = redis_conn .get_key::<bytes::Bytes>(&key.clone().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; // decrypt the cvc data let decrypted_payload = GcmAes256 .decode_message( encryption_key.peek().as_ref(), masking::Secret::new(data.into()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to decode TemporaryVaultCvc from vault")?; let cvc_data: TemporaryVaultCvc = bytes::Bytes::from(decrypted_payload) .parse_struct("TemporaryVaultCvc") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize TemporaryVaultCvc")?; // delete key after retrieving the cvc redis_conn.delete_key(&key.into()).await.map_err(|err| { logger::error!("Failed to delete token from redis: {:?}", err); }); Ok(cvc_data.card_cvc) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_payment_token( state: &routes::SessionState, key_for_token: &str, intent_status: enums::IntentStatus, ) -> RouterResult<()> { if ![ enums::IntentStatus::RequiresCustomerAction, enums::IntentStatus::RequiresMerchantAction, ] .contains(&intent_status) { utils::delete_payment_token_data(state, key_for_token) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to delete payment_token")?; } Ok(()) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, pm: &domain::PaymentMethod, ) -> RouterResult<pm_types::VaultRetrieveResponse> { let is_external_vault_enabled = profile.is_external_vault_enabled(); match is_external_vault_enabled { true => { let external_vault_source = pm.external_vault_source.as_ref(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), external_vault_source, ) .await .attach_printable( "failed to fetch merchant connector account for external vault retrieve", )?, )); retrieve_payment_method_from_vault_external( state, merchant_context.get_merchant_account(), pm, merchant_connector_account, ) .await } false => { let vault_id = pm .locker_id .clone() .ok_or(errors::VaultError::MissingRequiredField { field_name: "locker_id", }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Missing locker_id for VaultRetrieveRequest")?; retrieve_payment_method_from_vault_internal( state, merchant_context, &vault_id, &pm.customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault") } } } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault_internal( state: &routes::SessionState, merchant_context: &domain::MerchantContext, vault_id: domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> { let payload = pm_types::VaultDeleteRequest { entity_id: customer_id.to_owned(), vault_id, } .encode_to_vec() .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultDeleteRequest")?; let resp = call_to_vault::<pm_types::VaultDelete>(state, payload) .await .change_context(errors::VaultError::VaultAPIError) .attach_printable("Call to vault failed")?; let stored_pm_resp: pm_types::VaultDeleteResponse = resp .parse_struct("VaultDeleteResponse") .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultDeleteResponse")?; Ok(stored_pm_resp) } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault_external( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, merchant_connector_account: domain::MerchantConnectorAccountTypeDetails, vault_id: domain::VaultId, customer_id: &id_type::GlobalCustomerId, ) -> RouterResult<pm_types::VaultDeleteResponse> { let connector_vault_id = vault_id.get_string_repr().to_owned(); // Extract MerchantConnectorAccount from the enum let merchant_connector_account = match &merchant_connector_account { domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => { Ok(mca.as_ref()) } domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("MerchantConnectorDetails not supported for vault operations")) } }?; let router_data = core_utils::construct_vault_router_data( state, merchant_account.get_id(), merchant_connector_account, None, Some(connector_vault_id), None, ) .await?; let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault delete api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< ExternalVaultDeleteFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments_core::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_delete_payment_method_data::<ExternalVaultDeleteFlow>( router_data_resp, customer_id.to_owned(), ) } #[cfg(feature = "v2")] pub fn get_vault_response_for_delete_payment_method_data<F>( router_data: VaultRouterData<F>, customer_id: id_type::GlobalCustomerId, ) -> RouterResult<pm_types::VaultDeleteResponse> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultDeleteResponse { connector_vault_id } => { Ok(pm_types::VaultDeleteResponse { vault_id: domain::VaultId::generate(connector_vault_id), // converted to VaultId type entity_id: customer_id, }) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultRetrieveResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method")), } } #[cfg(feature = "v2")] pub async fn delete_payment_method_data_from_vault( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, pm: &domain::PaymentMethod, ) -> RouterResult<pm_types::VaultDeleteResponse> { let is_external_vault_enabled = profile.is_external_vault_enabled(); let vault_id = pm .locker_id .clone() .get_required_value("locker_id") .attach_printable("Missing locker_id in PaymentMethod")?; match is_external_vault_enabled { true => { let external_vault_source = pm.external_vault_source.as_ref(); let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new( payments_core::helpers::get_merchant_connector_account_v2( state, merchant_context.get_merchant_key_store(), external_vault_source, ) .await .attach_printable( "failed to fetch merchant connector account for external vault delete", )?, )); delete_payment_method_data_from_vault_external( state, merchant_context.get_merchant_account(), merchant_connector_account, vault_id.clone(), &pm.customer_id, ) .await } false => delete_payment_method_data_from_vault_internal( state, merchant_context, vault_id, &pm.customer_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete payment method from vault"), } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn retrieve_payment_method_from_vault_external_v1( state: &routes::SessionState, merchant_id: &id_type::MerchantId, pm: &domain::PaymentMethod, merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, ) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { let connector_vault_id = pm.locker_id.clone().map(|id| id.to_string()); let router_data = core_utils::construct_vault_router_data( state, merchant_id, &merchant_connector_account, None, connector_vault_id, None, ) .await?; let old_router_data = VaultConnectorFlowData::to_old_router_data(router_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Cannot construct router data for making the external vault retrieve api call", )?; let connector_name = merchant_connector_account.get_connector_name_as_string(); let connector_data = api::ConnectorData::get_external_vault_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, Some(merchant_connector_account.get_id()), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector data")?; let connector_integration: services::BoxedVaultConnectorIntegrationInterface< hyperswitch_domain_models::router_flow_types::ExternalVaultRetrieveFlow, types::VaultRequestData, types::VaultResponseData, > = connector_data.connector.get_connector_integration(); let router_data_resp = services::execute_connector_processing_step( state, connector_integration, &old_router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_vault_failed_response()?; get_vault_response_for_retrieve_payment_method_data_v1(router_data_resp) } pub fn get_vault_response_for_retrieve_payment_method_data_v1<F>( router_data: VaultRouterData<F>, ) -> RouterResult<hyperswitch_domain_models::vault::PaymentMethodVaultingData> { match router_data.response { Ok(response) => match response { types::VaultResponseData::ExternalVaultRetrieveResponse { vault_data } => { Ok(vault_data) } types::VaultResponseData::ExternalVaultInsertResponse { .. } | types::VaultResponseData::ExternalVaultDeleteResponse { .. } | types::VaultResponseData::ExternalVaultCreateResponse { .. } => { Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid Vault Response")) } }, Err(err) => { logger::error!( "Failed to retrieve payment method from external vault: {:?}", err ); Err(report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from external vault")) } } } // ********************************************** PROCESS TRACKER ********************************************** pub async fn add_delete_tokenized_data_task( db: &dyn db::StorageInterface, lookup_key: &str, pm: enums::PaymentMethod, ) -> RouterResult<()> { let runner = storage::ProcessTrackerRunner::DeleteTokenizeDataWorkflow; let process_tracker_id = format!("{runner}_{lookup_key}"); let task = runner.to_string(); let tag = ["BASILISK-V3"]; let tracking_data = storage::TokenizeCoreWorkflow { lookup_key: lookup_key.to_owned(), pm, }; let schedule_time = get_delete_tokenize_schedule_time(db, pm, 0) .await .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to obtain initial process tracker schedule time")?; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, &task, runner, tag, tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct delete tokenized data process tracker task")?; let response = db.insert_process(process_tracker_entry).await; response.map(|_| ()).or_else(|err| { if err.current_context().is_db_unique_violation() { Ok(()) } else { Err(report!(errors::ApiErrorResponse::InternalServerError)) } }) } pub async fn start_tokenize_data_workflow( state: &routes::SessionState, tokenize_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let delete_tokenize_data = serde_json::from_value::<storage::TokenizeCoreWorkflow>( tokenize_tracker.tracking_data.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into DeleteTokenizeByTokenRequest {:?}", tokenize_tracker.tracking_data ) })?; match delete_tokenized_data(state, &delete_tokenize_data.lookup_key).await { Ok(()) => { logger::info!("Card From locker deleted Successfully"); //mark task as finished db.as_scheduler() .finish_process_with_business_status( tokenize_tracker.clone(), diesel_models::process_tracker::business_status::COMPLETED_BY_PT, ) .await?; } Err(err) => { logger::error!("Err: Deleting Card From Locker : {:?}", err); retry_delete_tokenize(db, delete_tokenize_data.pm, tokenize_tracker.to_owned()).await?; metrics::RETRIED_DELETE_DATA_COUNT.add(1, &[]); } } Ok(()) } pub async fn get_delete_tokenize_schedule_time( db: &dyn db::StorageInterface, pm: enums::PaymentMethod, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { let redis_mapping = db::get_and_deserialize_key( db, &format!("pt_mapping_delete_{pm}_tokenize_data"), "PaymentMethodsPTMapping", ) .await; let mapping = match redis_mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::PaymentMethodsPTMapping::default() } }; let time_delta = process_tracker_utils::get_pm_schedule_time(mapping, pm, retry_count + 1); process_tracker_utils::get_time_from_delta(time_delta) } pub async fn retry_delete_tokenize( db: &dyn db::StorageInterface, pm: enums::PaymentMethod, pt: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await; match schedule_time { Some(s_time) => { let retry_schedule = db .as_scheduler() .retry_process(pt, s_time) .await .map_err(Into::into); metrics::TASKS_RESET_COUNT.add( 1, router_env::metric_attributes!(("flow", "DeleteTokenizeData")), ); retry_schedule } None => db .as_scheduler() .finish_process_with_business_status( pt, diesel_models::process_tracker::business_status::RETRIES_EXCEEDED, ) .await .map_err(Into::into), } } // Fallback logic of old temp locker needs to be removed later
{ "crate": "router", "file": "crates/router/src/core/payment_methods/vault.rs", "file_size": 84482, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-5171145087954519437
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/db/refund.rs // File size: 77165 bytes #[cfg(feature = "olap")] use std::collections::{HashMap, HashSet}; #[cfg(feature = "olap")] use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit}; use diesel_models::{errors::DatabaseError, refund as diesel_refund}; use hyperswitch_domain_models::refunds; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::enums, }; #[cfg(feature = "olap")] const MAX_LIMIT: usize = 100; #[async_trait::async_trait] pub trait RefundInterface { #[cfg(feature = "v1")] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>; #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; async fn insert_refund( &self, new: diesel_refund::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; #[cfg(all(feature = "v2", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; #[cfg(all(feature = "v2", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use hyperswitch_domain_models::refunds; use router_env::{instrument, tracing}; use super::RefundInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums}, }; #[async_trait::async_trait] impl RefundInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_id(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints( &conn, merchant_id, refund_details, ) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait, }; use diesel_models::refund as diesel_refund; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::refunds; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::RefundInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums, kv}, utils::db_utils, }; #[async_trait::async_trait] impl RefundInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_inter_ref_{}_{internal_reference_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let merchant_id = new.merchant_id.clone(); let payment_id = new.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let key_str = key.to_string(); // TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id // Check for database presence as well Maybe use a read replica here ? let created_refund = diesel_refund::Refund { refund_id: new.refund_id.clone(), merchant_id: new.merchant_id.clone(), attempt_id: new.attempt_id.clone(), internal_reference_id: new.internal_reference_id.clone(), payment_id: new.payment_id.clone(), connector_transaction_id: new.connector_transaction_id.clone(), connector: new.connector.clone(), connector_refund_id: new.connector_refund_id.clone(), external_reference_id: new.external_reference_id.clone(), refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata.clone(), refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: new.created_at, description: new.description.clone(), refund_reason: new.refund_reason.clone(), profile_id: new.profile_id.clone(), updated_by: new.updated_by.clone(), merchant_connector_id: new.merchant_connector_id.clone(), charges: new.charges.clone(), split_refunds: new.split_refunds.clone(), organization_id: new.organization_id.clone(), unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; let field = format!( "pa_{}_ref_{}", &created_refund.attempt_id, &created_refund.refund_id ); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Refund(new)), }, }; let mut reverse_lookups = vec![ storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_ref_id_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.refund_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, // [#492]: A discussion is required on whether this is required? storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_inter_ref_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.internal_reference_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, ]; if let Some(connector_refund_id) = created_refund.to_owned().get_optional_connector_refund_id() { reverse_lookups.push(storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_connector_{}_{}_{}", created_refund.merchant_id.get_string_repr(), connector_refund_id, created_refund.connector ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }) }; let rev_look = reverse_lookups .into_iter() .map(|rev| self.insert_reverse_lookup(rev, storage_scheme)); futures::future::try_join_all(rev_look).await?; match Box::pin(kv_wrapper::<diesel_refund::Refund, _, _>( self, KvOperation::<diesel_refund::Refund>::HSetNx( &field, &created_refund, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "refund", key: Some(created_refund.refund_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_refund), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pa_conn_trans_{}_{connector_transaction_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::Scan(&pattern), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let updated_refund = refund.clone().apply_changeset(this.clone()); let redis_value = updated_refund .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::RefundUpdate(Box::new( kv::RefundUpdateMems { orig: this, update_data: refund, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_refund::Refund>( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_refund) } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_id(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!("ref_ref_id_{}_{refund_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_connector_{}_{connector_refund_id}_{connector}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_refund::Refund>::Scan("pa_*_ref_*"), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_refund::Refund::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints(&conn, merchant_id, refund_details) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v1", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl RefundInterface for MockDb { #[cfg(feature = "v1")] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund.internal_reference_id == internal_reference_id }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = diesel_refund::Refund { internal_reference_id: new.internal_reference_id, refund_id: new.refund_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, merchant_connector_id: new.merchant_connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; refunds.push(refund.clone()); Ok(refund) } #[cfg(feature = "v2")] async fn insert_refund( &self, new: diesel_refund::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = diesel_refund::Refund { id: new.id, merchant_reference_id: new.merchant_reference_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, connector_id: new.connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), }; refunds.push(refund.clone()); Ok(refund) } async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .take_while(|refund| { refund.merchant_id == *merchant_id && refund.get_connector_transaction_id() == connector_transaction_id }) .cloned() .collect::<Vec<_>>()) } #[cfg(feature = "v1")] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.refund_id == refund.refund_id) .map(|r| { let refund_updated = diesel_refund::RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(feature = "v2")] async fn update_refund( &self, this: diesel_refund::Refund, refund: diesel_refund::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.merchant_reference_id == refund.merchant_reference_id) .map(|r| { let refund_updated = diesel_refund::RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.merchant_id == *merchant_id && refund.refund_id == refund_id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund .get_optional_connector_refund_id() .map(|refund_id| refund_id.as_str()) == Some(connector_refund_id) && refund.connector == connector }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(feature = "v1")] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == *payment_id) .cloned() .collect::<Vec<_>>()) } #[cfg(feature = "v2")] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<diesel_refund::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.id == *id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .skip(usize::try_from(offset).unwrap_or_default()) .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) .cloned() .collect::<Vec<_>>(); Ok(filtered_refunds) } #[cfg(all(feature = "v2", feature = "olap"))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(connector_id_list) = &refund_details.connector_id_list { connector_id_list.iter().for_each(|unique_connector_id| { unique_connector_ids.insert(unique_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund .profile_id .as_ref() .is_some_and(|profile_id| profile_id == &refund_details.profile_id) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_connector_ids.is_empty() || refund .connector_id .as_ref() .is_some_and(|id| unique_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .skip(usize::try_from(offset).unwrap_or_default()) .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) .cloned() .collect::<Vec<_>>(); Ok(filtered_refunds) } #[cfg(all(feature = "v1", feature = "olap"))] async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = refund_details.start_time; let end_time = refund_details .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_meta_data = api_models::refunds::RefundListMetaData { connector: vec![], currency: vec![], refund_status: vec![], }; let mut unique_connectors = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); for refund in filtered_refunds.into_iter() { unique_connectors.insert(refund.connector); let currency: api_models::enums::Currency = refund.currency; unique_currencies.insert(currency); let status: api_models::enums::RefundStatus = refund.refund_status; unique_statuses.insert(status); } refund_meta_data.connector = unique_connectors.into_iter().collect(); refund_meta_data.currency = unique_currencies.into_iter().collect(); refund_meta_data.refund_status = unique_statuses.into_iter().collect(); Ok(refund_meta_data) } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| { refund.created_at >= start_time && refund.created_at <= end_time && profile_id_list .as_ref() .zip(refund.profile_id.as_ref()) .map(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) .unwrap_or(true) }) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_status_counts: HashMap<api_models::enums::RefundStatus, i64> = HashMap::new(); for refund in filtered_refunds { *refund_status_counts .entry(refund.refund_status) .or_insert(0) += 1; } let result: Vec<(api_models::enums::RefundStatus, i64)> = refund_status_counts.into_iter().collect(); Ok(result) } #[cfg(all(feature = "v1", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .cloned() .collect::<Vec<_>>(); let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); Ok(filtered_refunds_count) } #[cfg(all(feature = "v2", feature = "olap"))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(connector_id_list) = &refund_details.connector_id_list { connector_id_list.iter().for_each(|unique_connector_id| { unique_connector_ids.insert(unique_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .is_none_or(|id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .is_none_or(|id| id == refund.id) }) .filter(|refund| { refund .profile_id .as_ref() .is_some_and(|profile_id| profile_id == &refund_details.profile_id) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details.amount_filter.as_ref().is_none_or(|amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_connector_ids.is_empty() || refund .connector_id .as_ref() .is_some_and(|id| unique_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .cloned() .collect::<Vec<_>>(); let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); Ok(filtered_refunds_count) } }
{ "crate": "router", "file": "crates/router/src/db/refund.rs", "file_size": 77165, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-3451067206245137353
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/routing/utils.rs // File size: 74598 bytes use std::{ collections::{HashMap, HashSet}, str::FromStr, }; use api_models::{ open_router as or_types, routing::{ self as api_routing, ComparisonType, ConnectorSelection, ConnectorVolumeSplit, DeRoutableConnectorChoice, MetadataValue, NumberComparison, RoutableConnectorChoice, RoutingEvaluateRequest, RoutingEvaluateResponse, ValueType, }, }; use async_trait::async_trait; use common_enums::{RoutableConnectors, TransactionType}; use common_utils::{ ext_traits::{BytesExt, StringExt}, id_type, }; use diesel_models::{enums, routing_algorithm}; use error_stack::ResultExt; use euclid::{ backend::BackendInput, frontend::{ ast::{self}, dir::{self, transformers::IntoDirValue}, }, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use external_services::grpc_client::dynamic_routing as ir_client; use hyperswitch_domain_models::business_profile; use hyperswitch_interfaces::events::routing_api_logs as routing_events; use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; use super::RoutingResult; use crate::{ core::errors, db::domain, routes::{app::SessionStateInfo, SessionState}, services::{self, logger}, types::transformers::ForeignInto, }; // New Trait for handling Euclid API calls #[async_trait] pub trait DecisionEngineApiHandler { async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, // Option to handle GET/DELETE requests without body timeout: Option<u64>, events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone; } // Struct to implement the DecisionEngineApiHandler trait pub struct EuclidApiClient; pub struct ConfigApiClient; pub struct SRApiClient; pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, _timeout: Option<u64>, context_message: &str, events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static, ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface, { let decision_engine_base_url = &state.conf.open_router.url; let url = format!("{decision_engine_base_url}/{path}"); logger::debug!(decision_engine_api_call_url = %url, decision_engine_request_path = %path, http_method = ?http_method, "decision_engine: Initiating decision_engine API call ({})", context_message); let mut request_builder = services::RequestBuilder::new() .method(http_method) .url(&url); if let Some(body_content) = request_body { let body = common_utils::request::RequestContent::Json(Box::new(body_content)); request_builder = request_builder.set_body(body); } let http_request = request_builder.build(); logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message); let should_parse_response = events_wrapper .as_ref() .map(|wrapper| wrapper.parse_response) .unwrap_or(true); let closure = || async { let response = services::call_connector_api(state, http_request, "Decision Engine API call") .await .change_context(errors::RoutingError::OpenRouterCallFailed)?; match response { Ok(resp) => { logger::debug!( "decision_engine: Received response from Decision Engine API ({:?})", String::from_utf8_lossy(&resp.response) // For logging ); let resp = should_parse_response .then(|| { if std::any::TypeId::of::<Res>() == std::any::TypeId::of::<String>() && resp.response.is_empty() { return serde_json::from_str::<Res>("\"\"").change_context( errors::RoutingError::OpenRouterError( "Failed to parse empty response as String".into(), ), ); } let response_type: Res = resp .response .parse_struct(std::any::type_name::<Res>()) .change_context(errors::RoutingError::OpenRouterError( "Failed to parse the response from open_router".into(), ))?; Ok::<_, error_stack::Report<errors::RoutingError>>(response_type) }) .transpose()?; logger::debug!("decision_engine_success_response: {:?}", resp); Ok(resp) } Err(err) => { logger::debug!( "decision_engine: Received response from Decision Engine API ({:?})", String::from_utf8_lossy(&err.response) // For logging ); let err_resp: ErrRes = err .response .parse_struct(std::any::type_name::<ErrRes>()) .change_context(errors::RoutingError::OpenRouterError( "Failed to parse the response from open_router".into(), ))?; logger::error!( decision_engine_error_code = %err_resp.get_error_code(), decision_engine_error_message = %err_resp.get_error_message(), decision_engine_raw_response = ?err_resp.get_error_data(), ); Err(error_stack::report!( errors::RoutingError::RoutingEventsError { message: err_resp.get_error_message(), status_code: err.status_code, } )) } } }; let events_response = if let Some(wrapper) = events_wrapper { wrapper .construct_event_builder( url, routing_events::RoutingEngine::DecisionEngine, routing_events::ApiMethod::Rest(http_method), )? .trigger_event(state, closure) .await? } else { let resp = closure() .await .change_context(errors::RoutingError::OpenRouterCallFailed)?; RoutingEventsResponse::new(None, resp) }; Ok(events_response) } #[async_trait] impl DecisionEngineApiHandler for EuclidApiClient { async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, // Option to handle GET/DELETE requests without body timeout: Option<u64>, events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, { let event_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>( state, http_method, path, request_body, timeout, "parsing response", events_wrapper, ) .await?; let parsed_response = event_response .response .as_ref() .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API"); Ok(event_response) } } #[async_trait] impl DecisionEngineApiHandler for ConfigApiClient { async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, timeout: Option<u64>, events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, { let events_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>( state, http_method, path, request_body, timeout, "parsing response", events_wrapper, ) .await?; let parsed_response = events_response .response .as_ref() .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); Ok(events_response) } } #[async_trait] impl DecisionEngineApiHandler for SRApiClient { async fn send_decision_engine_request<Req, Res>( state: &SessionState, http_method: services::Method, path: &str, request_body: Option<Req>, timeout: Option<u64>, events_wrapper: Option<RoutingEventsWrapper<Req>>, ) -> RoutingResult<RoutingEventsResponse<Res>> where Req: Serialize + Send + Sync + 'static + Clone, Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone, { let events_response = build_and_send_decision_engine_http_request::<_, _, or_types::ErrorResponse>( state, http_method, path, request_body, timeout, "parsing response", events_wrapper, ) .await?; let parsed_response = events_response .response .as_ref() .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API"); Ok(events_response) } } const EUCLID_API_TIMEOUT: u64 = 5; pub async fn perform_decision_euclid_routing( state: &SessionState, input: BackendInput, created_by: String, events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>, fallback_output: Vec<RoutableConnectorChoice>, ) -> RoutingResult<RoutingEvaluateResponse> { logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation"); let mut events_wrapper = events_wrapper; let fallback_output = fallback_output .into_iter() .map(|c| DeRoutableConnectorChoice { gateway_name: c.connector, gateway_id: c.merchant_connector_id, }) .collect::<Vec<_>>(); let routing_request = convert_backend_input_to_routing_eval(created_by, input, fallback_output)?; events_wrapper.set_request_body(routing_request.clone()); let event_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/evaluate", Some(routing_request), Some(EUCLID_API_TIMEOUT), Some(events_wrapper), ) .await?; let euclid_response: RoutingEvaluateResponse = event_response .response .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; let mut routing_event = event_response .event .ok_or(errors::RoutingError::RoutingEventsError { message: "Routing event not found in EventsResponse".to_string(), status_code: 500, })?; routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string()); routing_event.set_routable_connectors(euclid_response.evaluated_output.clone()); state.event_handler.log_event(&routing_event); logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid"); logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid"); Ok(euclid_response) } /// This function transforms the decision_engine response in a way that's usable for further flows: /// It places evaluated_output connectors first, followed by remaining output connectors (no duplicates). pub fn transform_de_output_for_router( de_output: Vec<ConnectorInfo>, de_evaluated_output: Vec<RoutableConnectorChoice>, ) -> RoutingResult<Vec<RoutableConnectorChoice>> { let mut seen = HashSet::new(); // evaluated connectors on top, to ensure the fallback is based on other connectors. let mut ordered = Vec::with_capacity(de_output.len() + de_evaluated_output.len()); for eval_conn in de_evaluated_output { if seen.insert(eval_conn.connector) { ordered.push(eval_conn); } } // Add remaining connectors from de_output (only if not already seen), for fallback for conn in de_output { let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| { errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), } })?; if seen.insert(key) { let de_choice = DeRoutableConnectorChoice::try_from(conn)?; ordered.push(RoutableConnectorChoice::from(de_choice)); } } Ok(ordered) } pub async fn decision_engine_routing( state: &SessionState, backend_input: BackendInput, business_profile: &domain::Profile, payment_id: String, merchant_fallback_config: Vec<RoutableConnectorChoice>, ) -> RoutingResult<Vec<RoutableConnectorChoice>> { let routing_events_wrapper = RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_id, business_profile.get_id().to_owned(), business_profile.merchant_id.to_owned(), "DecisionEngine: Euclid Static Routing".to_string(), None, true, false, ); let de_euclid_evaluate_response = perform_decision_euclid_routing( state, backend_input.clone(), business_profile.get_id().get_string_repr().to_string(), routing_events_wrapper, merchant_fallback_config, ) .await; let Ok(de_euclid_response) = de_euclid_evaluate_response else { logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule"); return Ok(Vec::default()); }; let de_output_connector = extract_de_output_connectors(de_euclid_response.output) .map_err(|e| { logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output"); e })?; transform_de_output_for_router( de_output_connector.clone(), de_euclid_response.evaluated_output.clone(), ) .map_err(|e| { logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output"); e }) } /// Custom deserializer for output from decision_engine, this is required as untagged enum is /// stored but the enum requires tagged deserialization, hence deserializing it into specific /// variants pub fn extract_de_output_connectors( output_value: serde_json::Value, ) -> RoutingResult<Vec<ConnectorInfo>> { const SINGLE: &str = "straight_through"; const PRIORITY: &str = "priority"; const VOLUME_SPLIT: &str = "volume_split"; const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority"; let obj = output_value.as_object().ok_or_else(|| { logger::error!("decision_engine_euclid_error: output is not a JSON object"); errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into()) })?; let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| { logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output"); errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into()) })?; match type_str { SINGLE => { let connector_value = obj.get("connector").ok_or_else(|| { logger::error!( "decision_engine_euclid_error: missing 'connector' field for type=single" ); errors::RoutingError::OpenRouterError( "Missing 'connector' field for single output".into(), ) })?; let connector: ConnectorInfo = serde_json::from_value(connector_value.clone()) .map_err(|e| { logger::error!( ?e, "decision_engine_euclid_error: Failed to parse single connector" ); errors::RoutingError::OpenRouterError( "Failed to deserialize single connector".into(), ) })?; Ok(vec![connector]) } PRIORITY => { let connectors_value = obj.get("connectors").ok_or_else(|| { logger::error!( "decision_engine_euclid_error: missing 'connectors' field for type=priority" ); errors::RoutingError::OpenRouterError( "Missing 'connectors' field for priority output".into(), ) })?; let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone()) .map_err(|e| { logger::error!( ?e, "decision_engine_euclid_error: Failed to parse connectors for priority" ); errors::RoutingError::OpenRouterError( "Failed to deserialize priority connectors".into(), ) })?; Ok(connectors) } VOLUME_SPLIT => { let splits_value = obj.get("splits").ok_or_else(|| { logger::error!( "decision_engine_euclid_error: missing 'splits' field for type=volume_split" ); errors::RoutingError::OpenRouterError( "Missing 'splits' field for volume_split output".into(), ) })?; // Transform each {connector, split} into {output, split} let fixed_splits: Vec<_> = splits_value .as_array() .ok_or_else(|| { logger::error!("decision_engine_euclid_error: 'splits' is not an array"); errors::RoutingError::OpenRouterError("'splits' field must be an array".into()) })? .iter() .map(|entry| { let mut entry_map = entry.as_object().cloned().ok_or_else(|| { logger::error!( "decision_engine_euclid_error: invalid split entry in volume_split" ); errors::RoutingError::OpenRouterError( "Invalid entry in splits array".into(), ) })?; if let Some(connector) = entry_map.remove("connector") { entry_map.insert("output".to_string(), connector); } Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object( entry_map, )) }) .collect::<Result<Vec<_>, _>>()?; let splits: Vec<VolumeSplit<ConnectorInfo>> = serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| { logger::error!( ?e, "decision_engine_euclid_error: Failed to parse volume_split" ); errors::RoutingError::OpenRouterError( "Failed to deserialize volume_split connectors".into(), ) })?; Ok(splits.into_iter().map(|s| s.output).collect()) } VOLUME_SPLIT_PRIORITY => { let splits_value = obj.get("splits").ok_or_else(|| { logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority"); errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into()) })?; // Transform each {connector: [...], split} into {output: [...], split} let fixed_splits: Vec<_> = splits_value .as_array() .ok_or_else(|| { logger::error!("decision_engine_euclid_error: 'splits' is not an array"); errors::RoutingError::OpenRouterError("'splits' field must be an array".into()) })? .iter() .map(|entry| { let mut entry_map = entry.as_object().cloned().ok_or_else(|| { logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority"); errors::RoutingError::OpenRouterError("Invalid entry in splits array".into()) })?; if let Some(connector) = entry_map.remove("connector") { entry_map.insert("output".to_string(), connector); } Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map)) }) .collect::<Result<Vec<_>, _>>()?; let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> = serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| { logger::error!( ?e, "decision_engine_euclid_error: Failed to parse volume_split_priority" ); errors::RoutingError::OpenRouterError( "Failed to deserialize volume_split_priority connectors".into(), ) })?; Ok(splits.into_iter().flat_map(|s| s.output).collect()) } other => { logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type"); Err( errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}")) .into(), ) } } } pub async fn create_de_euclid_routing_algo( state: &SessionState, routing_request: &RoutingRule, ) -> RoutingResult<String> { logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation"); logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid"); let events_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, "routing/create", Some(routing_request.clone()), Some(EUCLID_API_TIMEOUT), None, ) .await?; let euclid_response: RoutingDictionaryRecord = events_response .response .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid"); Ok(euclid_response.rule_id) } pub async fn link_de_euclid_routing_algorithm( state: &SessionState, routing_request: ActivateRoutingConfigRequest, ) -> RoutingResult<()> { logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm"); EuclidApiClient::send_decision_engine_request::<_, String>( state, services::Method::Post, "routing/activate", Some(routing_request.clone()), Some(EUCLID_API_TIMEOUT), None, ) .await?; logger::debug!(decision_engine_euclid_activated=?routing_request, "decision_engine_euclid: link_de_euclid_routing_algorithm completed"); Ok(()) } pub async fn list_de_euclid_routing_algorithms( state: &SessionState, routing_list_request: ListRountingAlgorithmsRequest, ) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms"); let created_by = routing_list_request.created_by; let events_response = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, format!("routing/list/{created_by}").as_str(), None::<()>, Some(EUCLID_API_TIMEOUT), None, ) .await?; let euclid_response: Vec<RoutingAlgorithmRecord> = events_response .response .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; Ok(euclid_response .into_iter() .map(routing_algorithm::RoutingProfileMetadata::from) .map(ForeignInto::foreign_into) .collect::<Vec<_>>()) } pub async fn list_de_euclid_active_routing_algorithm( state: &SessionState, created_by: String, ) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> { logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm"); let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request( state, services::Method::Post, format!("routing/list/active/{created_by}").as_str(), None::<()>, Some(EUCLID_API_TIMEOUT), None, ) .await? .response .ok_or(errors::RoutingError::OpenRouterError( "Response from decision engine API is empty".to_string(), ))?; Ok(response .into_iter() .map(|record| routing_algorithm::RoutingProfileMetadata::from(record).foreign_into()) .collect()) } pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>( de_result: Vec<T>, result: Vec<T>, flow: String, ) { let is_equal = de_result .iter() .zip(result.iter()) .all(|(a, b)| T::is_equal(a, b)); let is_equal_in_length = de_result.len() == result.len(); router_env::logger::debug!(routing_flow=?flow, is_equal=?is_equal, is_equal_length=?is_equal_in_length, de_response=?to_json_string(&de_result), hs_response=?to_json_string(&result), "decision_engine_euclid"); } pub trait RoutingEq<T> { fn is_equal(a: &T, b: &T) -> bool; } impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord { fn is_equal(a: &Self, b: &Self) -> bool { a.id == b.id && a.name == b.name && a.profile_id == b.profile_id && a.description == b.description && a.kind == b.kind && a.algorithm_for == b.algorithm_for } } impl RoutingEq<Self> for String { fn is_equal(a: &Self, b: &Self) -> bool { a.to_lowercase() == b.to_lowercase() } } impl RoutingEq<Self> for RoutableConnectorChoice { fn is_equal(a: &Self, b: &Self) -> bool { a.connector.eq(&b.connector) && a.choice_kind.eq(&b.choice_kind) && a.merchant_connector_id.eq(&b.merchant_connector_id) } } pub fn to_json_string<T: Serialize>(value: &T) -> String { serde_json::to_string(value) .map_err(|_| errors::RoutingError::GenericConversionError { from: "T".to_string(), to: "JsonValue".to_string(), }) .unwrap_or_default() } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ActivateRoutingConfigRequest { pub created_by: String, pub routing_algorithm_id: String, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct ListRountingAlgorithmsRequest { pub created_by: String, } // Maps Hyperswitch `BackendInput` to a `RoutingEvaluateRequest` compatible with Decision Engine pub fn convert_backend_input_to_routing_eval( created_by: String, input: BackendInput, fallback_output: Vec<DeRoutableConnectorChoice>, ) -> RoutingResult<RoutingEvaluateRequest> { let mut params: HashMap<String, Option<ValueType>> = HashMap::new(); // Payment params.insert( "amount".to_string(), Some(ValueType::Number( input .payment .amount .get_amount_as_i64() .try_into() .unwrap_or_default(), )), ); params.insert( "currency".to_string(), Some(ValueType::EnumVariant(input.payment.currency.to_string())), ); if let Some(auth_type) = input.payment.authentication_type { params.insert( "authentication_type".to_string(), Some(ValueType::EnumVariant(auth_type.to_string())), ); } if let Some(bin) = input.payment.card_bin { params.insert("card_bin".to_string(), Some(ValueType::StrValue(bin))); } if let Some(capture_method) = input.payment.capture_method { params.insert( "capture_method".to_string(), Some(ValueType::EnumVariant(capture_method.to_string())), ); } if let Some(country) = input.payment.business_country { params.insert( "business_country".to_string(), Some(ValueType::EnumVariant(country.to_string())), ); } if let Some(country) = input.payment.billing_country { params.insert( "billing_country".to_string(), Some(ValueType::EnumVariant(country.to_string())), ); } if let Some(label) = input.payment.business_label { params.insert( "business_label".to_string(), Some(ValueType::StrValue(label)), ); } if let Some(sfu) = input.payment.setup_future_usage { params.insert( "setup_future_usage".to_string(), Some(ValueType::EnumVariant(sfu.to_string())), ); } // PaymentMethod if let Some(pm) = input.payment_method.payment_method { params.insert( "payment_method".to_string(), Some(ValueType::EnumVariant(pm.to_string())), ); if let Some(pmt) = input.payment_method.payment_method_type { match (pmt, pm).into_dir_value() { Ok(dv) => insert_dirvalue_param(&mut params, dv), Err(e) => logger::debug!( ?e, ?pmt, ?pm, "decision_engine_euclid: into_dir_value failed; skipping subset param" ), } } } if let Some(pmt) = input.payment_method.payment_method_type { params.insert( "payment_method_type".to_string(), Some(ValueType::EnumVariant(pmt.to_string())), ); } if let Some(network) = input.payment_method.card_network { params.insert( "card_network".to_string(), Some(ValueType::EnumVariant(network.to_string())), ); } // Mandate if let Some(pt) = input.mandate.payment_type { params.insert( "payment_type".to_string(), Some(ValueType::EnumVariant(pt.to_string())), ); } if let Some(mt) = input.mandate.mandate_type { params.insert( "mandate_type".to_string(), Some(ValueType::EnumVariant(mt.to_string())), ); } if let Some(mat) = input.mandate.mandate_acceptance_type { params.insert( "mandate_acceptance_type".to_string(), Some(ValueType::EnumVariant(mat.to_string())), ); } // Metadata if let Some(meta) = input.metadata { for (k, v) in meta.into_iter() { params.insert( k.clone(), Some(ValueType::MetadataVariant(MetadataValue { key: k, value: v, })), ); } } Ok(RoutingEvaluateRequest { created_by, parameters: params, fallback_output, }) } // All the independent variants of payment method types, configured via dashboard fn insert_dirvalue_param(params: &mut HashMap<String, Option<ValueType>>, dv: dir::DirValue) { match dv { dir::DirValue::RewardType(v) => { params.insert( "reward".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::CardType(v) => { params.insert( "card".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::PayLaterType(v) => { params.insert( "pay_later".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::WalletType(v) => { params.insert( "wallet".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::VoucherType(v) => { params.insert( "voucher".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::BankRedirectType(v) => { params.insert( "bank_redirect".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::BankDebitType(v) => { params.insert( "bank_debit".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::BankTransferType(v) => { params.insert( "bank_transfer".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::RealTimePaymentType(v) => { params.insert( "real_time_payment".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::UpiType(v) => { params.insert( "upi".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::GiftCardType(v) => { params.insert( "gift_card".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::CardRedirectType(v) => { params.insert( "card_redirect".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::OpenBankingType(v) => { params.insert( "open_banking".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::MobilePaymentType(v) => { params.insert( "mobile_payment".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } dir::DirValue::CryptoType(v) => { params.insert( "crypto".to_string(), Some(ValueType::EnumVariant(v.to_string())), ); } other => { // all other values can be ignored for now as they don't converge with // payment method type logger::warn!( ?other, "decision_engine_euclid: unmapped dir::DirValue; add a mapping here" ); } } } #[derive(Debug, Clone, serde::Deserialize)] struct DeErrorResponse { code: String, message: String, data: Option<serde_json::Value>, } impl DecisionEngineErrorsInterface for DeErrorResponse { fn get_error_message(&self) -> String { self.message.clone() } fn get_error_code(&self) -> String { self.code.clone() } fn get_error_data(&self) -> Option<String> { self.data.as_ref().map(|data| data.to_string()) } } impl DecisionEngineErrorsInterface for or_types::ErrorResponse { fn get_error_message(&self) -> String { self.error_message.clone() } fn get_error_code(&self) -> String { self.error_code.clone() } fn get_error_data(&self) -> Option<String> { Some(format!( "decision_engine Error: {}", self.error_message.clone() )) } } pub type Metadata = HashMap<String, serde_json::Value>; /// Represents a single comparison condition. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Comparison { /// The left hand side which will always be a domain input identifier like "payment.method.cardtype" pub lhs: String, /// The comparison operator pub comparison: ComparisonType, /// The value to compare against pub value: ValueType, /// Additional metadata that the Static Analyzer and Backend does not touch. /// This can be used to store useful information for the frontend and is required for communication /// between the static analyzer and the frontend. // #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Metadata, } /// Represents all the conditions of an IF statement /// eg: /// /// ```text /// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners /// ``` pub type IfCondition = Vec<Comparison>; /// Represents an IF statement with conditions and optional nested IF statements /// /// ```text /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct IfStatement { // #[schema(value_type=Vec<Comparison>)] pub condition: IfCondition, pub nested: Option<Vec<IfStatement>>, } /// Represents a rule /// /// ```text /// rule_name: [stripe, adyen, checkout] /// { /// payment.method = card { /// payment.method.cardtype = (credit, debit) { /// payment.method.network = (amex, rupay, diners) /// } /// /// payment.method.cardtype = credit /// } /// } /// ``` #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] // #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] pub struct Rule { pub name: String, #[serde(alias = "routingType")] pub routing_type: RoutingType, #[serde(alias = "routingOutput")] pub output: Output, pub statements: Vec<IfStatement>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RoutingType { Priority, VolumeSplit, VolumeSplitPriority, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct VolumeSplit<T> { pub split: u8, pub output: T, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct ConnectorInfo { pub gateway_name: String, pub gateway_id: Option<String>, } impl TryFrom<ConnectorInfo> for DeRoutableConnectorChoice { type Error = error_stack::Report<errors::RoutingError>; fn try_from(c: ConnectorInfo) -> Result<Self, Self::Error> { let gateway_id = c .gateway_id .map(|mca| { id_type::MerchantConnectorAccountId::wrap(mca) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string") }) .transpose()?; let gateway_name = RoutableConnectors::from_str(&c.gateway_name) .map_err(|_| errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert connector name to RoutableConnectors")?; Ok(Self { gateway_name, gateway_id, }) } } impl ConnectorInfo { pub fn new(gateway_name: String, gateway_id: Option<String>) -> Self { Self { gateway_name, gateway_id, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Output { Single(ConnectorInfo), Priority(Vec<ConnectorInfo>), VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>), VolumeSplitPriority(Vec<VolumeSplit<Vec<ConnectorInfo>>>), } pub type Globals = HashMap<String, HashSet<ValueType>>; /// The program, having a default connector selection and /// a bunch of rules. Also can hold arbitrary metadata. #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] // #[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)] pub struct Program { pub globals: Globals, pub default_selection: Output, // #[schema(value_type=RuleConnectorSelection)] pub rules: Vec<Rule>, // #[schema(value_type=HashMap<String, serde_json::Value>)] pub metadata: Option<Metadata>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RoutingRule { pub rule_id: Option<String>, pub name: String, pub description: Option<String>, pub metadata: Option<RoutingMetadata>, pub created_by: String, #[serde(default)] pub algorithm_for: AlgorithmType, pub algorithm: StaticRoutingAlgorithm, } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AlgorithmType { #[default] Payment, Payout, ThreeDsAuthentication, } impl From<TransactionType> for AlgorithmType { fn from(transaction_type: TransactionType) -> Self { match transaction_type { TransactionType::Payment => Self::Payment, TransactionType::Payout => Self::Payout, TransactionType::ThreeDsAuthentication => Self::ThreeDsAuthentication, } } } impl From<RoutableConnectorChoice> for ConnectorInfo { fn from(c: RoutableConnectorChoice) -> Self { Self { gateway_name: c.connector.to_string(), gateway_id: c .merchant_connector_id .map(|mca_id| mca_id.get_string_repr().to_string()), } } } impl From<Box<RoutableConnectorChoice>> for ConnectorInfo { fn from(c: Box<RoutableConnectorChoice>) -> Self { Self { gateway_name: c.connector.to_string(), gateway_id: c .merchant_connector_id .map(|mca_id| mca_id.get_string_repr().to_string()), } } } impl From<ConnectorVolumeSplit> for VolumeSplit<ConnectorInfo> { fn from(v: ConnectorVolumeSplit) -> Self { Self { split: v.split, output: ConnectorInfo { gateway_name: v.connector.connector.to_string(), gateway_id: v .connector .merchant_connector_id .map(|mca_id| mca_id.get_string_repr().to_string()), }, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StaticRoutingAlgorithm { Single(Box<ConnectorInfo>), Priority(Vec<ConnectorInfo>), VolumeSplit(Vec<VolumeSplit<ConnectorInfo>>), Advanced(Program), } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct RoutingMetadata { pub kind: enums::RoutingAlgorithmKind, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct RoutingDictionaryRecord { pub rule_id: String, pub name: String, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct RoutingAlgorithmRecord { pub id: id_type::RoutingId, pub name: String, pub description: Option<String>, pub created_by: id_type::ProfileId, pub algorithm_data: StaticRoutingAlgorithm, pub algorithm_for: TransactionType, pub metadata: Option<RoutingMetadata>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, } impl From<RoutingAlgorithmRecord> for routing_algorithm::RoutingProfileMetadata { fn from(record: RoutingAlgorithmRecord) -> Self { let kind = match record.algorithm_data { StaticRoutingAlgorithm::Single(_) => enums::RoutingAlgorithmKind::Single, StaticRoutingAlgorithm::Priority(_) => enums::RoutingAlgorithmKind::Priority, StaticRoutingAlgorithm::VolumeSplit(_) => enums::RoutingAlgorithmKind::VolumeSplit, StaticRoutingAlgorithm::Advanced(_) => enums::RoutingAlgorithmKind::Advanced, }; Self { profile_id: record.created_by, algorithm_id: record.id, name: record.name, description: record.description, kind, created_at: record.created_at, modified_at: record.modified_at, algorithm_for: record.algorithm_for, } } } impl TryFrom<ast::Program<ConnectorSelection>> for Program { type Error = error_stack::Report<errors::RoutingError>; fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> { let rules = p .rules .into_iter() .map(convert_rule) .collect::<Result<Vec<_>, _>>()?; Ok(Self { globals: HashMap::new(), default_selection: convert_output(p.default_selection), rules, metadata: Some(p.metadata), }) } } impl TryFrom<ast::Program<ConnectorSelection>> for StaticRoutingAlgorithm { type Error = error_stack::Report<errors::RoutingError>; fn try_from(p: ast::Program<ConnectorSelection>) -> Result<Self, Self::Error> { let internal_program: Program = p.try_into()?; Ok(Self::Advanced(internal_program)) } } fn convert_rule(rule: ast::Rule<ConnectorSelection>) -> RoutingResult<Rule> { let routing_type = match &rule.connector_selection { ConnectorSelection::Priority(_) => RoutingType::Priority, ConnectorSelection::VolumeSplit(_) => RoutingType::VolumeSplit, }; Ok(Rule { name: rule.name, routing_type, output: convert_output(rule.connector_selection), statements: rule .statements .into_iter() .map(convert_if_stmt) .collect::<RoutingResult<Vec<IfStatement>>>()?, }) } fn convert_if_stmt(stmt: ast::IfStatement) -> RoutingResult<IfStatement> { Ok(IfStatement { condition: stmt .condition .into_iter() .map(convert_comparison) .collect::<RoutingResult<Vec<Comparison>>>()?, nested: stmt .nested .map(|v| { v.into_iter() .map(convert_if_stmt) .collect::<RoutingResult<Vec<IfStatement>>>() }) .transpose()?, }) } fn convert_comparison(c: ast::Comparison) -> RoutingResult<Comparison> { Ok(Comparison { lhs: c.lhs, comparison: convert_comparison_type(c.comparison), value: convert_value(c.value)?, metadata: c.metadata, }) } fn convert_comparison_type(ct: ast::ComparisonType) -> ComparisonType { match ct { ast::ComparisonType::Equal => ComparisonType::Equal, ast::ComparisonType::NotEqual => ComparisonType::NotEqual, ast::ComparisonType::LessThan => ComparisonType::LessThan, ast::ComparisonType::LessThanEqual => ComparisonType::LessThanEqual, ast::ComparisonType::GreaterThan => ComparisonType::GreaterThan, ast::ComparisonType::GreaterThanEqual => ComparisonType::GreaterThanEqual, } } fn convert_value(v: ast::ValueType) -> RoutingResult<ValueType> { use ast::ValueType::*; match v { Number(n) => Ok(ValueType::Number( n.get_amount_as_i64().try_into().unwrap_or_default(), )), EnumVariant(e) => Ok(ValueType::EnumVariant(e)), MetadataVariant(m) => Ok(ValueType::MetadataVariant(MetadataValue { key: m.key, value: m.value, })), StrValue(s) => Ok(ValueType::StrValue(s)), NumberArray(arr) => Ok(ValueType::NumberArray( arr.into_iter() .map(|n| n.get_amount_as_i64().try_into().unwrap_or_default()) .collect(), )), EnumVariantArray(arr) => Ok(ValueType::EnumVariantArray(arr)), NumberComparisonArray(arr) => Ok(ValueType::NumberComparisonArray( arr.into_iter() .map(|nc| NumberComparison { comparison_type: convert_comparison_type(nc.comparison_type), number: nc.number.get_amount_as_i64().try_into().unwrap_or_default(), }) .collect(), )), } } fn convert_output(sel: ConnectorSelection) -> Output { match sel { ConnectorSelection::Priority(choices) => { Output::Priority(choices.into_iter().map(stringify_choice).collect()) } ConnectorSelection::VolumeSplit(vs) => Output::VolumeSplit( vs.into_iter() .map(|v| VolumeSplit { split: v.split, output: stringify_choice(v.connector), }) .collect(), ), } } fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo { ConnectorInfo::new( c.connector.to_string(), c.merchant_connector_id .map(|mca_id| mca_id.get_string_repr().to_string()), ) } pub async fn select_routing_result<T>( state: &SessionState, business_profile: &business_profile::Profile, hyperswitch_result: T, de_result: T, ) -> T { let routing_result_source: Option<api_routing::RoutingResultSource> = state .store .find_config_by_key(&format!( "routing_result_source_{0}", business_profile.get_id().get_string_repr() )) .await .map(|c| c.config.parse_enum("RoutingResultSource").ok()) .unwrap_or(None); //Ignore errors so that we can use the hyperswitch result as a fallback if let Some(api_routing::RoutingResultSource::DecisionEngine) = routing_result_source { logger::debug!(business_profile_id=?business_profile.get_id(), "Using Decision Engine routing result"); de_result } else { logger::debug!(business_profile_id=?business_profile.get_id(), "Using Hyperswitch routing result"); hyperswitch_result } } pub trait DecisionEngineErrorsInterface { fn get_error_message(&self) -> String; fn get_error_code(&self) -> String; fn get_error_data(&self) -> Option<String>; } #[derive(Debug)] pub struct RoutingEventsWrapper<Req> where Req: Serialize + Clone, { pub tenant_id: id_type::TenantId, pub request_id: Option<RequestId>, pub payment_id: String, pub profile_id: id_type::ProfileId, pub merchant_id: id_type::MerchantId, pub flow: String, pub request: Option<Req>, pub parse_response: bool, pub log_event: bool, pub routing_event: Option<routing_events::RoutingEvent>, } #[derive(Debug)] pub enum EventResponseType<Res> where Res: Serialize + serde::de::DeserializeOwned + Clone, { Structured(Res), String(String), } #[derive(Debug, Serialize)] pub struct RoutingEventsResponse<Res> where Res: Serialize + serde::de::DeserializeOwned + Clone, { pub event: Option<routing_events::RoutingEvent>, pub response: Option<Res>, } impl<Res> RoutingEventsResponse<Res> where Res: Serialize + serde::de::DeserializeOwned + Clone, { pub fn new(event: Option<routing_events::RoutingEvent>, response: Option<Res>) -> Self { Self { event, response } } pub fn set_response(&mut self, response: Res) { self.response = Some(response); } pub fn set_event(&mut self, event: routing_events::RoutingEvent) { self.event = Some(event); } } impl<Req> RoutingEventsWrapper<Req> where Req: Serialize + Clone, { #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: id_type::TenantId, request_id: Option<RequestId>, payment_id: String, profile_id: id_type::ProfileId, merchant_id: id_type::MerchantId, flow: String, request: Option<Req>, parse_response: bool, log_event: bool, ) -> Self { Self { tenant_id, request_id, payment_id, profile_id, merchant_id, flow, request, parse_response, log_event, routing_event: None, } } pub fn construct_event_builder( self, url: String, routing_engine: routing_events::RoutingEngine, method: routing_events::ApiMethod, ) -> RoutingResult<Self> { let mut wrapper = self; let request = wrapper .request .clone() .ok_or(errors::RoutingError::RoutingEventsError { message: "Request body is missing".to_string(), status_code: 400, })?; let serialized_request = serde_json::to_value(&request) .change_context(errors::RoutingError::RoutingEventsError { message: "Failed to serialize RoutingRequest".to_string(), status_code: 500, }) .attach_printable("Failed to serialize request body")?; let routing_event = routing_events::RoutingEvent::new( wrapper.tenant_id.clone(), "".to_string(), &wrapper.flow, serialized_request, url, method, wrapper.payment_id.clone(), wrapper.profile_id.clone(), wrapper.merchant_id.clone(), wrapper.request_id, routing_engine, ); wrapper.set_routing_event(routing_event); Ok(wrapper) } pub async fn trigger_event<Res, F, Fut>( self, state: &SessionState, func: F, ) -> RoutingResult<RoutingEventsResponse<Res>> where F: FnOnce() -> Fut + Send, Res: Serialize + serde::de::DeserializeOwned + Clone, Fut: futures::Future<Output = RoutingResult<Option<Res>>> + Send, { let mut routing_event = self.routing_event .ok_or(errors::RoutingError::RoutingEventsError { message: "Routing event is missing".to_string(), status_code: 500, })?; let mut response = RoutingEventsResponse::new(None, None); let resp = func().await; match resp { Ok(ok_resp) => { if let Some(resp) = ok_resp { routing_event.set_response_body(&resp); // routing_event // .set_routable_connectors(ok_resp.get_routable_connectors().unwrap_or_default()); // routing_event.set_payment_connector(ok_resp.get_payment_connector()); routing_event.set_status_code(200); response.set_response(resp.clone()); self.log_event .then(|| state.event_handler().log_event(&routing_event)); } } Err(err) => { // Need to figure out a generic way to log errors routing_event .set_error(serde_json::json!({"error": err.current_context().to_string()})); match err.current_context() { errors::RoutingError::RoutingEventsError { status_code, .. } => { routing_event.set_status_code(*status_code); } _ => { routing_event.set_status_code(500); } } state.event_handler().log_event(&routing_event) } } response.set_event(routing_event); Ok(response) } pub fn set_log_event(&mut self, log_event: bool) { self.log_event = log_event; } pub fn set_request_body(&mut self, request: Req) { self.request = Some(request); } pub fn set_routing_event(&mut self, routing_event: routing_events::RoutingEvent) { self.routing_event = Some(routing_event); } } pub trait RoutingEventsInterface { fn get_routable_connectors(&self) -> Option<Vec<RoutableConnectorChoice>>; fn get_payment_connector(&self) -> Option<RoutableConnectorChoice>; } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateConfigEventRequest { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub specificity_level: api_routing::SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, } impl From<&api_routing::SuccessBasedRoutingConfigBody> for CalSuccessRateConfigEventRequest { fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self { Self { min_aggregates_size: value.min_aggregates_size, default_success_rate: value.default_success_rate, specificity_level: value.specificity_level, exploration_percent: value.exploration_percent, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<CalSuccessRateConfigEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventBucketConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } impl From<&api_routing::EliminationAnalyserConfig> for EliminationRoutingEventBucketConfig { fn from(value: &api_routing::EliminationAnalyserConfig) -> Self { Self { bucket_size: value.bucket_size, bucket_leak_interval_in_secs: value.bucket_leak_interval_in_secs, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<EliminationRoutingEventBucketConfig>, } /// API-1 types #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalContractScoreEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<api_routing::ContractBasedRoutingConfig>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithScoreEventResponse { pub score: f64, pub label: String, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventResponse { pub labels_with_score: Vec<LabelWithScoreEventResponse>, pub routing_approach: RoutingApproach, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl TryFrom<&ir_client::success_rate_client::CalSuccessRateResponse> for CalSuccessRateEventResponse { type Error = errors::RoutingError; fn try_from( value: &ir_client::success_rate_client::CalSuccessRateResponse, ) -> Result<Self, Self::Error> { Ok(Self { labels_with_score: value .labels_with_score .iter() .map(|l| LabelWithScoreEventResponse { score: l.score, label: l.label.clone(), }) .collect(), routing_approach: match value.routing_approach { 0 => RoutingApproach::Exploration, 1 => RoutingApproach::Exploitation, _ => { return Err(errors::RoutingError::GenericNotFoundError { field: "unknown routing approach from dynamic routing service".to_string(), }) } }, }) } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RoutingApproach { Exploitation, Exploration, Elimination, ContractBased, StaticRouting, Default, } impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::Exploitation, "SR_V3_HEDGING" => Self::Exploration, _ => Self::Default, } } } impl From<RoutingApproach> for common_enums::RoutingApproach { fn from(approach: RoutingApproach) -> Self { match approach { RoutingApproach::Exploitation => Self::SuccessRateExploitation, RoutingApproach::Exploration => Self::SuccessRateExploration, RoutingApproach::ContractBased => Self::ContractBasedRouting, RoutingApproach::StaticRouting => Self::RuleBasedRouting, _ => Self::DefaultFallback, } } } impl std::fmt::Display for RoutingApproach { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Exploitation => write!(f, "Exploitation"), Self::Exploration => write!(f, "Exploration"), Self::Elimination => write!(f, "Elimination"), Self::ContractBased => write!(f, "ContractBased"), Self::StaticRouting => write!(f, "StaticRouting"), Self::Default => write!(f, "Default"), } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct BucketInformationEventResponse { pub is_eliminated: bool, pub bucket_name: Vec<String>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationInformationEventResponse { pub entity: Option<BucketInformationEventResponse>, pub global: Option<BucketInformationEventResponse>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithStatusEliminationEventResponse { pub label: String, pub elimination_information: Option<EliminationInformationEventResponse>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationEventResponse { pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl From<&ir_client::elimination_based_client::EliminationResponse> for EliminationEventResponse { fn from(value: &ir_client::elimination_based_client::EliminationResponse) -> Self { Self { labels_with_status: value .labels_with_status .iter() .map( |label_with_status| LabelWithStatusEliminationEventResponse { label: label_with_status.label.clone(), elimination_information: label_with_status .elimination_information .as_ref() .map(|info| EliminationInformationEventResponse { entity: info.entity.as_ref().map(|entity_info| { BucketInformationEventResponse { is_eliminated: entity_info.is_eliminated, bucket_name: entity_info.bucket_name.clone(), } }), global: info.global.as_ref().map(|global_info| { BucketInformationEventResponse { is_eliminated: global_info.is_eliminated, bucket_name: global_info.bucket_name.clone(), } }), }), }, ) .collect(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct ScoreDataEventResponse { pub score: f64, pub label: String, pub current_count: u64, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalContractScoreEventResponse { pub labels_with_score: Vec<ScoreDataEventResponse>, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl From<&ir_client::contract_routing_client::CalContractScoreResponse> for CalContractScoreEventResponse { fn from(value: &ir_client::contract_routing_client::CalContractScoreResponse) -> Self { Self { labels_with_score: value .labels_with_score .iter() .map(|label_with_score| ScoreDataEventResponse { score: label_with_score.score, label: label_with_score.label.clone(), current_count: label_with_score.current_count, }) .collect(), } } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalGlobalSuccessRateConfigEventRequest { pub entity_min_aggregates_size: u32, pub entity_default_success_rate: f64, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalGlobalSuccessRateEventRequest { pub entity_id: String, pub entity_params: String, pub entity_labels: Vec<String>, pub global_labels: Vec<String>, pub config: Option<CalGlobalSuccessRateConfigEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateSuccessRateWindowConfig { pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<api_routing::CurrentBlockThreshold>, } impl From<&api_routing::SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig { fn from(value: &api_routing::SuccessBasedRoutingConfigBody) -> Self { Self { max_aggregates_size: value.max_aggregates_size, current_block_threshold: value.current_block_threshold.clone(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateLabelWithStatusEventRequest { pub label: String, pub status: bool, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateSuccessRateWindowEventRequest { pub id: String, pub params: String, pub labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, pub config: Option<UpdateSuccessRateWindowConfig>, pub global_labels_with_status: Vec<UpdateLabelWithStatusEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateSuccessRateWindowEventResponse { pub status: UpdationStatusEventResponse, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl TryFrom<&ir_client::success_rate_client::UpdateSuccessRateWindowResponse> for UpdateSuccessRateWindowEventResponse { type Error = errors::RoutingError; fn try_from( value: &ir_client::success_rate_client::UpdateSuccessRateWindowResponse, ) -> Result<Self, Self::Error> { Ok(Self { status: match value.status { 0 => UpdationStatusEventResponse::WindowUpdationSucceeded, 1 => UpdationStatusEventResponse::WindowUpdationFailed, _ => { return Err(errors::RoutingError::GenericNotFoundError { field: "unknown updation status from dynamic routing service".to_string(), }) } }, }) } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum UpdationStatusEventResponse { WindowUpdationSucceeded, WindowUpdationFailed, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithBucketNameEventRequest { pub label: String, pub bucket_name: String, } impl From<&api_routing::RoutableConnectorChoiceWithBucketName> for LabelWithBucketNameEventRequest { fn from(value: &api_routing::RoutableConnectorChoiceWithBucketName) -> Self { Self { label: value.routable_connector_choice.to_string(), bucket_name: value.bucket_name.clone(), } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateEliminationBucketEventRequest { pub id: String, pub params: String, pub labels_with_bucket_name: Vec<LabelWithBucketNameEventRequest>, pub config: Option<EliminationRoutingEventBucketConfig>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateEliminationBucketEventResponse { pub status: EliminationUpdationStatusEventResponse, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl TryFrom<&ir_client::elimination_based_client::UpdateEliminationBucketResponse> for UpdateEliminationBucketEventResponse { type Error = errors::RoutingError; fn try_from( value: &ir_client::elimination_based_client::UpdateEliminationBucketResponse, ) -> Result<Self, Self::Error> { Ok(Self { status: match value.status { 0 => EliminationUpdationStatusEventResponse::BucketUpdationSucceeded, 1 => EliminationUpdationStatusEventResponse::BucketUpdationFailed, _ => { return Err(errors::RoutingError::GenericNotFoundError { field: "unknown updation status from dynamic routing service".to_string(), }) } }, }) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum EliminationUpdationStatusEventResponse { BucketUpdationSucceeded, BucketUpdationFailed, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct ContractLabelInformationEventRequest { pub label: String, pub target_count: u64, pub target_time: u64, pub current_count: u64, } impl From<&api_routing::LabelInformation> for ContractLabelInformationEventRequest { fn from(value: &api_routing::LabelInformation) -> Self { Self { label: value.label.clone(), target_count: value.target_count, target_time: value.target_time, current_count: 1, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateContractRequestEventRequest { pub id: String, pub params: String, pub labels_information: Vec<ContractLabelInformationEventRequest>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct UpdateContractEventResponse { pub status: ContractUpdationStatusEventResponse, } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] impl TryFrom<&ir_client::contract_routing_client::UpdateContractResponse> for UpdateContractEventResponse { type Error = errors::RoutingError; fn try_from( value: &ir_client::contract_routing_client::UpdateContractResponse, ) -> Result<Self, Self::Error> { Ok(Self { status: match value.status { 0 => ContractUpdationStatusEventResponse::ContractUpdationSucceeded, 1 => ContractUpdationStatusEventResponse::ContractUpdationFailed, _ => { return Err(errors::RoutingError::GenericNotFoundError { field: "unknown updation status from dynamic routing service".to_string(), }) } }, }) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ContractUpdationStatusEventResponse { ContractUpdationSucceeded, ContractUpdationFailed, }
{ "crate": "router", "file": "crates/router/src/core/payments/routing/utils.rs", "file_size": 74598, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-2772609402682719321
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/operations/payment_create.rs // File size: 70419 bytes use std::marker::PhantomData; use api_models::{ enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData, payments::GetAddressFromPaymentMethodData, }; use async_trait::async_trait; use common_types::payments as common_payments_types; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, MinorUnit, }, }; use diesel_models::{ ephemeral_key, payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId, }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ mandates::MandateDetails, payments::{ payment_attempt::PaymentAttempt, payment_intent::CustomerData, FromRequestEncryptablePaymentIntent, }, }; use masking::{ExposeInterface, PeekInterface, Secret}; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use time::PrimitiveDateTime; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ consts, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, payment_link, payment_methods::cards::create_encrypted_data, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, utils as core_utils, }, db::StorageInterface, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ self, api::{self, ConnectorCallType, PaymentIdTypeExt}, domain, storage::{ self, enums::{self, IntentStatus}, }, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::{self, OptionExt}, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "authorize")] pub struct PaymentCreate; type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>; /// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments /// This will create all the entities required for a new payment from the request #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_context).await; let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let money @ (amount, currency) = payments_create_request_validation(request)?; let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v1")] helpers::validate_business_details( request.business_country, request.business_label.as_ref(), merchant_context, )?; // If profile id is not passed, get it from the business_country and business_label #[cfg(feature = "v1")] let profile_id = core_utils::get_profile_id_from_business_details( key_manager_state, request.business_country, request.business_label.as_ref(), merchant_context, request.profile_id.as_ref(), &*state.store, true, ) .await?; // Profile id will be mandatory in v2 in the request / headers #[cfg(feature = "v2")] let profile_id = request .profile_id .clone() .get_required_value("profile_id") .attach_printable("Profile id is a mandatory parameter")?; // TODO: eliminate a redundant db call to fetch the business profile // Validate whether profile_id passed in request is valid and is linked to the merchant let business_profile = if let Some(business_profile) = core_utils::validate_and_get_business_profile( db, key_manager_state, merchant_context.get_merchant_key_store(), Some(&profile_id), merchant_id, ) .await? { business_profile } else { db.find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })? }; let customer_acceptance = request.customer_acceptance.clone(); let recurring_details = request.recurring_details.clone(); let mandate_type = m_helpers::get_mandate_type( request.mandate_data.clone(), request.off_session, request.setup_future_usage, request.customer_acceptance.clone(), request.payment_token.clone(), request.payment_method, ) .change_context(errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of recurring_details and mandate_data but got both".into(), })?; let m_helpers::MandateGenericData { token, payment_method, payment_method_type, mandate_data, recurring_mandate_payment_data, mandate_connector, payment_method_info, } = helpers::get_token_pm_type_mandate_details( state, request, mandate_type, merchant_context, None, None, ) .await?; helpers::validate_allowed_payment_method_types_request( state, &profile_id, merchant_context, request.allowed_payment_method_types.clone(), ) .await?; let customer_details = helpers::get_customer_details_from_request(request); let shipping_address = helpers::create_or_find_address_for_payment_by_request( state, request.shipping.as_ref(), None, merchant_id, customer_details.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( state, request.billing.as_ref(), None, merchant_id, customer_details.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing_address = helpers::create_or_find_address_for_payment_by_request( state, request .payment_method_data .as_ref() .and_then(|pmd| pmd.billing.as_ref()), None, merchant_id, customer_details.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let browser_info = request .browser_info .clone() .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id( &state.conf, merchant_id, ) { payment_id.get_string_repr().to_string() } else { payment_id.get_attempt_id(1) }; let session_expiry = common_utils::date_time::now().saturating_add(time::Duration::seconds( request.session_expiry.map(i64::from).unwrap_or( business_profile .session_expiry .unwrap_or(consts::DEFAULT_SESSION_EXPIRY), ), )); let payment_link_data = match request.payment_link { Some(true) => { let merchant_name = merchant_context .get_merchant_account() .merchant_name .clone() .map(|name| name.into_inner().peek().to_owned()) .unwrap_or_default(); let default_domain_name = state.base_url.clone(); let (payment_link_config, domain_name) = payment_link::get_payment_link_config_based_on_priority( request.payment_link_config.clone(), business_profile.payment_link_config.clone(), merchant_name, default_domain_name, request.payment_link_config_id.clone(), )?; create_payment_link( request, payment_link_config, merchant_id, payment_id.clone(), db, amount, request.description.clone(), profile_id.clone(), domain_name, session_expiry, header_payload.locale.clone(), ) .await? } _ => None, }; let payment_intent_new = Self::make_payment_intent( state, &payment_id, merchant_context, money, request, shipping_address .as_ref() .map(|address| address.address_id.clone()), payment_link_data.clone(), billing_address .as_ref() .map(|address| address.address_id.clone()), attempt_id, profile_id.clone(), session_expiry, &business_profile, request.is_payment_id_from_merchant, ) .await?; let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt( &payment_id, merchant_id, &merchant_context.get_merchant_account().organization_id, money, payment_method, payment_method_type, request, browser_info, state, payment_method_billing_address .as_ref() .map(|address| address.address_id.clone()), &payment_method_info, merchant_context.get_merchant_key_store(), profile_id, &customer_acceptance, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_intent = db .insert_payment_intent( key_manager_state, payment_intent_new, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; if let Some(order_details) = &request.order_details { helpers::validate_order_details_amount( order_details.to_owned(), payment_intent.amount, false, )?; } #[cfg(feature = "v1")] let mut payment_attempt = db .insert_payment_attempt(payment_attempt_new, storage_scheme) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; #[cfg(feature = "v2")] let payment_attempt = db .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt_new, storage_scheme, ) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; let mandate_details_present = payment_attempt.mandate_details.is_some(); helpers::validate_mandate_data_and_future_usage( request.setup_future_usage, mandate_details_present, )?; // connector mandate reference update history let mandate_id = request .mandate_id .as_ref() .or_else(|| { request.recurring_details .as_ref() .and_then(|recurring_details| match recurring_details { RecurringDetails::MandateId(id) => Some(id), _ => None, }) }) .async_and_then(|mandate_id| async { let mandate = db .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound); Some(mandate.and_then(|mandate_obj| { match ( mandate_obj.network_transaction_id, mandate_obj.connector_mandate_ids, ) { (_, Some(connector_mandate_id)) => connector_mandate_id .parse_value("ConnectorMandateId") .change_context(errors::ApiErrorResponse::MandateNotFound) .map(|connector_id: api_models::payments::ConnectorMandateReferenceId| { api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( connector_id.get_connector_mandate_id(), connector_id.get_payment_method_id(), None, None, connector_id.get_connector_mandate_request_reference_id(), ) )) } }), (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some( api_models::payments::MandateReferenceId::NetworkMandateId( network_tx_id, ), ), }), (_, _) => Ok(api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: None, }), } })) }) .await .transpose()?; let mandate_id = if mandate_id.is_none() { request .recurring_details .as_ref() .and_then(|recurring_details| match recurring_details { RecurringDetails::ProcessorPaymentToken(token) => { Some(api_models::payments::MandateIds { mandate_id: None, mandate_reference_id: Some( api_models::payments::MandateReferenceId::ConnectorMandateId( api_models::payments::ConnectorMandateReferenceId::new( Some(token.processor_payment_token.clone()), None, None, None, None, ), ), ), }) } _ => None, }) } else { mandate_id }; let operation = payments::if_not_create_change_operation::<_, F>( payment_intent.status, request.confirm, self, ); let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; // The operation merges mandate data from both request and payment_attempt let setup_mandate = mandate_data; let surcharge_details = request.surcharge_details.map(|request_surcharge_details| { payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt)) }); let payment_method_data_after_card_bin_call = request .payment_method_data .as_ref() .and_then(|payment_method_data_from_request| { payment_method_data_from_request .payment_method_data .as_ref() }) .zip(additional_payment_data) .map(|(payment_method_data, additional_payment_data)| { payment_method_data.apply_additional_payment_data(additional_payment_data) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Card cobadge check failed due to an invalid card network regex")?; let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info { let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm .payment_method_data .clone() .map(|x| x.into_inner().expose()) .and_then(|v| { v.parse_value("PaymentMethodsData") .map_err(|err| { router_env::logger::info!( "PaymentMethodsData deserialization failed: {:?}", err ) }) .ok() }) .and_then(|pmd| match pmd { PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), _ => None, }); card_detail_from_locker.map(|card_details| { let additional_data = card_details.into(); api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data)) }) } else { None }; // Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() { payment_attempt.payment_method_data = Some( Encode::encode_to_value(additional_pm_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?, ); } let amount = payment_attempt.get_total_amount().into(); payment_attempt.connector_mandate_detail = Some(DieselConnectorMandateReferenceId::foreign_from( api_models::payments::ConnectorMandateReferenceId::new( None, None, None, // update_history None, // mandate_metadata Some(common_utils::generate_id_with_len( consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH, )), // connector_mandate_request_reference_id ), )); let address = PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing_address.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ); let payment_method_data_billing = request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.as_ref()) .and_then(|payment_method_data_billing| { payment_method_data_billing.get_billing_address() }) .map(From::from); let unified_address = address.unify_with_payment_method_data_billing(payment_method_data_billing); let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: request.email.clone(), mandate_id: mandate_id.clone(), mandate_connector, setup_mandate, customer_acceptance, token, address: unified_address, token_data: None, confirm: request.confirm, payment_method_data: payment_method_data_after_card_bin_call.map(Into::into), payment_method_token: None, payment_method_info, refunds: vec![], disputes: vec![], attempts: None, force_sync: None, all_keys_required: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data, ephemeral_key, multiple_capture_data: None, redirect_response: None, surcharge_details, frm_message: None, payment_link_data, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, is_l2_l3_enabled: business_profile.is_l2_l3_enabled, }; let get_trackers_response = operations::GetTrackerResponse { operation, customer_details: Some(customer_details), payment_data, business_profile, mandate_type, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentCreate { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(PaymentCreateOperation<'a, F>, Option<domain::Customer>), errors::StorageError> { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } async fn payments_dynamic_tax_calculation<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, _connector_call_type: &ConnectorCallType, business_profile: &domain::Profile, merchant_context: &domain::MerchantContext, ) -> CustomResult<(), errors::ApiErrorResponse> { let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled(); let skip_external_tax_calculation = payment_data .payment_intent .skip_external_tax_calculation .unwrap_or(false); if is_tax_connector_enabled && !skip_external_tax_calculation { let db = state.store.as_ref(); let key_manager_state: &KeyManagerState = &state.into(); let merchant_connector_id = business_profile .tax_connector_id .as_ref() .get_required_value("business_profile.tax_connector_id")?; #[cfg(feature = "v1")] let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &business_profile.merchant_id, merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, )?; #[cfg(feature = "v2")] let mca = db .find_merchant_connector_account_by_id( key_manager_state, merchant_connector_id, key_store, ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, )?; let connector_data = api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?; let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data( state, merchant_context, payment_data, &mca, ) .await?; let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::CalculateTax, types::PaymentsTaxCalculationData, types::TaxCalculationResponseData, > = connector_data.connector.get_connector_integration(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Tax connector Response Failed")?; let tax_response = response.response.map_err(|err| { errors::ApiErrorResponse::ExternalConnectorError { code: err.code, message: err.message, connector: connector_data.connector_name.clone().to_string(), status_code: err.status_code, reason: err.reason, } })?; payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount: tax_response.order_tax_amount, }), payment_method_type: None, }); Ok(()) } else { Ok(()) } } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut PaymentData<F>, storage_scheme: enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( PaymentCreateOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { Box::pin(helpers::make_pm_data( Box::new(self), state, payment_data, merchant_key_store, customer, storage_scheme, business_profile, should_retry_with_pan, )) .await } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, _state: &'a SessionState, _payment_attempt: &PaymentAttempt, _requeue: bool, _schedule_time: Option<PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentCreateOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let status = match payment_data.payment_intent.status { IntentStatus::RequiresPaymentMethod => match payment_data.payment_method_data { Some(_) => Some(IntentStatus::RequiresConfirmation), _ => None, }, IntentStatus::RequiresConfirmation => { if let Some(true) = payment_data.confirm { //TODO: do this later, request validation should happen before Some(IntentStatus::Processing) } else { None } } _ => None, }; let payment_token = payment_data.token.clone(); let connector = payment_data.payment_attempt.connector.clone(); let straight_through_algorithm = payment_data .payment_attempt .straight_through_algorithm .clone(); let authorized_amount = payment_data.payment_attempt.get_total_amount(); let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let surcharge_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.surcharge_amount); let tax_amount = payment_data .surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.tax_on_surcharge_amount); let routing_approach = payment_data.payment_attempt.routing_approach.clone(); let is_stored_credential = helpers::is_stored_credential( &payment_data.recurring_details, &payment_data.pm_token, payment_data.mandate_id.is_some(), payment_data.payment_attempt.is_stored_credential, ); payment_data.payment_attempt = state .store .update_payment_attempt_with_attempt_id( payment_data.payment_attempt, storage::PaymentAttemptUpdate::UpdateTrackers { payment_token, connector, straight_through_algorithm, amount_capturable: match payment_data.confirm.unwrap_or(true) { true => Some(authorized_amount), false => None, }, surcharge_amount, tax_amount, updated_by: storage_scheme.to_string(), merchant_connector_id, routing_approach, is_stored_credential, }, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let customer_id = payment_data.payment_intent.customer_id.clone(); let raw_customer_details = customer .map(|customer| CustomerData::foreign_try_from(customer.clone())) .transpose()?; let key_manager_state = state.into(); // Updation of Customer Details for the cases where both customer_id and specific customer // details are provided in Payment Create Request let customer_details = raw_customer_details .clone() .async_map(|customer_details| { create_encrypted_data(&key_manager_state, key_store, customer_details) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?; payment_data.payment_intent = state .store .update_payment_intent( &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::PaymentCreateUpdate { return_url: None, status, customer_id, shipping_address_id: None, billing_address_id: None, customer_details, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentCreate)) .with(payment_data.to_event()) .emit(); // payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id); Ok(( payments::is_confirm(self, payment_data.confirm), payment_data, )) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>> for PaymentCreate { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentCreateOperation<'b, F>, operations::ValidateResult)> { helpers::validate_customer_information(request)?; if let Some(amount) = request.amount { helpers::validate_max_amount(amount)?; } if let Some(session_expiry) = &request.session_expiry { helpers::validate_session_expiry(session_expiry.to_owned())?; } if let Some(payment_link) = &request.payment_link { if *payment_link { helpers::validate_payment_link_request(request)?; } }; let payment_id = request.payment_id.clone().ok_or(error_stack::report!( errors::ApiErrorResponse::PaymentNotFound ))?; let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?; helpers::validate_request_amount_and_amount_to_capture( request.amount, request.amount_to_capture, request.surcharge_details, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount_to_capture".to_string(), expected_format: "amount_to_capture lesser than amount".to_string(), })?; helpers::validate_amount_to_capture_and_capture_method(None, request)?; helpers::validate_card_data( request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone()), )?; helpers::validate_payment_method_fields_present(request)?; let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, &request.mandate_id, )?; request.validate_stored_credential().change_context( errors::ApiErrorResponse::InvalidRequestData { message: "is_stored_credential should be true when reusing stored payment method data" .to_string(), }, )?; helpers::validate_overcapture_request( &request.enable_overcapture, &request.capture_method, )?; request.validate_mit_request().change_context( errors::ApiErrorResponse::InvalidRequestData { message: "`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`." .to_string(), }, )?; if request.confirm.unwrap_or(false) { helpers::validate_pm_or_token_given( &request.payment_method, &request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone()), &request.payment_method_type, &mandate_type, &request.payment_token, &request.ctp_service_details, )?; helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), request.customer_id.as_ref().or(request .customer .as_ref() .map(|customer| customer.id.clone()) .as_ref()), )?; } if request.split_payments.is_some() { let amount = request.amount.get_required_value("amount")?; helpers::validate_platform_request_for_marketplace( amount, request.split_payments.clone(), )?; }; let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request .routing .clone() .map(|val| val.parse_value("RoutingAlgorithm")) .transpose() .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid straight through routing rules format".to_string(), }) .attach_printable("Invalid straight through routing rules format")?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id, storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: matches!( request.retry_action, Some(api_models::enums::RetryAction::Requeue) ), }, )) } } impl PaymentCreate { #[cfg(feature = "v2")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn make_payment_attempt( payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, money: (api::Amount, enums::Currency), payment_method: Option<enums::PaymentMethod>, payment_method_type: Option<enums::PaymentMethodType>, request: &api::PaymentsRequest, browser_info: Option<serde_json::Value>, state: &SessionState, payment_method_billing_address_id: Option<String>, payment_method_info: &Option<domain::PaymentMethod>, _key_store: &domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, customer_acceptance: &Option<payments::CustomerAcceptance>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( storage::PaymentAttemptNew, Option<api_models::payments::AdditionalPaymentData>, )> { todo!() } #[cfg(feature = "v1")] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn make_payment_attempt( payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, organization_id: &common_utils::id_type::OrganizationId, money: (api::Amount, enums::Currency), payment_method: Option<enums::PaymentMethod>, payment_method_type: Option<enums::PaymentMethodType>, request: &api::PaymentsRequest, browser_info: Option<serde_json::Value>, state: &SessionState, optional_payment_method_billing_address_id: Option<String>, payment_method_info: &Option<domain::PaymentMethod>, key_store: &domain::MerchantKeyStore, profile_id: common_utils::id_type::ProfileId, customer_acceptance: &Option<common_payments_types::CustomerAcceptance>, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( storage::PaymentAttemptNew, Option<api_models::payments::AdditionalPaymentData>, )> { let payment_method_data = request .payment_method_data .as_ref() .and_then(|payment_method_data_request| { payment_method_data_request.payment_method_data.as_ref() }); let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now()); let status = helpers::payment_attempt_status_fsm(payment_method_data, request.confirm); let (amount, currency) = (money.0, Some(money.1)); let mut additional_pm_data = request .payment_method_data .as_ref() .and_then(|payment_method_data_request| { payment_method_data_request.payment_method_data.clone() }) .async_map(|payment_method_data| async { helpers::get_additional_payment_data( &payment_method_data.into(), &*state.store, &profile_id, ) .await }) .await .transpose()? .flatten(); if additional_pm_data.is_none() { // If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object additional_pm_data = payment_method_info.as_ref().and_then(|pm_info| { pm_info .payment_method_data .clone() .map(|x| x.into_inner().expose()) .and_then(|v| { serde_json::from_value::<PaymentMethodsData>(v) .map_err(|err| { logger::error!( "Unable to deserialize payment methods data: {:?}", err ) }) .ok() }) .and_then(|pmd| match pmd { PaymentMethodsData::Card(card) => { Some(api_models::payments::AdditionalPaymentData::Card(Box::new( api::CardDetailFromLocker::from(card).into(), ))) } PaymentMethodsData::WalletDetails(wallet) => match payment_method_type { Some(enums::PaymentMethodType::ApplePay) => { Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: api::payments::ApplepayPaymentMethod::try_from( wallet, ) .inspect_err(|err| { logger::error!( "Unable to transform PaymentMethodDataWalletInfo to ApplepayPaymentMethod: {:?}", err ) }) .ok(), google_pay: None, samsung_pay: None, }) } Some(enums::PaymentMethodType::GooglePay) => { Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: Some(wallet.into()), samsung_pay: None, }) } Some(enums::PaymentMethodType::SamsungPay) => { Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: Some(wallet.into()), }) } _ => None, }, _ => None, }) .or_else(|| match payment_method_type { Some(enums::PaymentMethodType::Paypal) => { Some(api_models::payments::AdditionalPaymentData::Wallet { apple_pay: None, google_pay: None, samsung_pay: None, }) } _ => None, }) }); }; let additional_pm_data_value = additional_pm_data .as_ref() .map(Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encode additional pm data")?; let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id( &state.conf, merchant_id, ) { payment_id.get_string_repr().to_owned() } else { payment_id.get_attempt_id(1) }; if request.mandate_data.as_ref().is_some_and(|mandate_data| { mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some() }) { Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? } let mandate_data = if let Some(update_id) = request .mandate_data .as_ref() .and_then(|inner| inner.update_mandate_id.clone()) { let mandate_details = MandateDetails { update_mandate_id: Some(update_id), }; Some(mandate_details) } else { None }; let payment_method_type = Option::<enums::PaymentMethodType>::foreign_from(( payment_method_type, additional_pm_data.as_ref(), payment_method, )); // TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed let payment_method_billing_address_id = match optional_payment_method_billing_address_id { None => payment_method_info .as_ref() .and_then(|pm_info| pm_info.payment_method_billing_address.as_ref()) .map(|address| { address.clone().deserialize_inner_value(|value| { value.parse_value::<api_models::payments::Address>("Address") }) }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .ok() .flatten() .async_map(|addr| async move { helpers::create_or_find_address_for_payment_by_request( state, Some(addr.get_inner()), None, merchant_id, payment_method_info .as_ref() .map(|pmd_info| pmd_info.customer_id.clone()) .as_ref(), key_store, payment_id, storage_scheme, ) .await }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)? .flatten() .map(|address| address.address_id), address_id => address_id, }; let is_stored_credential = helpers::is_stored_credential( &request.recurring_details, &request.payment_token, request.mandate_id.is_some(), request.is_stored_credential, ); Ok(( storage::PaymentAttemptNew { payment_id: payment_id.to_owned(), merchant_id: merchant_id.to_owned(), attempt_id, status, currency, payment_method, capture_method: request.capture_method, capture_on: request.capture_on, confirm: request.confirm.unwrap_or(false), created_at, modified_at, last_synced, authentication_type: request.authentication_type, browser_info, payment_experience: request.payment_experience, payment_method_type, payment_method_data: additional_pm_data_value, amount_to_capture: request.amount_to_capture, payment_token: request.payment_token.clone(), mandate_id: request.mandate_id.clone(), business_sub_label: request.business_sub_label.clone(), mandate_details: request .mandate_data .as_ref() .and_then(|inner| inner.mandate_type.clone().map(Into::into)), external_three_ds_authentication_attempted: None, mandate_data, payment_method_billing_address_id, net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request( request, MinorUnit::from(amount), ), save_to_locker: None, connector: None, error_message: None, offer_amount: None, payment_method_id: payment_method_info .as_ref() .map(|pm_info| pm_info.get_id().clone()), cancellation_reason: None, error_code: None, connector_metadata: None, straight_through_algorithm: None, preprocessing_step_id: None, error_reason: None, connector_response_reference_id: None, multiple_capture_count: None, amount_capturable: MinorUnit::new(i64::default()), updated_by: String::default(), authentication_data: None, encoded_data: None, merchant_connector_id: None, unified_code: None, unified_message: None, fingerprint_id: None, authentication_connector: None, authentication_id: None, client_source: None, client_version: None, customer_acceptance: customer_acceptance .clone() .map(|customer_acceptance| customer_acceptance.encode_to_value()) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize customer_acceptance")? .map(Secret::new), organization_id: organization_id.clone(), profile_id, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, processor_merchant_id: merchant_id.to_owned(), created_by: None, setup_future_usage_applied: request.setup_future_usage, routing_approach: Some(common_enums::RoutingApproach::default()), connector_request_reference_id: None, network_transaction_id:None, network_details:None, is_stored_credential, authorized_amount: None, }, additional_pm_data, )) } #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] async fn make_payment_intent( state: &SessionState, payment_id: &common_utils::id_type::PaymentId, merchant_context: &domain::MerchantContext, money: (api::Amount, enums::Currency), request: &api::PaymentsRequest, shipping_address_id: Option<String>, payment_link_data: Option<api_models::payments::PaymentLinkResponse>, billing_address_id: Option<String>, active_attempt_id: String, profile_id: common_utils::id_type::ProfileId, session_expiry: PrimitiveDateTime, business_profile: &domain::Profile, is_payment_id_from_merchant: bool, ) -> RouterResult<storage::PaymentIntent> { let created_at @ modified_at @ last_synced = common_utils::date_time::now(); let status = helpers::payment_intent_status_fsm( request .payment_method_data .as_ref() .and_then(|request_payment_method_data| { request_payment_method_data.payment_method_data.as_ref() }), request.confirm, ); let client_secret = payment_id.generate_client_secret(); let (amount, currency) = (money.0, Some(money.1)); let order_details = request .get_order_details_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert order details to value")?; let allowed_payment_method_types = request .get_allowed_payment_method_types_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting allowed_payment_types to Value")?; let connector_metadata = request .get_connector_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting connector_metadata to Value")?; let feature_metadata = request .get_feature_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting feature_metadata to Value")?; let payment_link_id = payment_link_data.map(|pl_data| pl_data.payment_link_id); let request_incremental_authorization = core_utils::get_request_incremental_authorization_value( request.request_incremental_authorization, request.capture_method, )?; let split_payments = request.split_payments.clone(); // Derivation of directly supplied Customer data in our Payment Create Request let raw_customer_details = if request.customer_id.is_none() && (request.name.is_some() || request.email.is_some() || request.phone.is_some() || request.phone_country_code.is_some()) { Some(CustomerData { name: request.name.clone(), phone: request.phone.clone(), email: request.email.clone(), phone_country_code: request.phone_country_code.clone(), tax_registration_id: None, }) } else { None }; let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then( |recurring_details| match recurring_details { RecurringDetails::ProcessorPaymentToken(_) => Some(true), _ => None, }, ); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let key_manager_state: KeyManagerState = state.into(); let shipping_details_encoded = request .shipping .clone() .map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode billing details to serde_json::Value")?; let billing_details_encoded = request .billing .clone() .map(|billing| Encode::encode_to_value(&billing).map(Secret::new)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode billing details to serde_json::Value")?; let customer_details_encoded = raw_customer_details .map(|customer| Encode::encode_to_value(&customer).map(Secret::new)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode shipping details to serde_json::Value")?; let encrypted_data = domain::types::crypto_operation( &key_manager_state, type_name!(storage::PaymentIntent), domain::types::CryptoOperation::BatchEncrypt( FromRequestEncryptablePaymentIntent::to_encryptable( FromRequestEncryptablePaymentIntent { shipping_details: shipping_details_encoded, billing_details: billing_details_encoded, customer_details: customer_details_encoded, }, ), ), identifier.clone(), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt data")?; let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt the payment intent data")?; let skip_external_tax_calculation = request.skip_external_tax_calculation; let tax_details = request .order_tax_amount .map(|tax_amount| diesel_models::TaxDetails { default: Some(diesel_models::DefaultTax { order_tax_amount: tax_amount, }), payment_method_type: None, }); let force_3ds_challenge_trigger = request .force_3ds_challenge .unwrap_or(business_profile.force_3ds_challenge); Ok(storage::PaymentIntent { payment_id: payment_id.to_owned(), merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), status, amount: MinorUnit::from(amount), currency, description: request.description.clone(), created_at, modified_at, last_synced: Some(last_synced), client_secret: Some(client_secret), setup_future_usage: request.setup_future_usage, off_session: request.off_session, return_url: request.return_url.as_ref().map(|a| a.to_string()), shipping_address_id, billing_address_id, statement_descriptor_name: request.statement_descriptor_name.clone(), statement_descriptor_suffix: request.statement_descriptor_suffix.clone(), metadata: request.metadata.clone(), business_country: request.business_country, business_label: request.business_label.clone(), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( active_attempt_id, ), order_details, amount_captured: None, customer_id: request.get_customer_id().cloned(), connector_id: None, allowed_payment_method_types, connector_metadata, feature_metadata, attempt_count: 1, profile_id: Some(profile_id), merchant_decision: None, payment_link_id, payment_confirm_source: None, surcharge_applicable: None, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), request_incremental_authorization, incremental_authorization_allowed: None, authorization_count: None, fingerprint_id: None, session_expiry: Some(session_expiry), request_external_three_ds_authentication: request .request_external_three_ds_authentication, split_payments, frm_metadata: request.frm_metadata.clone(), billing_details: encrypted_data.billing_details, customer_details: encrypted_data.customer_details, merchant_order_reference_id: request.merchant_order_reference_id.clone(), shipping_details: encrypted_data.shipping_details, is_payment_processor_token_flow, organization_id: merchant_context .get_merchant_account() .organization_id .clone(), shipping_cost: request.shipping_cost, tax_details, skip_external_tax_calculation, request_extended_authorization: request.request_extended_authorization, psd2_sca_exemption_type: request.psd2_sca_exemption_type, processor_merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), created_by: None, force_3ds_challenge: request.force_3ds_challenge, force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger), is_iframe_redirection_enabled: request .is_iframe_redirection_enabled .or(business_profile.is_iframe_redirection_enabled), is_payment_id_from_merchant: Some(is_payment_id_from_merchant), payment_channel: request.payment_channel.clone(), order_date: request.order_date, discount_amount: request.discount_amount, duty_amount: request.duty_amount, tax_status: request.tax_status, shipping_amount_tax: request.shipping_amount_tax, enable_partial_authorization: request.enable_partial_authorization, enable_overcapture: request.enable_overcapture, mit_category: request.mit_category, }) } #[instrument(skip_all)] pub async fn get_ephemeral_key( request: &api::PaymentsRequest, state: &SessionState, merchant_context: &domain::MerchantContext, ) -> Option<ephemeral_key::EphemeralKey> { match request.get_customer_id() { Some(customer_id) => helpers::make_ephemeral_key( state.clone(), customer_id.clone(), merchant_context .get_merchant_account() .get_id() .to_owned() .clone(), ) .await .ok() .and_then(|ek| { if let services::ApplicationResponse::Json(ek) = ek { Some(ek) } else { None } }), None => None, } } } #[instrument(skip_all)] pub fn payments_create_request_validation( req: &api::PaymentsRequest, ) -> RouterResult<(api::Amount, enums::Currency)> { let currency = req.currency.get_required_value("currency")?; let amount = req.amount.get_required_value("amount")?; Ok((amount, currency)) } #[allow(clippy::too_many_arguments)] async fn create_payment_link( request: &api::PaymentsRequest, payment_link_config: api_models::admin::PaymentLinkConfig, merchant_id: &common_utils::id_type::MerchantId, payment_id: common_utils::id_type::PaymentId, db: &dyn StorageInterface, amount: api::Amount, description: Option<String>, profile_id: common_utils::id_type::ProfileId, domain_name: String, session_expiry: PrimitiveDateTime, locale: Option<String>, ) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> { let created_at @ last_modified_at = Some(common_utils::date_time::now()); let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink"); let locale_str = locale.unwrap_or("en".to_owned()); let open_payment_link = format!( "{}/payment_link/{}/{}?locale={}", domain_name, merchant_id.get_string_repr(), payment_id.get_string_repr(), locale_str.clone(), ); let secure_link = payment_link_config.allowed_domains.as_ref().map(|_| { format!( "{}/payment_link/s/{}/{}?locale={}", domain_name, merchant_id.get_string_repr(), payment_id.get_string_repr(), locale_str, ) }); let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config", }, )?; let payment_link_req = storage::PaymentLinkNew { payment_link_id: payment_link_id.clone(), payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), link_to_pay: open_payment_link.clone(), amount: MinorUnit::from(amount), currency: request.currency, created_at, last_modified_at, fulfilment_time: Some(session_expiry), custom_merchant_name: Some(payment_link_config.seller_name), description, payment_link_config: Some(payment_link_config_encoded_value), profile_id: Some(profile_id), secure_link, }; let payment_link_db = db .insert_payment_link(payment_link_req) .await .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError { message: "payment link already exists!".to_string(), })?; Ok(Some(api_models::payments::PaymentLinkResponse { link: payment_link_db.link_to_pay.clone(), secure_link: payment_link_db.secure_link, payment_link_id: payment_link_db.payment_link_id, })) }
{ "crate": "router", "file": "crates/router/src/core/payments/operations/payment_create.rs", "file_size": 70419, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_6756942469511123447
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/unified_authentication_service.rs // File size: 69421 bytes pub mod types; use std::str::FromStr; pub mod utils; #[cfg(feature = "v1")] use api_models::authentication::{ AuthenticationEligibilityRequest, AuthenticationEligibilityResponse, AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse, }; use api_models::{ authentication::{ AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse, AuthenticationCreateRequest, AuthenticationResponse, }, payments, }; #[cfg(feature = "v1")] use common_utils::{ext_traits::ValueExt, types::keymanager::ToEncryptable}; use diesel_models::authentication::{Authentication, AuthenticationNew}; use error_stack::ResultExt; use hyperswitch_domain_models::{ errors::api_error_response::ApiErrorResponse, payment_method_data, router_request_types::{ authentication::{MessageCategory, PreAuthenticationData}, unified_authentication_service::{ AuthenticationInfo, PaymentDetails, ServiceSessionIds, ThreeDsMetaData, TransactionDetails, UasAuthenticationRequestData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, BrowserInformation, }, types::{ UasAuthenticationRouterData, UasPostAuthenticationRouterData, UasPreAuthenticationRouterData, }, }; use masking::{ExposeInterface, PeekInterface}; use super::{ errors::{RouterResponse, RouterResult}, payments::helpers::MerchantConnectorAccountType, }; use crate::{ consts, core::{ authentication::utils as auth_utils, errors::utils::StorageErrorExt, payments::helpers, unified_authentication_service::types::{ ClickToPay, ExternalAuthentication, UnifiedAuthenticationService, UNIFIED_AUTHENTICATION_SERVICE, }, utils as core_utils, }, db::domain, routes::SessionState, services::AuthFlow, types::{domain::types::AsyncLift, transformers::ForeignTryFrom}, }; #[cfg(feature = "v1")] #[async_trait::async_trait] impl UnifiedAuthenticationService for ClickToPay { fn get_pre_authentication_request_data( _payment_method_data: Option<&domain::PaymentMethodData>, service_details: Option<payments::CtpServiceDetails>, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, _payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<UasPreAuthenticationRequestData> { let domain_service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails { service_session_ids: Some(ServiceSessionIds { merchant_transaction_id: service_details .as_ref() .and_then(|details| details.merchant_transaction_id.clone()), correlation_id: service_details .as_ref() .and_then(|details| details.correlation_id.clone()), x_src_flow_id: service_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), }), payment_details: None, }; let transaction_details = TransactionDetails { amount: Some(amount), currency, device_channel: None, message_category: None, }; let authentication_info = Some(AuthenticationInfo { authentication_type: None, authentication_reasons: None, consent_received: false, // This is not relevant in this flow so keeping it as false is_authenticated: false, // This is not relevant in this flow so keeping it as false locale: None, supported_card_brands: None, encrypted_payload: service_details .as_ref() .and_then(|details| details.encrypted_payload.clone()), }); Ok(UasPreAuthenticationRequestData { service_details: Some(domain_service_details), transaction_details: Some(transaction_details), payment_details: None, authentication_info, merchant_details: merchant_details.cloned(), billing_address: billing_address.cloned(), acquirer_bin, acquirer_merchant_id, }) } async fn pre_authentication( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payment_id: Option<&common_utils::id_type::PaymentId>, payment_method_data: Option<&domain::PaymentMethodData>, payment_method_type: Option<common_enums::PaymentMethodType>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, service_details: Option<payments::CtpServiceDetails>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data( payment_method_data, service_details, amount, currency, merchant_details, billing_address, acquirer_bin, acquirer_merchant_id, payment_method_type, )?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, )) .await } async fn post_authentication( state: &SessionState, _business_profile: &domain::Profile, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, merchant_id: &common_utils::id_type::MerchantId, _authentication: Option<&Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let post_authentication_data = UasPostAuthenticationRequestData { threeds_server_transaction_id: None, }; let post_auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, post_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), post_auth_router_data, ) .await } async fn confirmation( state: &SessionState, authentication_id: Option<&common_utils::id_type::AuthenticationId>, currency: Option<common_enums::Currency>, status: common_enums::AttemptStatus, service_details: Option<payments::CtpServiceDetails>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_method: common_enums::PaymentMethod, net_amount: common_utils::types::MinorUnit, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<()> { let authentication_id = authentication_id .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Missing authentication id in tracker")?; let currency = currency.ok_or(ApiErrorResponse::MissingRequiredField { field_name: "currency", })?; let current_time = common_utils::date_time::date_as_yyyymmddthhmmssmmmz() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get current time")?; let payment_attempt_status = status; let (checkout_event_status, confirmation_reason) = utils::get_checkout_event_status_and_reason(payment_attempt_status); let click_to_pay_details = service_details.clone(); let authentication_confirmation_data = UasConfirmationRequestData { x_src_flow_id: click_to_pay_details .as_ref() .and_then(|details| details.x_src_flow_id.clone()), transaction_amount: net_amount, transaction_currency: currency, checkout_event_type: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented checkout_event_status: checkout_event_status.clone(), confirmation_status: checkout_event_status.clone(), confirmation_reason, confirmation_timestamp: Some(current_time), network_authorization_code: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented network_transaction_identifier: Some("mastercard".to_string()), // hardcoded to 'mastercard' since only mastercard has confirmation flow requirement correlation_id: click_to_pay_details .clone() .and_then(|details| details.correlation_id), merchant_transaction_id: click_to_pay_details .and_then(|details| details.merchant_transaction_id), }; let authentication_confirmation_router_data : hyperswitch_domain_models::types::UasAuthenticationConfirmationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, authentication_confirmation_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), authentication_confirmation_router_data, ) .await .ok(); // marking this as .ok() since this is not a required step at our end for completing the transaction Ok(()) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl UnifiedAuthenticationService for ExternalAuthentication { fn get_pre_authentication_request_data( payment_method_data: Option<&domain::PaymentMethodData>, _service_details: Option<payments::CtpServiceDetails>, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<UasPreAuthenticationRequestData> { let payment_method_data = payment_method_data .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("payment_method_data is missing")?; let payment_details = if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data { Some(PaymentDetails { pan: card.card_number.clone(), digital_card_id: None, payment_data_type: payment_method_type, encrypted_src_card_details: None, card_expiry_month: card.card_exp_month.clone(), card_expiry_year: card.card_exp_year.clone(), cardholder_name: card.card_holder_name.clone(), card_token_number: None, account_type: payment_method_type, card_cvc: Some(card.card_cvc.clone()), }) } else { None }; let transaction_details = TransactionDetails { amount: Some(amount), currency, device_channel: None, message_category: None, }; Ok(UasPreAuthenticationRequestData { service_details: None, transaction_details: Some(transaction_details), payment_details, authentication_info: None, merchant_details: merchant_details.cloned(), billing_address: billing_address.cloned(), acquirer_bin, acquirer_merchant_id, }) } #[allow(clippy::too_many_arguments)] async fn pre_authentication( state: &SessionState, merchant_id: &common_utils::id_type::MerchantId, payment_id: Option<&common_utils::id_type::PaymentId>, payment_method_data: Option<&domain::PaymentMethodData>, payment_method_type: Option<common_enums::PaymentMethodType>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, amount: common_utils::types::MinorUnit, currency: Option<common_enums::Currency>, service_details: Option<payments::CtpServiceDetails>, merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>, billing_address: Option<&hyperswitch_domain_models::address::Address>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, ) -> RouterResult<UasPreAuthenticationRouterData> { let pre_authentication_data = Self::get_pre_authentication_request_data( payment_method_data, service_details, amount, currency, merchant_details, billing_address, acquirer_bin, acquirer_merchant_id, payment_method_type, )?; let pre_auth_router_data: UasPreAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, merchant_id.clone(), None, pre_authentication_data, merchant_connector_account, Some(authentication_id.to_owned()), payment_id.cloned(), )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), pre_auth_router_data, )) .await } fn get_authentication_request_data( browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, ) -> RouterResult<UasAuthenticationRequestData> { Ok(UasAuthenticationRequestData { browser_details, transaction_details: TransactionDetails { amount, currency, device_channel: Some(device_channel), message_category: Some(message_category), }, pre_authentication_data: PreAuthenticationData { threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", }, )?, message_version: authentication.message_version.ok_or( ApiErrorResponse::MissingRequiredField { field_name: "authentication.message_version", }, )?, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, acquirer_country_code: authentication.acquirer_country_code, connector_metadata: authentication.connector_metadata, }, return_url, sdk_information, email, threeds_method_comp_ind, webhook_url, }) } #[allow(clippy::too_many_arguments)] async fn authentication( state: &SessionState, business_profile: &domain::Profile, payment_method: &common_enums::PaymentMethod, browser_details: Option<BrowserInformation>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, message_category: MessageCategory, device_channel: payments::DeviceChannel, authentication: Authentication, return_url: Option<String>, sdk_information: Option<payments::SdkInformation>, threeds_method_comp_ind: payments::ThreeDsCompletionIndicator, email: Option<common_utils::pii::Email>, webhook_url: String, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, payment_id: Option<common_utils::id_type::PaymentId>, ) -> RouterResult<UasAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_authentication_request_data( browser_details, amount, currency, message_category, device_channel, authentication.clone(), return_url, sdk_information, threeds_method_comp_ind, email, webhook_url, )?; let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method.to_owned(), business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication.authentication_id.to_owned()), payment_id, )?; Box::pin(utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, )) .await } fn get_post_authentication_request_data( authentication: Option<Authentication>, ) -> RouterResult<UasPostAuthenticationRequestData> { Ok(UasPostAuthenticationRequestData { // authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication threeds_server_transaction_id: Some( authentication .and_then(|auth| auth.threeds_server_transaction_id) .ok_or(ApiErrorResponse::MissingRequiredField { field_name: "authentication.threeds_server_transaction_id", })?, ), }) } async fn post_authentication( state: &SessionState, business_profile: &domain::Profile, payment_id: Option<&common_utils::id_type::PaymentId>, merchant_connector_account: &MerchantConnectorAccountType, connector_name: &str, authentication_id: &common_utils::id_type::AuthenticationId, payment_method: common_enums::PaymentMethod, _merchant_id: &common_utils::id_type::MerchantId, authentication: Option<&Authentication>, ) -> RouterResult<UasPostAuthenticationRouterData> { let authentication_data = <Self as UnifiedAuthenticationService>::get_post_authentication_request_data( authentication.cloned(), )?; let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data( state, connector_name.to_string(), payment_method, business_profile.merchant_id.clone(), None, authentication_data, merchant_connector_account, Some(authentication_id.clone()), payment_id.cloned(), )?; utils::do_auth_connector_call( state, UNIFIED_AUTHENTICATION_SERVICE.to_string(), auth_router_data, ) .await } } #[allow(clippy::too_many_arguments)] pub async fn create_new_authentication( state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: Option<String>, profile_id: common_utils::id_type::ProfileId, payment_id: Option<common_utils::id_type::PaymentId>, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, authentication_id: &common_utils::id_type::AuthenticationId, service_details: Option<payments::CtpServiceDetails>, authentication_status: common_enums::AuthenticationStatus, network_token: Option<payment_method_data::NetworkTokenData>, organization_id: common_utils::id_type::OrganizationId, force_3ds_challenge: Option<bool>, psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, acquirer_bin: Option<String>, acquirer_merchant_id: Option<String>, acquirer_country_code: Option<String>, amount: Option<common_utils::types::MinorUnit>, currency: Option<common_enums::Currency>, return_url: Option<String>, profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>, ) -> RouterResult<Authentication> { let service_details_value = service_details .map(serde_json::to_value) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable( "unable to parse service details into json value while inserting to DB", )?; let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!( "{}_secret", authentication_id.get_string_repr() ))); let new_authorization = AuthenticationNew { authentication_id: authentication_id.to_owned(), merchant_id, authentication_connector, connector_authentication_id: None, payment_method_id: "".to_string(), authentication_type: None, authentication_status, authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused, error_message: None, error_code: None, connector_metadata: None, maximum_supported_version: None, threeds_server_transaction_id: None, cavv: None, authentication_flow_type: None, message_version: None, eci: network_token.and_then(|data| data.eci), trans_status: None, acquirer_bin, acquirer_merchant_id, three_ds_method_data: None, three_ds_method_url: None, acs_url: None, challenge_request: None, challenge_request_key: None, acs_reference_number: None, acs_trans_id: None, acs_signed_content: None, profile_id, payment_id, merchant_connector_id, ds_trans_id: None, directory_server_id: None, acquirer_country_code, service_details: service_details_value, organization_id, authentication_client_secret, force_3ds_challenge, psd2_sca_exemption_type, return_url, amount, currency, billing_address: None, shipping_address: None, browser_info: None, email: None, profile_acquirer_id, challenge_code: None, challenge_cancel: None, challenge_code_reason: None, message_extension: None, }; state .store .insert_authentication(new_authorization) .await .to_duplicate_response(ApiErrorResponse::GenericDuplicateError { message: format!( "Authentication with authentication_id {} already exists", authentication_id.get_string_repr() ), }) } // Modular authentication #[cfg(feature = "v1")] pub async fn authentication_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationCreateRequest, ) -> RouterResponse<AuthenticationResponse> { let db = &*state.store; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let organization_id = merchant_account.organization_id.clone(); let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id( consts::AUTHENTICATION_ID_PREFIX, ); let force_3ds_challenge = Some( req.force_3ds_challenge .unwrap_or(business_profile.force_3ds_challenge), ); // Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(acquirer_details) = &req.acquirer_details { // Priority 1: Use acquirer_details from request if present ( acquirer_details.acquirer_bin.clone(), acquirer_details.acquirer_merchant_id.clone(), acquirer_details.merchant_country_code.clone(), ) } else { // Priority 2: Fallback to profile_acquirer_id lookup let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| { acquirer_config_map.0.get(&acquirer_id).cloned() }) }); acquirer_details .as_ref() .map(|details| { ( Some(details.acquirer_bin.clone()), Some(details.acquirer_assigned_merchant_id.clone()), business_profile .merchant_country_code .map(|code| code.get_country_code().to_owned()), ) }) .unwrap_or((None, None, None)) }; let new_authentication = create_new_authentication( &state, merchant_id.clone(), req.authentication_connector .map(|connector| connector.to_string()), profile_id.clone(), None, None, &authentication_id, None, common_enums::AuthenticationStatus::Started, None, organization_id, force_3ds_challenge, req.psd2_sca_exemption_type, acquirer_bin, acquirer_merchant_id, acquirer_country_code, Some(req.amount), Some(req.currency), req.return_url, req.profile_acquirer_id.clone(), ) .await?; let acquirer_details = Some(AcquirerDetails { acquirer_bin: new_authentication.acquirer_bin.clone(), acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(), merchant_country_code: new_authentication.acquirer_country_code.clone(), }); let amount = new_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = new_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let response = AuthenticationResponse::foreign_try_from(( new_authentication.clone(), amount, currency, profile_id, acquirer_details, new_authentication.profile_acquirer_id, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } impl ForeignTryFrom<( Authentication, common_utils::types::MinorUnit, common_enums::Currency, common_utils::id_type::ProfileId, Option<AcquirerDetails>, Option<common_utils::id_type::ProfileAcquirerId>, )> for AuthenticationResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, amount, currency, profile_id, acquirer_details, profile_acquirer_id): ( Authentication, common_utils::types::MinorUnit, common_enums::Currency, common_utils::id_type::ProfileId, Option<AcquirerDetails>, Option<common_utils::id_type::ProfileAcquirerId>, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; Ok(Self { authentication_id: authentication.authentication_id, client_secret: authentication .authentication_client_secret .map(masking::Secret::new), amount, currency, force_3ds_challenge: authentication.force_3ds_challenge, merchant_id: authentication.merchant_id, status: authentication.authentication_status, authentication_connector, return_url: authentication.return_url, created_at: Some(authentication.created_at), error_code: authentication.error_code, error_message: authentication.error_message, profile_id: Some(profile_id), psd2_sca_exemption_type: authentication.psd2_sca_exemption_type, acquirer_details, profile_acquirer_id, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<( Authentication, api_models::authentication::NextAction, common_utils::id_type::ProfileId, Option<payments::Address>, Option<payments::Address>, Option<payments::BrowserInformation>, common_utils::crypto::OptionalEncryptableEmail, )> for AuthenticationEligibilityResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, next_action, profile_id, billing, shipping, browser_information, email): ( Authentication, api_models::authentication::NextAction, common_utils::id_type::ProfileId, Option<payments::Address>, Option<payments::Address>, Option<payments::BrowserInformation>, common_utils::crypto::OptionalEncryptableEmail, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let three_ds_method_url = authentication .three_ds_method_url .map(|url| url::Url::parse(&url)) .transpose() .map_err(error_stack::Report::from) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse three_ds_method_url")?; let three_ds_data = Some(api_models::authentication::ThreeDsData { three_ds_server_transaction_id: authentication.threeds_server_transaction_id, maximum_supported_3ds_version: authentication.maximum_supported_version, connector_authentication_id: authentication.connector_authentication_id, three_ds_method_data: authentication.three_ds_method_data, three_ds_method_url, message_version: authentication.message_version, directory_server_id: authentication.directory_server_id, }); let acquirer_details = AcquirerDetails { acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, merchant_country_code: authentication.acquirer_country_code, }; Ok(Self { authentication_id: authentication.authentication_id, next_action, status: authentication.authentication_status, eligibility_response_params: three_ds_data .map(api_models::authentication::EligibilityResponseParams::ThreeDsData), connector_metadata: authentication.connector_metadata, profile_id, error_message: authentication.error_message, error_code: authentication.error_code, billing, shipping, authentication_connector, browser_information, email, acquirer_details: Some(acquirer_details), }) } } #[cfg(feature = "v1")] pub async fn authentication_eligibility_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationEligibilityRequest, authentication_id: common_utils::id_type::AuthenticationId, ) -> RouterResponse<AuthenticationEligibilityResponse> { let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .clone() .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = core_utils::get_profile_id_from_business_details( &key_manager_state, None, None, &merchant_context, req.profile_id.as_ref(), db, true, ) .await?; let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let notification_url = match authentication_connector { common_enums::AuthenticationConnectors::Juspaythreedsserver => { Some(url::Url::parse(&format!( "{base_url}/authentication/{merchant_id}/{authentication_id}/redirect", base_url = state.base_url, merchant_id = merchant_id.get_string_repr(), authentication_id = authentication_id.get_string_repr() ))) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse notification url")? } _ => authentication .return_url .as_ref() .map(|url| url::Url::parse(url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse return url")?, }; let authentication_connector_name = authentication_connector.to_string(); let payment_method_data = domain::PaymentMethodData::from(req.payment_method_data.clone()); let amount = authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("no amount found in authentication table")?; let acquirer_details = authentication .profile_acquirer_id .clone() .and_then(|acquirer_id| { business_profile .acquirer_config_map .and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned()) }); let metadata: Option<ThreeDsMetaData> = three_ds_connector_account .get_metadata() .map(|metadata| { metadata.expose().parse_value("ThreeDsMetaData").inspect_err(|err| { router_env::logger::warn!(parsing_error=?err,"Error while parsing ThreeDsMetaData"); }) }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let merchant_country_code = authentication.acquirer_country_code.clone(); let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails { merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()), merchant_name: acquirer_details.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)), merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)), endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix), three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url), three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id), three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name), merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new), notification_url, }); let domain_address = req .billing .clone() .map(hyperswitch_domain_models::address::Address::from); let pre_auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::pre_authentication( &state, merchant_id, None, Some(&payment_method_data), req.payment_method_type, &three_ds_connector_account, &authentication_connector_name, &authentication_id, req.payment_method, amount, authentication.currency, None, merchant_details.as_ref(), domain_address.as_ref(), authentication.acquirer_bin.clone(), authentication.acquirer_merchant_id.clone(), ) .await?; let billing_details_encoded = req .billing .clone() .map(|billing| { common_utils::ext_traits::Encode::encode_to_value(&billing) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode billing details to serde_json::Value")?; let shipping_details_encoded = req .shipping .clone() .map(|shipping| { common_utils::ext_traits::Encode::encode_to_value(&shipping) .map(masking::Secret::<serde_json::Value>::new) }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode shipping details to serde_json::Value")?; let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchEncrypt( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable( hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication { billing_address: billing_details_encoded, shipping_address: shipping_details_encoded, }, ), ), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_encrypted = req .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = req .browser_information .as_ref() .map(common_utils::ext_traits::Encode::encode_to_value) .transpose() .change_context(ApiErrorResponse::InvalidDataValue { field_name: "browser_information", })?; let updated_authentication = utils::external_authentication_update_trackers( &state, pre_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), encrypted_data .billing_address .map(common_utils::encryption::Encryption::from), encrypted_data .shipping_address .map(common_utils::encryption::Encryption::from), email_encrypted .clone() .map(common_utils::encryption::Encryption::from), browser_info, ) .await?; let response = AuthenticationEligibilityResponse::foreign_try_from(( updated_authentication, req.get_next_action_api( state.base_url, authentication_id.get_string_repr().to_string(), ) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get next action api")?, profile_id, req.get_billing_address(), req.get_shipping_address(), req.get_browser_information(), email_encrypted, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(feature = "v1")] pub async fn authentication_authenticate_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationAuthenticateRequest, auth_flow: AuthFlow, ) -> RouterResponse<AuthenticationAuthenticateResponse> { let authentication_id = req.authentication_id.clone(); let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let email_encrypted = authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to decrypt email from authentication table")?; let browser_info = authentication .browser_info .clone() .map(|browser_info| browser_info.parse_value::<BrowserInformation>("BrowserInformation")) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse browser information from authentication table")?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let authentication_details = business_profile .authentication_connector_details .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector_details not configured by the merchant")?; let connector_name_string = authentication_connector.to_string(); let mca_id_option = three_ds_connector_account.get_mca_id(); let merchant_connector_account_id_or_connector_name = mca_id_option .as_ref() .map(|mca_id| mca_id.get_string_repr()) .unwrap_or(&connector_name_string); let webhook_url = helpers::create_webhook_url( &state.base_url, merchant_id, merchant_connector_account_id_or_connector_name, ); let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication( &state, &business_profile, &common_enums::PaymentMethod::Card, browser_info, authentication.amount, authentication.currency, MessageCategory::Payment, req.device_channel, authentication.clone(), None, req.sdk_information, req.threeds_method_comp_ind, email_encrypted.map(common_utils::pii::Email::from), webhook_url, &three_ds_connector_account, &authentication_connector.to_string(), None, ) .await?; let authentication = utils::external_authentication_update_trackers( &state, auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), authentication.eci.clone(), ) } else { (None, None) } } }; let response = AuthenticationAuthenticateResponse::foreign_try_from(( &authentication, authentication_value, eci, authentication_details, ))?; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } impl ForeignTryFrom<( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, )> for AuthenticationAuthenticateResponse { type Error = error_stack::Report<ApiErrorResponse>; fn foreign_try_from( (authentication, authentication_value, eci, authentication_details): ( &Authentication, Option<masking::Secret<String>>, Option<String>, diesel_models::business_profile::AuthenticationConnectorDetails, ), ) -> Result<Self, Self::Error> { let authentication_connector = authentication .authentication_connector .as_ref() .map(|connector| common_enums::AuthenticationConnectors::from_str(connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let acs_url = authentication .acs_url .clone() .map(|acs_url| url::Url::parse(&acs_url)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to parse the url with param")?; let acquirer_details = AcquirerDetails { acquirer_bin: authentication.acquirer_bin.clone(), acquirer_merchant_id: authentication.acquirer_merchant_id.clone(), merchant_country_code: authentication.acquirer_country_code.clone(), }; Ok(Self { transaction_status: authentication.trans_status.clone(), acs_url, challenge_request: authentication.challenge_request.clone(), acs_reference_number: authentication.acs_reference_number.clone(), acs_trans_id: authentication.acs_trans_id.clone(), three_ds_server_transaction_id: authentication.threeds_server_transaction_id.clone(), acs_signed_content: authentication.acs_signed_content.clone(), three_ds_requestor_url: authentication_details.three_ds_requestor_url.clone(), three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url.clone(), error_code: None, error_message: authentication.error_message.clone(), authentication_value, status: authentication.authentication_status, authentication_connector, eci, authentication_id: authentication.authentication_id.clone(), acquirer_details: Some(acquirer_details), }) } } #[cfg(feature = "v1")] pub async fn authentication_sync_core( state: SessionState, merchant_context: domain::MerchantContext, auth_flow: AuthFlow, req: AuthenticationSyncRequest, ) -> RouterResponse<AuthenticationSyncResponse> { let authentication_id = req.authentication_id; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; req.client_secret .map(|client_secret| { utils::authenticate_authentication_client_secret_and_check_expiry( client_secret.peek(), &authentication, ) }) .transpose()?; let key_manager_state = (&state).into(); let profile_id = authentication.profile_id.clone(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let updated_authentication = match authentication.trans_status.clone() { Some(trans_status) if trans_status.clone().is_pending() => { let post_auth_response = ExternalAuthentication::post_authentication( &state, &business_profile, None, &three_ds_connector_account, &authentication_connector.to_string(), &authentication_id, common_enums::PaymentMethod::Card, merchant_id, Some(&authentication), ) .await?; utils::external_authentication_update_trackers( &state, post_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await? } _ => authentication, }; let (authentication_value, eci) = match auth_flow { AuthFlow::Client => (None, None), AuthFlow::Merchant => { if let Some(common_enums::TransactionStatus::Success) = updated_authentication.trans_status { let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data( &state, authentication_id.get_string_repr(), false, merchant_context.get_merchant_key_store().key.get_inner(), ) .await .inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err)) .attach_printable("cavv not present after authentication status is success")?; ( Some(masking::Secret::new(tokenised_data.value1)), updated_authentication.eci.clone(), ) } else { (None, None) } } }; let acquirer_details = Some(AcquirerDetails { acquirer_bin: updated_authentication.acquirer_bin.clone(), acquirer_merchant_id: updated_authentication.acquirer_merchant_id.clone(), merchant_country_code: updated_authentication.acquirer_country_code.clone(), }); let encrypted_data = domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication), domain::types::CryptoOperation::BatchDecrypt( hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable( hyperswitch_domain_models::authentication::EncryptedAuthentication { billing_address: updated_authentication.billing_address, shipping_address: updated_authentication.shipping_address, }, ), ), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt authentication data".to_string())?; let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data) .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to get encrypted data for authentication after encryption")?; let email_decrypted = updated_authentication .email .clone() .async_lift(|inner| async { domain::types::crypto_operation( &key_manager_state, common_utils::type_name!(Authentication), domain::types::CryptoOperation::DecryptOptional(inner), common_utils::types::keymanager::Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), merchant_context.get_merchant_key_store().key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt email")?; let browser_info = updated_authentication .browser_info .clone() .map(|browser_info| { browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation") }) .transpose() .change_context(ApiErrorResponse::InternalServerError)?; let amount = updated_authentication .amount .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("amount failed to get amount from authentication table")?; let currency = updated_authentication .currency .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("currency failed to get currency from authentication table")?; let authentication_connector = updated_authentication .authentication_connector .map(|connector| common_enums::AuthenticationConnectors::from_str(&connector)) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Incorrect authentication connector stored in table")?; let billing = encrypted_data .billing_address .map(|billing| { billing .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse billing address")?; let shipping = encrypted_data .shipping_address .map(|shipping| { shipping .into_inner() .expose() .parse_value::<payments::Address>("Address") }) .transpose() .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse shipping address")?; let response = AuthenticationSyncResponse { authentication_id: authentication_id.clone(), merchant_id: merchant_id.clone(), status: updated_authentication.authentication_status, client_secret: updated_authentication .authentication_client_secret .map(masking::Secret::new), amount, currency, authentication_connector, force_3ds_challenge: updated_authentication.force_3ds_challenge, return_url: updated_authentication.return_url.clone(), created_at: updated_authentication.created_at, profile_id: updated_authentication.profile_id.clone(), psd2_sca_exemption_type: updated_authentication.psd2_sca_exemption_type, acquirer_details, error_message: updated_authentication.error_message.clone(), error_code: updated_authentication.error_code.clone(), authentication_value, threeds_server_transaction_id: updated_authentication.threeds_server_transaction_id.clone(), maximum_supported_3ds_version: updated_authentication.maximum_supported_version.clone(), connector_authentication_id: updated_authentication.connector_authentication_id.clone(), three_ds_method_data: updated_authentication.three_ds_method_data.clone(), three_ds_method_url: updated_authentication.three_ds_method_url.clone(), message_version: updated_authentication.message_version.clone(), connector_metadata: updated_authentication.connector_metadata.clone(), directory_server_id: updated_authentication.directory_server_id.clone(), billing, shipping, browser_information: browser_info, email: email_decrypted, transaction_status: updated_authentication.trans_status.clone(), acs_url: updated_authentication.acs_url.clone(), challenge_request: updated_authentication.challenge_request.clone(), acs_reference_number: updated_authentication.acs_reference_number.clone(), acs_trans_id: updated_authentication.acs_trans_id.clone(), acs_signed_content: updated_authentication.acs_signed_content, three_ds_requestor_url: business_profile .authentication_connector_details .clone() .map(|details| details.three_ds_requestor_url), three_ds_requestor_app_url: business_profile .authentication_connector_details .and_then(|details| details.three_ds_requestor_app_url), profile_acquirer_id: updated_authentication.profile_acquirer_id.clone(), eci, }; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) } #[cfg(feature = "v1")] pub async fn authentication_post_sync_core( state: SessionState, merchant_context: domain::MerchantContext, req: AuthenticationSyncPostUpdateRequest, ) -> RouterResponse<()> { let authentication_id = req.authentication_id; let merchant_account = merchant_context.get_merchant_account(); let merchant_id = merchant_account.get_id(); let db = &*state.store; let authentication = db .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id) .await .to_not_found_response(ApiErrorResponse::AuthenticationNotFound { id: authentication_id.get_string_repr().to_owned(), })?; ensure_not_terminal_status(authentication.trans_status.clone())?; let key_manager_state = (&state).into(); let business_profile = db .find_business_profile_by_profile_id( &key_manager_state, merchant_context.get_merchant_key_store(), &authentication.profile_id, ) .await .to_not_found_response(ApiErrorResponse::ProfileNotFound { id: authentication.profile_id.get_string_repr().to_owned(), })?; let (authentication_connector, three_ds_connector_account) = auth_utils::get_authentication_connector_data( &state, merchant_context.get_merchant_key_store(), &business_profile, authentication.authentication_connector.clone(), ) .await?; let post_auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::post_authentication( &state, &business_profile, None, &three_ds_connector_account, &authentication_connector.to_string(), &authentication_id, common_enums::PaymentMethod::Card, merchant_id, Some(&authentication), ) .await?; let updated_authentication = utils::external_authentication_update_trackers( &state, post_auth_response, authentication.clone(), None, merchant_context.get_merchant_key_store(), None, None, None, None, ) .await?; let authentication_details = business_profile .authentication_connector_details .clone() .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("authentication_connector_details not configured by the merchant")?; let authentication_response = AuthenticationAuthenticateResponse::foreign_try_from(( &updated_authentication, None, None, authentication_details, ))?; let redirect_response = helpers::get_handle_response_url_for_modular_authentication( authentication_id, &business_profile, &authentication_response, authentication_connector.to_string(), authentication.return_url, updated_authentication .authentication_client_secret .clone() .map(masking::Secret::new) .as_ref(), updated_authentication.amount, )?; Ok(hyperswitch_domain_models::api::ApplicationResponse::JsonForRedirection(redirect_response)) } fn ensure_not_terminal_status( status: Option<common_enums::TransactionStatus>, ) -> Result<(), error_stack::Report<ApiErrorResponse>> { status .filter(|s| s.clone().is_terminal_state()) .map(|s| { Err(error_stack::Report::new( ApiErrorResponse::UnprocessableEntity { message: format!( "authentication status for the given authentication_id is already in {s}" ), }, )) }) .unwrap_or(Ok(())) }
{ "crate": "router", "file": "crates/router/src/core/unified_authentication_service.rs", "file_size": 69421, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-8913315627087513085
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/webhooks/recovery_incoming.rs // File size: 68371 bytes use std::{collections::HashMap, marker::PhantomData, str::FromStr}; use api_models::{enums as api_enums, payments as api_payments, webhooks}; use common_utils::{ ext_traits::{AsyncExt, ValueExt}, id_type, }; use diesel_models::process_tracker as storage; use error_stack::{report, ResultExt}; use futures::stream::SelectNextSome; use hyperswitch_domain_models::{ payments as domain_payments, revenue_recovery::{self, RecoveryPaymentIntent}, router_data_v2::flow_common_types, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, types as router_types, }; use hyperswitch_interfaces::webhooks as interface_webhooks; use masking::{PeekInterface, Secret}; use router_env::{instrument, logger, tracing}; use services::kafka; use storage::business_status; use crate::{ core::{ self, admin, errors::{self, CustomResult}, payments::{self, helpers}, }, db::{errors::RevenueRecoveryError, StorageInterface}, routes::{app::ReqState, metrics, SessionState}, services::{ self, connector_integration_interface::{self, RouterDataConversion}, }, types::{ self, api, domain, storage::{ revenue_recovery as storage_revenue_recovery, revenue_recovery_redis_operation::{ PaymentProcessorTokenDetails, PaymentProcessorTokenStatus, RedisTokenManager, }, }, transformers::ForeignFrom, }, workflows::revenue_recovery as revenue_recovery_flow, }; #[cfg(feature = "v2")] pub const REVENUE_RECOVERY: &str = "revenue_recovery"; #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] #[cfg(feature = "revenue_recovery")] pub async fn recovery_incoming_webhook_flow( state: SessionState, merchant_context: domain::MerchantContext, business_profile: domain::Profile, source_verified: bool, connector_enum: &connector_integration_interface::ConnectorEnum, billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, event_type: webhooks::IncomingWebhookEvent, req_state: ReqState, object_ref_id: &webhooks::ObjectReferenceId, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { // Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system. common_utils::fp_utils::when(!source_verified, || { Err(report!( errors::RevenueRecoveryError::WebhookAuthenticationFailed )) })?; let connector = api_enums::Connector::from_str(connector_name) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; let billing_connectors_with_invoice_sync_call = &state.conf.billing_connectors_invoice_sync; let should_billing_connector_invoice_api_called = billing_connectors_with_invoice_sync_call .billing_connectors_which_requires_invoice_sync_call .contains(&connector); let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync; let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call .billing_connectors_which_require_payment_sync .contains(&connector); let billing_connector_payment_details = BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details( should_billing_connector_payment_api_called, &state, &merchant_context, &billing_connector_account, connector_name, object_ref_id, ) .await?; let invoice_id = billing_connector_payment_details .clone() .map(|data| data.merchant_reference_id); let billing_connector_invoice_details = BillingConnectorInvoiceSyncResponseData::get_billing_connector_invoice_details( should_billing_connector_invoice_api_called, &state, &merchant_context, &billing_connector_account, connector_name, invoice_id, ) .await?; // Checks whether we have data in billing_connector_invoice_details , if it is there then we construct revenue recovery invoice from it else it takes from webhook let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details( connector_enum, request_details, billing_connector_invoice_details.as_ref(), )?; // Fetch the intent using merchant reference id, if not found create new intent. let payment_intent = invoice_details .get_payment_intent(&state, &req_state, &merchant_context, &business_profile) .await .transpose() .async_unwrap_or_else(|| async { invoice_details .create_payment_intent(&state, &req_state, &merchant_context, &business_profile) .await }) .await?; let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event(); let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) = RevenueRecoveryAttempt::get_recovery_payment_attempt( is_event_recovery_transaction_event, &billing_connector_account, &state, connector_enum, &req_state, billing_connector_payment_details.as_ref(), request_details, &merchant_context, &business_profile, &payment_intent, &invoice_details.0, ) .await?; // Publish event to Kafka if let Some(ref attempt) = recovery_attempt_from_payment_attempt { // Passing `merchant_context` here let recovery_payment_tuple = &RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt); if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( &state, recovery_payment_tuple, None, ) .await { logger::error!( "Failed to publish revenue recovery event to kafka : {:?}", e ); }; } let attempt_triggered_by = recovery_attempt_from_payment_attempt .as_ref() .and_then(|attempt| attempt.get_attempt_triggered_by()); let recovery_action = RecoveryAction { action: RecoveryAction::get_action(event_type, attempt_triggered_by), }; let mca_retry_threshold = billing_connector_account .get_retry_threshold() .ok_or(report!( errors::RevenueRecoveryError::BillingThresholdRetryCountFetchFailed ))?; let intent_retry_count = recovery_intent_from_payment_attempt .feature_metadata .as_ref() .and_then(|metadata| metadata.get_retry_count()) .ok_or(report!(errors::RevenueRecoveryError::RetryCountFetchFailed))?; logger::info!("Intent retry count: {:?}", intent_retry_count); recovery_action .handle_action( &state, &business_profile, &merchant_context, &billing_connector_account, mca_retry_threshold, intent_retry_count, &( recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt, ), ) .await } async fn handle_monitoring_threshold( state: &SessionState, business_profile: &domain::Profile, key_store: &domain::MerchantKeyStore, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let db = &*state.store; let key_manager_state = &(state).into(); let monitoring_threshold_config = state.conf.revenue_recovery.monitoring_threshold_in_seconds; let retry_algorithm_type = state.conf.revenue_recovery.retry_algorithm_type; let revenue_recovery_retry_algorithm = business_profile .revenue_recovery_retry_algorithm_data .clone() .ok_or(report!( errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound ))?; if revenue_recovery_retry_algorithm .has_exceeded_monitoring_threshold(monitoring_threshold_config) { let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone()); profile_wrapper .update_revenue_recovery_algorithm_under_profile( db, key_manager_state, key_store, retry_algorithm_type, ) .await .change_context(errors::RevenueRecoveryError::RetryAlgorithmUpdationFailed)?; } Ok(webhooks::WebhookResponseTracker::NoEffect) } #[allow(clippy::too_many_arguments)] async fn handle_schedule_failed_payment( billing_connector_account: &domain::MerchantConnectorAccount, intent_retry_count: u16, mca_retry_threshold: u16, state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt_with_recovery_intent: &( Option<revenue_recovery::RecoveryPaymentAttempt>, revenue_recovery::RecoveryPaymentIntent, ), business_profile: &domain::Profile, revenue_recovery_retry: api_enums::RevenueRecoveryAlgorithmType, ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) = payment_attempt_with_recovery_intent; // When intent_retry_count is less than or equal to threshold (intent_retry_count <= mca_retry_threshold) .then(|| { logger::error!( "Payment retry count {} is less than threshold {}", intent_retry_count, mca_retry_threshold ); Ok(webhooks::WebhookResponseTracker::NoEffect) }) .async_unwrap_or_else(|| async { // Call calculate_job core::revenue_recovery::upsert_calculate_pcr_task( billing_connector_account, state, merchant_context, recovery_intent_from_payment_attempt, business_profile, intent_retry_count, recovery_attempt_from_payment_attempt .as_ref() .map(|attempt| attempt.attempt_id.clone()), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, revenue_recovery_retry, ) .await }) .await } #[derive(Debug)] pub struct RevenueRecoveryInvoice(revenue_recovery::RevenueRecoveryInvoiceData); #[derive(Debug)] pub struct RevenueRecoveryAttempt(revenue_recovery::RevenueRecoveryAttemptData); impl RevenueRecoveryInvoice { pub async fn get_or_create_custom_recovery_intent( data: api_models::payments::RecoveryPaymentsCreate, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { let recovery_intent = Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from( data, )); recovery_intent .get_payment_intent(state, req_state, merchant_context, profile) .await .transpose() .async_unwrap_or_else(|| async { recovery_intent .create_payment_intent(state, req_state, merchant_context, profile) .await }) .await } fn get_recovery_invoice_details( connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, billing_connector_invoice_details: Option< &revenue_recovery_response::BillingConnectorInvoiceSyncResponse, >, ) -> CustomResult<Self, errors::RevenueRecoveryError> { billing_connector_invoice_details.map_or_else( || { interface_webhooks::IncomingWebhook::get_revenue_recovery_invoice_details( connector_enum, request_details, ) .change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed) .attach_printable("Failed while getting revenue recovery invoice details") .map(RevenueRecoveryInvoice) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryInvoiceData::from( data, ))) }, ) } async fn get_payment_intent( &self, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError> { let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference( state.clone(), merchant_context.clone(), profile.clone(), req_state.clone(), &self.0.merchant_reference_id, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await; let response = match payment_response { Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { let payment_id = payments_response.id.clone(); let status = payments_response.status; let feature_metadata = payments_response.feature_metadata; let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let revenue_recovery_invoice_data = &self.0; Ok(Some(revenue_recovery::RecoveryPaymentIntent { payment_id, status, feature_metadata, merchant_id, merchant_reference_id: Some( revenue_recovery_invoice_data.merchant_reference_id.clone(), ), invoice_amount: revenue_recovery_invoice_data.amount, invoice_currency: revenue_recovery_invoice_data.currency, created_at: revenue_recovery_invoice_data.billing_started_at, billing_address: revenue_recovery_invoice_data.billing_address.clone(), })) } Err(err) if matches!( err.current_context(), &errors::ApiErrorResponse::PaymentNotFound ) => { Ok(None) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) .attach_printable("Unexpected response from payment intent core"), error @ Err(_) => { logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed) .attach_printable("failed to fetch payment intent recovery webhook flow") } }?; Ok(response) } async fn create_payment_intent( &self, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, ) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> { let payload = api_payments::PaymentsCreateIntentRequest::from(&self.0); let global_payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id); let create_intent_response = Box::pin(payments::payments_intent_core::< router_flow_types::payments::PaymentCreateIntent, api_payments::PaymentsIntentResponse, _, _, hyperswitch_domain_models::payments::PaymentIntentData< router_flow_types::payments::PaymentCreateIntent, >, >( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), payments::operations::PaymentIntentCreate, payload, global_payment_id, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed)?; let response = create_intent_response .get_json_body() .change_context(errors::RevenueRecoveryError::PaymentIntentCreateFailed) .attach_printable("expected json response")?; let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let revenue_recovery_invoice_data = &self.0; Ok(revenue_recovery::RecoveryPaymentIntent { payment_id: response.id, status: response.status, feature_metadata: response.feature_metadata, merchant_id, merchant_reference_id: Some( revenue_recovery_invoice_data.merchant_reference_id.clone(), ), invoice_amount: revenue_recovery_invoice_data.amount, invoice_currency: revenue_recovery_invoice_data.currency, created_at: revenue_recovery_invoice_data.billing_started_at, billing_address: revenue_recovery_invoice_data.billing_address.clone(), }) } } impl RevenueRecoveryAttempt { pub async fn load_recovery_attempt_from_api( data: api_models::payments::RecoveryPaymentsCreate, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_intent: revenue_recovery::RecoveryPaymentIntent, payment_merchant_connector_account: domain::MerchantConnectorAccount, ) -> CustomResult< ( revenue_recovery::RecoveryPaymentAttempt, revenue_recovery::RecoveryPaymentIntent, ), errors::RevenueRecoveryError, > { let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from( &data, )); recovery_attempt .get_payment_attempt(state, req_state, merchant_context, profile, &payment_intent) .await .transpose() .async_unwrap_or_else(|| async { recovery_attempt .record_payment_attempt( state, req_state, merchant_context, profile, &payment_intent, &data.billing_merchant_connector_id, Some(payment_merchant_connector_account), ) .await }) .await } fn get_recovery_invoice_transaction_details( connector_enum: &connector_integration_interface::ConnectorEnum, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, billing_connector_invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData, ) -> CustomResult<Self, errors::RevenueRecoveryError> { billing_connector_payment_details.map_or_else( || { interface_webhooks::IncomingWebhook::get_revenue_recovery_attempt_details( connector_enum, request_details, ) .change_context(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed) .attach_printable( "Failed to get recovery attempt details from the billing connector", ) .map(RevenueRecoveryAttempt) }, |data| { Ok(Self(revenue_recovery::RevenueRecoveryAttemptData::from(( data, billing_connector_invoice_details, )))) }, ) } pub fn get_revenue_recovery_attempt( payment_intent: &domain_payments::PaymentIntent, revenue_recovery_metadata: &api_payments::PaymentRevenueRecoveryMetadata, billing_connector_account: &domain::MerchantConnectorAccount, card_info: api_payments::AdditionalCardInfo, payment_processor_token: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let revenue_recovery_data = payment_intent .create_revenue_recovery_attempt_data( revenue_recovery_metadata.clone(), billing_connector_account, card_info, payment_processor_token, ) .change_context(errors::RevenueRecoveryError::RevenueRecoveryAttemptDataCreateFailed) .attach_printable("Failed to build recovery attempt data")?; Ok(Self(revenue_recovery_data)) } async fn get_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_intent: &revenue_recovery::RecoveryPaymentIntent, ) -> CustomResult< Option<( revenue_recovery::RecoveryPaymentAttempt, revenue_recovery::RecoveryPaymentIntent, )>, errors::RevenueRecoveryError, > { let attempt_response = Box::pin(payments::payments_list_attempts_using_payment_intent_id::< payments::operations::PaymentGetListAttempts, api_payments::PaymentAttemptListResponse, _, payments::operations::payment_attempt_list::PaymentGetListAttempts, hyperswitch_domain_models::payments::PaymentAttemptListData< payments::operations::PaymentGetListAttempts, >, >( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), payments::operations::PaymentGetListAttempts, api_payments::PaymentAttemptListRequest { payment_intent_id: payment_intent.payment_id.clone(), }, payment_intent.payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await; let response = match attempt_response { Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => { let final_attempt = self .0 .charge_id .as_ref() .map(|charge_id| { payments_response .find_attempt_in_attempts_list_using_charge_id(charge_id.clone()) }) .unwrap_or_else(|| { self.0 .connector_transaction_id .as_ref() .and_then(|transaction_id| { payments_response .find_attempt_in_attempts_list_using_connector_transaction_id( transaction_id, ) }) }); let payment_attempt = final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt { attempt_id: res.id.to_owned(), attempt_status: res.status.to_owned(), feature_metadata: res.feature_metadata.to_owned(), amount: res.amount.net_amount, network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available network_decline_code: res .error .clone() .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available error_code: res.error.clone().map(|error| error.code), created_at: res.created_at, }); // If we have an attempt, combine it with payment_intent in a tuple. let res_with_payment_intent_and_attempt = payment_attempt.map(|attempt| (attempt, (*payment_intent).clone())); Ok(res_with_payment_intent_and_attempt) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("Unexpected response from payment intent core"), error @ Err(_) => { logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("failed to fetch payment attempt in recovery webhook flow") } }?; Ok(response) } #[allow(clippy::too_many_arguments)] async fn record_payment_attempt( &self, state: &SessionState, req_state: &ReqState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_intent: &revenue_recovery::RecoveryPaymentIntent, billing_connector_account_id: &id_type::MerchantConnectorAccountId, payment_connector_account: Option<domain::MerchantConnectorAccount>, ) -> CustomResult< ( revenue_recovery::RecoveryPaymentAttempt, revenue_recovery::RecoveryPaymentIntent, ), errors::RevenueRecoveryError, > { let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone()); let payment_connector_name = payment_connector_account .as_ref() .map(|account| account.connector_name); let request_payload: api_payments::PaymentsAttemptRecordRequest = self .create_payment_record_request( state, billing_connector_account_id, payment_connector_id, payment_connector_name, common_enums::TriggeredBy::External, ) .await?; let attempt_response = Box::pin(payments::record_attempt_core( state.clone(), req_state.clone(), merchant_context.clone(), profile.clone(), request_payload, payment_intent.payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await; let (recovery_attempt, updated_recovery_intent) = match attempt_response { Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => { Ok(( revenue_recovery::RecoveryPaymentAttempt { attempt_id: attempt_response.id.clone(), attempt_status: attempt_response.status, feature_metadata: attempt_response.payment_attempt_feature_metadata, amount: attempt_response.amount, network_advice_code: attempt_response .error_details .clone() .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available network_decline_code: attempt_response .error_details .clone() .and_then(|error| error.network_decline_code), // Placeholder, to be populated if available error_code: attempt_response .error_details .clone() .map(|error| error.code), created_at: attempt_response.created_at, }, revenue_recovery::RecoveryPaymentIntent { payment_id: payment_intent.payment_id.clone(), status: attempt_response.status.into(), // Using status from attempt_response feature_metadata: attempt_response.payment_intent_feature_metadata, // Using feature_metadata from attempt_response merchant_id: payment_intent.merchant_id.clone(), merchant_reference_id: payment_intent.merchant_reference_id.clone(), invoice_amount: payment_intent.invoice_amount, invoice_currency: payment_intent.invoice_currency, created_at: payment_intent.created_at, billing_address: payment_intent.billing_address.clone(), }, )) } Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("Unexpected response from record attempt core"), error @ Err(_) => { logger::error!(?error); Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed) .attach_printable("failed to record attempt in recovery webhook flow") } }?; let response = (recovery_attempt, updated_recovery_intent); self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name) .await .map_err(|e| { router_env::logger::error!( "Failed to store payment processor tokens in Redis: {:?}", e ); errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed })?; Ok(response) } pub async fn create_payment_record_request( &self, state: &SessionState, billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId, payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>, payment_connector: Option<common_enums::connector_enums::Connector>, triggered_by: common_enums::TriggeredBy, ) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError> { let revenue_recovery_attempt_data = &self.0; let amount_details = api_payments::PaymentAttemptAmountDetails::from(revenue_recovery_attempt_data); let feature_metadata = api_payments::PaymentAttemptFeatureMetadata { revenue_recovery: Some(api_payments::PaymentAttemptRevenueRecoveryData { // Since we are recording the external paymenmt attempt, this is hardcoded to External attempt_triggered_by: triggered_by, charge_id: self.0.charge_id.clone(), }), }; let card_info = revenue_recovery_attempt_data .card_info .card_isin .clone() .async_and_then(|isin| async move { let issuer_identifier_number = isin.clone(); state .store .get_card_info(issuer_identifier_number.as_str()) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten(); let payment_method_data = api_models::payments::RecordAttemptPaymentMethodDataRequest { payment_method_data: api_models::payments::AdditionalPaymentData::Card(Box::new( revenue_recovery_attempt_data.card_info.clone(), )), billing: None, }; let card_issuer = revenue_recovery_attempt_data.card_info.card_issuer.clone(); let error = Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data); Ok(api_payments::PaymentsAttemptRecordRequest { amount_details, status: revenue_recovery_attempt_data.status, billing: None, shipping: None, connector: payment_connector, payment_merchant_connector_id: payment_merchant_connector_account_id, error, description: None, connector_transaction_id: revenue_recovery_attempt_data .connector_transaction_id .clone(), payment_method_type: revenue_recovery_attempt_data.payment_method_type, billing_connector_id: billing_merchant_connector_account_id.clone(), payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type, payment_method_data: Some(payment_method_data), metadata: None, feature_metadata: Some(feature_metadata), transaction_created_at: revenue_recovery_attempt_data.transaction_created_at, processor_payment_method_token: revenue_recovery_attempt_data .processor_payment_method_token .clone(), connector_customer_id: revenue_recovery_attempt_data.connector_customer_id.clone(), retry_count: revenue_recovery_attempt_data.retry_count, invoice_next_billing_time: revenue_recovery_attempt_data.invoice_next_billing_time, invoice_billing_started_at_time: revenue_recovery_attempt_data .invoice_billing_started_at_time, triggered_by, card_network: revenue_recovery_attempt_data.card_info.card_network.clone(), card_issuer, }) } pub async fn find_payment_merchant_connector_account( &self, state: &SessionState, key_store: &domain::MerchantKeyStore, billing_connector_account: &domain::MerchantConnectorAccount, ) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> { let payment_merchant_connector_account_id = billing_connector_account .get_payment_merchant_connector_account_id_using_account_reference_id( self.0.connector_account_reference_id.clone(), ); let db = &*state.store; let key_manager_state = &(state).into(); let payment_merchant_connector_account = payment_merchant_connector_account_id .as_ref() .async_map(|mca_id| async move { db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store) .await }) .await .transpose() .change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound) .attach_printable( "failed to fetch payment merchant connector id using account reference id", )?; Ok(payment_merchant_connector_account) } #[allow(clippy::too_many_arguments)] async fn get_recovery_payment_attempt( is_recovery_transaction_event: bool, billing_connector_account: &domain::MerchantConnectorAccount, state: &SessionState, connector_enum: &connector_integration_interface::ConnectorEnum, req_state: &ReqState, billing_connector_payment_details: Option< &revenue_recovery_response::BillingConnectorPaymentsSyncResponse, >, request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_intent: &revenue_recovery::RecoveryPaymentIntent, invoice_details: &revenue_recovery::RevenueRecoveryInvoiceData, ) -> CustomResult< ( Option<revenue_recovery::RecoveryPaymentAttempt>, revenue_recovery::RecoveryPaymentIntent, ), errors::RevenueRecoveryError, > { let payment_attempt_with_recovery_intent = match is_recovery_transaction_event { true => { let invoice_transaction_details = Self::get_recovery_invoice_transaction_details( connector_enum, request_details, billing_connector_payment_details, invoice_details, )?; // Find the payment merchant connector ID at the top level to avoid multiple DB calls. let payment_merchant_connector_account = invoice_transaction_details .find_payment_merchant_connector_account( state, merchant_context.get_merchant_key_store(), billing_connector_account, ) .await?; let (payment_attempt, updated_payment_intent) = invoice_transaction_details .get_payment_attempt( state, req_state, merchant_context, business_profile, payment_intent, ) .await .transpose() .async_unwrap_or_else(|| async { invoice_transaction_details .record_payment_attempt( state, req_state, merchant_context, business_profile, payment_intent, &billing_connector_account.get_id(), payment_merchant_connector_account, ) .await }) .await?; (Some(payment_attempt), updated_payment_intent) } false => (None, payment_intent.clone()), }; Ok(payment_attempt_with_recovery_intent) } /// Store payment processor tokens in Redis for retry management async fn store_payment_processor_tokens_in_redis( &self, state: &SessionState, recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt, payment_connector_name: Option<common_enums::connector_enums::Connector>, ) -> CustomResult<(), errors::RevenueRecoveryError> { let revenue_recovery_attempt_data = &self.0; let error_code = revenue_recovery_attempt_data.error_code.clone(); let error_message = revenue_recovery_attempt_data.error_message.clone(); let connector_name = payment_connector_name .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed) .attach_printable("unable to derive payment connector")? .to_string(); let gsm_record = helpers::get_gsm_record( state, error_code.clone(), error_message, connector_name, REVENUE_RECOVERY.to_string(), ) .await; let is_hard_decline = gsm_record .and_then(|record| record.error_category) .map(|category| category == common_enums::ErrorCategory::HardDecline) .unwrap_or(false); // Extract required fields from the revenue recovery attempt data let connector_customer_id = revenue_recovery_attempt_data.connector_customer_id.clone(); let attempt_id = recovery_attempt.attempt_id.clone(); let token_unit = PaymentProcessorTokenStatus { error_code, inserted_by_attempt_id: attempt_id.clone(), daily_retry_history: HashMap::from([(recovery_attempt.created_at.date(), 1)]), scheduled_at: None, is_hard_decline: Some(is_hard_decline), payment_processor_token_details: PaymentProcessorTokenDetails { payment_processor_token: revenue_recovery_attempt_data .processor_payment_method_token .clone(), expiry_month: revenue_recovery_attempt_data .card_info .card_exp_month .clone(), expiry_year: revenue_recovery_attempt_data .card_info .card_exp_year .clone(), card_issuer: revenue_recovery_attempt_data.card_info.card_issuer.clone(), last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(), card_network: revenue_recovery_attempt_data.card_info.card_network.clone(), card_type: revenue_recovery_attempt_data.card_info.card_type.clone(), }, }; // Make the Redis call to store tokens RedisTokenManager::upsert_payment_processor_token( state, &connector_customer_id, token_unit, ) .await .change_context(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed) .attach_printable("Failed to store payment processor tokens in Redis")?; Ok(()) } } pub struct BillingConnectorPaymentsSyncResponseData( revenue_recovery_response::BillingConnectorPaymentsSyncResponse, ); pub struct BillingConnectorPaymentsSyncFlowRouterData( router_types::BillingConnectorPaymentsSyncRouterData, ); impl BillingConnectorPaymentsSyncResponseData { async fn handle_billing_connector_payment_sync_call( state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedBillingConnectorPaymentsSyncIntegrationInterface< router_flow_types::BillingConnectorPaymentsSync, revenue_recovery_request::BillingConnectorPaymentsSyncRequest, revenue_recovery_response::BillingConnectorPaymentsSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = BillingConnectorPaymentsSyncFlowRouterData::construct_router_data_for_billing_connector_payment_sync_call( state, connector_name, merchant_connector_account, merchant_context, id, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable( "Failed while constructing router data for billing connector psync call", )? .inner(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details")?; let additional_recovery_details = match response.response { Ok(response) => Ok(response), error @ Err(_) => { logger::error!(?error); Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector payment details") } }?; Ok(Self(additional_recovery_details)) } async fn get_billing_connector_payment_details( should_billing_connector_payment_api_called: bool, state: &SessionState, merchant_context: &domain::MerchantContext, billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, object_ref_id: &webhooks::ObjectReferenceId, ) -> CustomResult< Option<revenue_recovery_response::BillingConnectorPaymentsSyncResponse>, errors::RevenueRecoveryError, > { let response_data = match should_billing_connector_payment_api_called { true => { let billing_connector_transaction_id = object_ref_id .clone() .get_connector_transaction_id_as_string() .change_context( errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed, ) .attach_printable("Billing connector Payments api call failed")?; let billing_connector_payment_details = Self::handle_billing_connector_payment_sync_call( state, merchant_context, billing_connector_account, connector_name, &billing_connector_transaction_id, ) .await?; Some(billing_connector_payment_details.inner()) } false => None, }; Ok(response_data) } fn inner(self) -> revenue_recovery_response::BillingConnectorPaymentsSyncResponse { self.0 } } impl BillingConnectorPaymentsSyncFlowRouterData { async fn construct_router_data_for_billing_connector_payment_sync_call( state: &SessionState, connector_name: &str, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, merchant_context: &domain::MerchantContext, billing_connector_psync_id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal( Box::new(merchant_connector_account.clone()), ) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)?; let connector = common_enums::connector_enums::Connector::from_str(connector_name) .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable("Cannot find connector from the connector_name")?; let connector_params = hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( &state.conf.connectors, connector, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable(format!( "cannot find connector params for this connector {connector} in this flow", ))?; let router_data = types::RouterDataV2 { flow: PhantomData::<router_flow_types::BillingConnectorPaymentsSync>, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: flow_common_types::BillingConnectorPaymentsSyncFlowData, connector_auth_type: auth_type, request: revenue_recovery_request::BillingConnectorPaymentsSyncRequest { connector_params, billing_connector_psync_id: billing_connector_psync_id.to_string(), }, response: Err(types::ErrorResponse::default()), }; let old_router_data = flow_common_types::BillingConnectorPaymentsSyncFlowData::to_old_router_data( router_data, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable( "Cannot construct router data for making the billing connector payments api call", )?; Ok(Self(old_router_data)) } fn inner(self) -> router_types::BillingConnectorPaymentsSyncRouterData { self.0 } } pub struct BillingConnectorInvoiceSyncResponseData( revenue_recovery_response::BillingConnectorInvoiceSyncResponse, ); pub struct BillingConnectorInvoiceSyncFlowRouterData( router_types::BillingConnectorInvoiceSyncRouterData, ); impl BillingConnectorInvoiceSyncResponseData { async fn handle_billing_connector_invoice_sync_call( state: &SessionState, merchant_context: &domain::MerchantContext, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let connector_data = api::ConnectorData::get_connector_by_name( &state.conf.connectors, connector_name, api::GetToken::Connector, None, ) .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable("invalid connector name received in payment attempt")?; let connector_integration: services::BoxedBillingConnectorInvoiceSyncIntegrationInterface< router_flow_types::BillingConnectorInvoiceSync, revenue_recovery_request::BillingConnectorInvoiceSyncRequest, revenue_recovery_response::BillingConnectorInvoiceSyncResponse, > = connector_data.connector.get_connector_integration(); let router_data = BillingConnectorInvoiceSyncFlowRouterData::construct_router_data_for_billing_connector_invoice_sync_call( state, connector_name, merchant_connector_account, merchant_context, id, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable( "Failed while constructing router data for billing connector psync call", )? .inner(); let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable("Failed while fetching billing connector Invoice details")?; let additional_recovery_details = match response.response { Ok(response) => Ok(response), error @ Err(_) => { logger::error!(?error); Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable("Failed while fetching billing connector Invoice details") } }?; Ok(Self(additional_recovery_details)) } async fn get_billing_connector_invoice_details( should_billing_connector_invoice_api_called: bool, state: &SessionState, merchant_context: &domain::MerchantContext, billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, connector_name: &str, merchant_reference_id: Option<id_type::PaymentReferenceId>, ) -> CustomResult< Option<revenue_recovery_response::BillingConnectorInvoiceSyncResponse>, errors::RevenueRecoveryError, > { let response_data = match should_billing_connector_invoice_api_called { true => { let billing_connector_invoice_id = merchant_reference_id .as_ref() .map(|id| id.get_string_repr()) .ok_or(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?; let billing_connector_invoice_details = Self::handle_billing_connector_invoice_sync_call( state, merchant_context, billing_connector_account, connector_name, billing_connector_invoice_id, ) .await?; Some(billing_connector_invoice_details.inner()) } false => None, }; Ok(response_data) } fn inner(self) -> revenue_recovery_response::BillingConnectorInvoiceSyncResponse { self.0 } } impl BillingConnectorInvoiceSyncFlowRouterData { async fn construct_router_data_for_billing_connector_invoice_sync_call( state: &SessionState, connector_name: &str, merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, merchant_context: &domain::MerchantContext, billing_connector_invoice_id: &str, ) -> CustomResult<Self, errors::RevenueRecoveryError> { let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal( Box::new(merchant_connector_account.clone()), ) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?; let connector = common_enums::connector_enums::Connector::from_str(connector_name) .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable("Cannot find connector from the connector_name")?; let connector_params = hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( &state.conf.connectors, connector, ) .change_context(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed) .attach_printable(format!( "cannot find connector params for this connector {connector} in this flow", ))?; let router_data = types::RouterDataV2 { flow: PhantomData::<router_flow_types::BillingConnectorInvoiceSync>, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: flow_common_types::BillingConnectorInvoiceSyncFlowData, connector_auth_type: auth_type, request: revenue_recovery_request::BillingConnectorInvoiceSyncRequest { billing_connector_invoice_id: billing_connector_invoice_id.to_string(), connector_params, }, response: Err(types::ErrorResponse::default()), }; let old_router_data = flow_common_types::BillingConnectorInvoiceSyncFlowData::to_old_router_data( router_data, ) .change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed) .attach_printable( "Cannot construct router data for making the billing connector invoice api call", )?; Ok(Self(old_router_data)) } fn inner(self) -> router_types::BillingConnectorInvoiceSyncRouterData { self.0 } } #[derive(Clone, Debug)] pub struct RecoveryPaymentTuple( revenue_recovery::RecoveryPaymentIntent, revenue_recovery::RecoveryPaymentAttempt, ); impl RecoveryPaymentTuple { pub fn new( payment_intent: &revenue_recovery::RecoveryPaymentIntent, payment_attempt: &revenue_recovery::RecoveryPaymentAttempt, ) -> Self { Self(payment_intent.clone(), payment_attempt.clone()) } pub async fn publish_revenue_recovery_event_to_kafka( state: &SessionState, recovery_payment_tuple: &Self, retry_count: Option<i32>, ) -> CustomResult<(), errors::RevenueRecoveryError> { let recovery_payment_intent = &recovery_payment_tuple.0; let recovery_payment_attempt = &recovery_payment_tuple.1; let revenue_recovery_feature_metadata = recovery_payment_intent .feature_metadata .as_ref() .and_then(|metadata| metadata.revenue_recovery.as_ref()); let billing_city = recovery_payment_intent .billing_address .as_ref() .and_then(|billing_address| billing_address.address.as_ref()) .and_then(|address| address.city.clone()) .map(Secret::new); let billing_state = recovery_payment_intent .billing_address .as_ref() .and_then(|billing_address| billing_address.address.as_ref()) .and_then(|address| address.state.clone()); let billing_country = recovery_payment_intent .billing_address .as_ref() .and_then(|billing_address| billing_address.address.as_ref()) .and_then(|address| address.country); let card_info = revenue_recovery_feature_metadata.and_then(|metadata| { metadata .billing_connector_payment_method_details .as_ref() .and_then(|details| details.get_billing_connector_card_info()) }); #[allow(clippy::as_conversions)] let retry_count = Some(retry_count.unwrap_or_else(|| { revenue_recovery_feature_metadata .map(|data| data.total_retry_count as i32) .unwrap_or(0) })); let event = kafka::revenue_recovery::RevenueRecovery { merchant_id: &recovery_payment_intent.merchant_id, invoice_amount: recovery_payment_intent.invoice_amount, invoice_currency: &recovery_payment_intent.invoice_currency, invoice_date: revenue_recovery_feature_metadata.and_then(|data| { data.invoice_billing_started_at_time .map(|time| time.assume_utc()) }), invoice_due_date: revenue_recovery_feature_metadata .and_then(|data| data.invoice_next_billing_time.map(|time| time.assume_utc())), billing_city, billing_country: billing_country.as_ref(), billing_state, attempt_amount: recovery_payment_attempt.amount, attempt_currency: &recovery_payment_intent.invoice_currency.clone(), attempt_status: &recovery_payment_attempt.attempt_status.clone(), pg_error_code: recovery_payment_attempt.error_code.clone(), network_advice_code: recovery_payment_attempt.network_advice_code.clone(), network_error_code: recovery_payment_attempt.network_decline_code.clone(), first_pg_error_code: revenue_recovery_feature_metadata .and_then(|data| data.first_payment_attempt_pg_error_code.clone()), first_network_advice_code: revenue_recovery_feature_metadata .and_then(|data| data.first_payment_attempt_network_advice_code.clone()), first_network_error_code: revenue_recovery_feature_metadata .and_then(|data| data.first_payment_attempt_network_decline_code.clone()), attempt_created_at: recovery_payment_attempt.created_at.assume_utc(), payment_method_type: revenue_recovery_feature_metadata .map(|data| &data.payment_method_type), payment_method_subtype: revenue_recovery_feature_metadata .map(|data| &data.payment_method_subtype), card_network: card_info .as_ref() .and_then(|info| info.card_network.as_ref()), card_issuer: card_info.and_then(|data| data.card_issuer.clone()), retry_count, payment_gateway: revenue_recovery_feature_metadata.map(|data| data.connector), }; state.event_handler.log_event(&event); Ok(()) } } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct RecoveryAction { pub action: common_types::payments::RecoveryAction, } impl RecoveryAction { pub fn get_action( event_type: webhooks::IncomingWebhookEvent, attempt_triggered_by: Option<common_enums::TriggeredBy>, ) -> common_types::payments::RecoveryAction { match event_type { webhooks::IncomingWebhookEvent::PaymentIntentFailure | webhooks::IncomingWebhookEvent::PaymentIntentSuccess | webhooks::IncomingWebhookEvent::PaymentIntentProcessing | webhooks::IncomingWebhookEvent::PaymentIntentPartiallyFunded | webhooks::IncomingWebhookEvent::PaymentIntentCancelled | webhooks::IncomingWebhookEvent::PaymentIntentCancelFailure | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess | webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationFailure | webhooks::IncomingWebhookEvent::PaymentIntentCaptureSuccess | webhooks::IncomingWebhookEvent::PaymentIntentCaptureFailure | webhooks::IncomingWebhookEvent::PaymentIntentExpired | webhooks::IncomingWebhookEvent::PaymentActionRequired | webhooks::IncomingWebhookEvent::EventNotSupported | webhooks::IncomingWebhookEvent::SourceChargeable | webhooks::IncomingWebhookEvent::SourceTransactionCreated | webhooks::IncomingWebhookEvent::RefundFailure | webhooks::IncomingWebhookEvent::RefundSuccess | webhooks::IncomingWebhookEvent::DisputeOpened | webhooks::IncomingWebhookEvent::DisputeExpired | webhooks::IncomingWebhookEvent::DisputeAccepted | webhooks::IncomingWebhookEvent::DisputeCancelled | webhooks::IncomingWebhookEvent::DisputeChallenged | webhooks::IncomingWebhookEvent::DisputeWon | webhooks::IncomingWebhookEvent::DisputeLost | webhooks::IncomingWebhookEvent::MandateActive | webhooks::IncomingWebhookEvent::MandateRevoked | webhooks::IncomingWebhookEvent::EndpointVerification | webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationSuccess | webhooks::IncomingWebhookEvent::PaymentIntentExtendAuthorizationFailure | webhooks::IncomingWebhookEvent::ExternalAuthenticationARes | webhooks::IncomingWebhookEvent::FrmApproved | webhooks::IncomingWebhookEvent::FrmRejected | webhooks::IncomingWebhookEvent::PayoutSuccess | webhooks::IncomingWebhookEvent::PayoutFailure | webhooks::IncomingWebhookEvent::PayoutProcessing | webhooks::IncomingWebhookEvent::PayoutCancelled | webhooks::IncomingWebhookEvent::PayoutCreated | webhooks::IncomingWebhookEvent::PayoutExpired | webhooks::IncomingWebhookEvent::PayoutReversed | webhooks::IncomingWebhookEvent::InvoiceGenerated | webhooks::IncomingWebhookEvent::SetupWebhook => { common_types::payments::RecoveryAction::InvalidAction } webhooks::IncomingWebhookEvent::RecoveryPaymentFailure => match attempt_triggered_by { Some(common_enums::TriggeredBy::Internal) => { common_types::payments::RecoveryAction::NoAction } Some(common_enums::TriggeredBy::External) | None => { common_types::payments::RecoveryAction::ScheduleFailedPayment } }, webhooks::IncomingWebhookEvent::RecoveryPaymentSuccess => match attempt_triggered_by { Some(common_enums::TriggeredBy::Internal) => { common_types::payments::RecoveryAction::NoAction } Some(common_enums::TriggeredBy::External) | None => { common_types::payments::RecoveryAction::SuccessPaymentExternal } }, webhooks::IncomingWebhookEvent::RecoveryPaymentPending => { common_types::payments::RecoveryAction::PendingPayment } webhooks::IncomingWebhookEvent::RecoveryInvoiceCancel => { common_types::payments::RecoveryAction::CancelInvoice } } } #[allow(clippy::too_many_arguments)] pub async fn handle_action( &self, state: &SessionState, business_profile: &domain::Profile, merchant_context: &domain::MerchantContext, billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount, mca_retry_threshold: u16, intent_retry_count: u16, recovery_tuple: &( Option<revenue_recovery::RecoveryPaymentAttempt>, revenue_recovery::RecoveryPaymentIntent, ), ) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> { match self.action { common_types::payments::RecoveryAction::CancelInvoice => todo!(), common_types::payments::RecoveryAction::ScheduleFailedPayment => { let recovery_algorithm_type = business_profile .revenue_recovery_retry_algorithm_type .ok_or(report!( errors::RevenueRecoveryError::RetryAlgorithmTypeNotFound ))?; match recovery_algorithm_type { api_enums::RevenueRecoveryAlgorithmType::Monitoring => { handle_monitoring_threshold( state, business_profile, merchant_context.get_merchant_key_store(), ) .await } revenue_recovery_retry_type => { handle_schedule_failed_payment( billing_connector_account, intent_retry_count, mca_retry_threshold, state, merchant_context, recovery_tuple, business_profile, revenue_recovery_retry_type, ) .await } } } common_types::payments::RecoveryAction::SuccessPaymentExternal => { logger::info!("Payment has been succeeded via external system"); Ok(webhooks::WebhookResponseTracker::NoEffect) } common_types::payments::RecoveryAction::PendingPayment => { logger::info!( "Pending transactions are not consumed by the revenue recovery webhooks" ); Ok(webhooks::WebhookResponseTracker::NoEffect) } common_types::payments::RecoveryAction::NoAction => { logger::info!( "No Recovery action is taken place for recovery event and attempt triggered_by" ); Ok(webhooks::WebhookResponseTracker::NoEffect) } common_types::payments::RecoveryAction::InvalidAction => { logger::error!("Invalid Revenue recovery action state has been received"); Ok(webhooks::WebhookResponseTracker::NoEffect) } } } }
{ "crate": "router", "file": "crates/router/src/core/webhooks/recovery_incoming.rs", "file_size": 68371, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_6613088801097015282
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payouts/helpers.rs // File size: 66311 bytes use ::payment_methods::controller::PaymentMethodsController; use api_models::{enums, payment_methods::Card, payouts}; use common_utils::{ crypto::Encryptable, encryption::Encryption, errors::CustomResult, ext_traits::{AsyncExt, StringExt, ValueExt}, fp_utils, id_type, payout_method_utils as payout_additional, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, UnifiedCode, UnifiedMessage, }, }; #[cfg(feature = "v1")] use common_utils::{generate_customer_id_of_default_length, types::keymanager::ToEncryptable}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy}; use router_env::logger; use super::PayoutData; #[cfg(feature = "payouts")] use crate::core::payments::route_connector_v1_for_payouts; use crate::{ consts, core::{ errors::{self, RouterResult, StorageErrorExt}, payment_methods::{ cards, transformers::{DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq}, vault, }, payments::{helpers as payment_helpers, routing, CustomerDetails}, routing::TransactionData, utils as core_utils, }, db::StorageInterface, routes::{metrics, SessionState}, services, types::{ self as router_types, api::{self, enums as api_enums}, domain::{self, types::AsyncLift}, storage, transformers::ForeignFrom, }, utils::{self, OptionExt}, }; #[allow(clippy::too_many_arguments)] pub async fn make_payout_method_data( state: &SessionState, payout_method_data: Option<&api::PayoutMethodData>, payout_token: Option<&str>, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, payout_type: Option<api_enums::PayoutType>, merchant_key_store: &domain::MerchantKeyStore, payout_data: Option<&mut PayoutData>, storage_scheme: storage::enums::MerchantStorageScheme, ) -> RouterResult<Option<api::PayoutMethodData>> { let db = &*state.store; let hyperswitch_token = if let Some(payout_token) = payout_token { if payout_token.starts_with("temporary_token_") { Some(payout_token.to_string()) } else { let certain_payout_type = payout_type.get_required_value("payout_type")?.to_owned(); let key = format!( "pm_token_{}_{}_hyperswitch", payout_token, api_enums::PaymentMethod::foreign_from(certain_payout_type) ); let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; let hyperswitch_token = redis_conn .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? .ok_or(error_stack::Report::new( errors::ApiErrorResponse::UnprocessableEntity { message: "Token is invalid or expired".to_owned(), }, ))?; let payment_token_data = hyperswitch_token .clone() .parse_struct("PaymentTokenData") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to deserialize hyperswitch token data")?; let payment_token = match payment_token_data { storage::PaymentTokenData::PermanentCard(storage::CardTokenData { locker_id, token, .. }) => locker_id.or(Some(token)), storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData { token, }) => Some(token), _ => None, }; payment_token.or(Some(payout_token.to_string())) } } else { None }; match ( payout_method_data.to_owned(), hyperswitch_token, payout_data, ) { // Get operation (None, Some(payout_token), _) => { if payout_token.starts_with("temporary_token_") || payout_type == Some(api_enums::PayoutType::Bank) { let (pm, supplementary_data) = vault::Vault::get_payout_method_data_from_temporary_locker( state, &payout_token, merchant_key_store, ) .await .attach_printable( "Payout method for given token not found or there was a problem fetching it", )?; utils::when( supplementary_data .customer_id .ne(&Some(customer_id.to_owned())), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payout method and customer passed in payout are not same".into() }) }, )?; Ok(pm) } else { let resp = cards::get_card_from_locker( state, customer_id, merchant_id, payout_token.as_ref(), ) .await .attach_printable("Payout method [card] could not be fetched from HS locker")?; Ok(Some({ api::PayoutMethodData::Card(api::CardPayout { card_number: resp.card_number, expiry_month: resp.card_exp_month, expiry_year: resp.card_exp_year, card_holder_name: resp.name_on_card, }) })) } } // Create / Update operation (Some(payout_method), payout_token, Some(payout_data)) => { let lookup_key = vault::Vault::store_payout_method_data_in_locker( state, payout_token.to_owned(), payout_method, Some(customer_id.to_owned()), merchant_key_store, ) .await?; // Update payout_token in payout_attempt table if payout_token.is_none() { let updated_payout_attempt = storage::PayoutAttemptUpdate::PayoutTokenUpdate { payout_token: lookup_key, }; payout_data.payout_attempt = db .update_payout_attempt( &payout_data.payout_attempt, updated_payout_attempt, &payout_data.payouts, storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating token in payout attempt")?; } Ok(Some(payout_method.clone())) } // Ignore if nothing is passed _ => Ok(None), } } pub fn should_create_connector_transfer_method( payout_data: &PayoutData, connector_data: &api::ConnectorData, ) -> RouterResult<Option<String>> { let connector_transfer_method_id = payout_data.payment_method.as_ref().and_then(|pm| { let common_mandate_reference = pm .get_common_mandate_reference() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to deserialize connector mandate details") .ok()?; connector_data .merchant_connector_id .as_ref() .and_then(|merchant_connector_id| { common_mandate_reference .payouts .and_then(|payouts_mandate_reference| { payouts_mandate_reference .get(merchant_connector_id) .and_then(|payouts_mandate_reference_record| { payouts_mandate_reference_record.transfer_method_id.clone() }) }) }) }); Ok(connector_transfer_method_id) } pub async fn fetch_payout_method_data( state: &SessionState, payout_data: &mut PayoutData, connector_data: &api::ConnectorData, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { let connector_transfer_method_id = should_create_connector_transfer_method(payout_data, connector_data)?; if connector_transfer_method_id.is_some() { logger::info!("Using stored transfer_method_id, skipping payout_method_data fetch"); } else { let customer_id = payout_data .payouts .customer_id .clone() .get_required_value("customer_id")?; let payout_method_data_clone = payout_data.payout_method_data.clone(); let payout_token = payout_data.payout_attempt.payout_token.clone(); let merchant_id = payout_data.payout_attempt.merchant_id.clone(); let payout_type = payout_data.payouts.payout_type; let payout_method_data = make_payout_method_data( state, payout_method_data_clone.as_ref(), payout_token.as_deref(), &customer_id, &merchant_id, payout_type, merchant_context.get_merchant_key_store(), Some(payout_data), merchant_context.get_merchant_account().storage_scheme, ) .await? .get_required_value("payout_method_data")?; payout_data.payout_method_data = Some(payout_method_data); } Ok(()) } #[cfg(feature = "v1")] pub async fn save_payout_data_to_locker( state: &SessionState, payout_data: &mut PayoutData, customer_id: &id_type::CustomerId, payout_method_data: &api::PayoutMethodData, connector_mandate_details: Option<serde_json::Value>, merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { let mut pm_id: Option<String> = None; let payouts = &payout_data.payouts; let key_manager_state = state.into(); let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) = match payout_method_data { payouts::PayoutMethodData::Card(card) => { let card_detail = api::CardDetail { card_number: card.card_number.to_owned(), card_holder_name: card.card_holder_name.to_owned(), card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), nick_name: None, card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { merchant_id: merchant_context.get_merchant_account().get_id().clone(), merchant_customer_id: customer_id.to_owned(), card: Card { card_number: card.card_number.to_owned(), name_on_card: card.card_holder_name.to_owned(), card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), card_brand: None, card_isin: None, nick_name: None, }, requestor_card_reference: None, ttl: state.conf.locker.ttl_for_storage_in_secs, }); ( payload, Some(card_detail), None, None, api_enums::PaymentMethodType::Debit, ) } _ => { let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let key_manager_state: KeyManagerState = state.into(); let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encode payout method data") .ok() .map(|v| { let secret: Secret<String> = Secret::new(v.to_string()); secret }) .async_lift(|inner| async { crypto_operation( &key_manager_state, type_name!(storage::PaymentMethod), CryptoOperation::EncryptOptional(inner), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await } .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt payout method data")? .map(Encryption::from) .map(|e| e.into_inner()) .map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| { Ok(hex::encode(e.peek())) })?; let payload = StoreLockerReq::LockerGeneric(StoreGenericReq { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), merchant_customer_id: customer_id.to_owned(), enc_data, ttl: state.conf.locker.ttl_for_storage_in_secs, }); match payout_method_data { payouts::PayoutMethodData::Bank(bank) => ( payload, None, Some(bank.to_owned()), None, api_enums::PaymentMethodType::foreign_from(bank), ), payouts::PayoutMethodData::Wallet(wallet) => ( payload, None, None, Some(wallet.to_owned()), api_enums::PaymentMethodType::foreign_from(wallet), ), payouts::PayoutMethodData::Card(_) | payouts::PayoutMethodData::BankRedirect(_) => { Err(errors::ApiErrorResponse::InternalServerError)? } } } }; // Store payout method in locker let stored_resp = cards::add_card_to_hs_locker( state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let db = &*state.store; // Handle duplicates let (should_insert_in_pm_table, metadata_update) = match stored_resp.duplication_check { // Check if equivalent entry exists in payment_methods Some(duplication_check) => { let locker_ref = stored_resp.card_reference.clone(); // Use locker ref as payment_method_id let existing_pm_by_pmid = db .find_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), &locker_ref, merchant_context.get_merchant_account().storage_scheme, ) .await; match existing_pm_by_pmid { // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_method's table Ok(pm) => { pm_id = Some(pm.payment_method_id.clone()); ( false, if duplication_check == DataDuplicationCheck::MetaDataChanged { Some(pm.clone()) } else { None }, ) } // If not found, use locker ref as locker_id Err(err) => { if err.current_context().is_db_not_found() { match db .find_payment_method_by_locker_id( &(state.into()), merchant_context.get_merchant_key_store(), &locker_ref, merchant_context.get_merchant_account().storage_scheme, ) .await { // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_methods table Ok(pm) => { pm_id = Some(pm.payment_method_id.clone()); ( false, if duplication_check == DataDuplicationCheck::MetaDataChanged { Some(pm.clone()) } else { None }, ) } Err(err) => { // If not found, update locker's metadata [DELETE + INSERT OP], and insert in payment_methods table if err.current_context().is_db_not_found() { (true, None) // Misc. DB errors } else { Err(err) .change_context( errors::ApiErrorResponse::InternalServerError, ) .attach_printable( "DB failures while finding payment method by locker ID", )? } } } // Misc. DB errors } else { Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("DB failures while finding payment method by pm ID")? } } } } // Not duplicate, should be inserted in payment_methods table None => (true, None), }; // Form payment method entry and card's metadata whenever insertion or metadata update is required let (card_details_encrypted, new_payment_method) = if let (api::PayoutMethodData::Card(_), true, _) | (api::PayoutMethodData::Card(_), _, Some(_)) = ( payout_method_data, should_insert_in_pm_table, metadata_update.as_ref(), ) { // Fetch card info from db let card_isin = card_details.as_ref().map(|c| c.card_number.get_card_isin()); let mut payment_method = api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::foreign_from(payout_method_data)), payment_method_type: Some(payment_method_type), payment_method_issuer: None, payment_method_issuer_code: None, bank_transfer: None, card: card_details.clone(), wallet: None, metadata: None, customer_id: Some(customer_id.to_owned()), card_network: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }; let pm_data = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { payment_method .payment_method_issuer .clone_from(&card_info.card_issuer); payment_method.card_network = card_info.card_network.clone().map(|cn| cn.to_string()); api::payment_methods::PaymentMethodsData::Card( api::payment_methods::CardDetailsPaymentMethod { last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()), issuer_country: card_info.card_issuing_country, expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), card_holder_name: card_details .as_ref() .and_then(|c| c.card_holder_name.clone()), card_isin: card_isin.clone(), card_issuer: card_info.card_issuer, card_network: card_info.card_network, card_type: card_info.card_type, saved_to_locker: true, co_badged_card_data: None, }, ) }) .unwrap_or_else(|| { api::payment_methods::PaymentMethodsData::Card( api::payment_methods::CardDetailsPaymentMethod { last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()), issuer_country: None, expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), card_holder_name: card_details .as_ref() .and_then(|c| c.card_holder_name.clone()), card_isin: card_isin.clone(), card_issuer: None, card_network: None, card_type: None, saved_to_locker: true, co_badged_card_data: None, }, ) }); ( Some( cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), pm_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt customer details")?, ), payment_method, ) } else { ( None, api::PaymentMethodCreate { payment_method: Some(api_enums::PaymentMethod::foreign_from( payout_method_data, )), payment_method_type: Some(payment_method_type), payment_method_issuer: None, payment_method_issuer_code: None, bank_transfer: bank_details, card: None, wallet: wallet_details, metadata: None, customer_id: Some(customer_id.to_owned()), card_network: None, client_secret: None, payment_method_data: None, billing: None, connector_mandate_details: None, network_transaction_id: None, }, ) }; let payment_method_billing_address = payout_data .billing_address .clone() .async_map(|billing_addr| async { cards::create_encrypted_data( &key_manager_state, merchant_context.get_merchant_key_store(), billing_addr, ) .await }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt billing address")?; // Insert new entry in payment_methods table if should_insert_in_pm_table { let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); payout_data.payment_method = Some( cards::PmCards { state, merchant_context, } .create_payment_method( &new_payment_method, customer_id, &payment_method_id, Some(stored_resp.card_reference.clone()), merchant_context.get_merchant_account().get_id(), None, None, card_details_encrypted.clone(), connector_mandate_details, None, None, payment_method_billing_address, None, None, None, None, Default::default(), ) .await?, ); } /* 1. Delete from locker * 2. Create new entry in locker * 3. Handle creation response from locker * 4. Update card's metadata in payment_methods table */ if let Some(existing_pm) = metadata_update { let card_reference = &existing_pm .locker_id .clone() .unwrap_or(existing_pm.payment_method_id.clone()); // Delete from locker cards::delete_card_from_hs_locker( state, customer_id, merchant_context.get_merchant_account().get_id(), card_reference, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to delete PMD from locker as a part of metadata update operation", )?; locker_req.update_requestor_card_reference(Some(card_reference.to_string())); // Store in locker let stored_resp = cards::add_card_to_hs_locker( state, &locker_req, customer_id, api_enums::LockerChoice::HyperswitchCardVault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError); // Check if locker operation was successful or not, if not, delete the entry from payment_methods table if let Err(err) = stored_resp { logger::error!(vault_err=?err); db.delete_payment_method_by_merchant_id_payment_method_id( &(state.into()), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &existing_pm.payment_method_id, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; Err(errors::ApiErrorResponse::InternalServerError).attach_printable( "Failed to insert PMD from locker as a part of metadata update operation", )? }; // Update card's metadata in payment_methods table let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { payment_method_data: card_details_encrypted.map(Into::into), }; payout_data.payment_method = Some( db.update_payment_method( &(state.into()), merchant_context.get_merchant_key_store(), existing_pm, pm_update, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?, ); }; // Store card_reference in payouts table let payout_method_id = match &payout_data.payment_method { Some(pm) => pm.payment_method_id.clone(), None => { if let Some(id) = pm_id { id } else { Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method was not found")? } } }; let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id }; payout_data.payouts = db .update_payout( payouts, updated_payout, &payout_data.payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; Ok(()) } #[cfg(feature = "v2")] pub async fn save_payout_data_to_locker( _state: &SessionState, _payout_data: &mut PayoutData, _customer_id: &id_type::CustomerId, _payout_method_data: &api::PayoutMethodData, _connector_mandate_details: Option<serde_json::Value>, _merchant_context: &domain::MerchantContext, ) -> RouterResult<()> { todo!() } #[cfg(feature = "v2")] pub(super) async fn get_or_create_customer_details( _state: &SessionState, _customer_details: &CustomerDetails, _merchant_context: &domain::MerchantContext, ) -> RouterResult<Option<domain::Customer>> { todo!() } #[cfg(feature = "v1")] pub(super) async fn get_or_create_customer_details( state: &SessionState, customer_details: &CustomerDetails, merchant_context: &domain::MerchantContext, ) -> RouterResult<Option<domain::Customer>> { let db: &dyn StorageInterface = &*state.store; // Create customer_id if not passed in request let customer_id = customer_details .customer_id .clone() .unwrap_or_else(generate_customer_id_of_default_length); let merchant_id = merchant_context.get_merchant_account().get_id(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let key_manager_state = &state.into(); match db .find_customer_optional_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)? { // Customer found Some(customer) => Ok(Some(customer)), // Customer not found // create only if atleast one of the fields were provided for customer creation or else throw error None => { if customer_details.name.is_some() || customer_details.email.is_some() || customer_details.phone.is_some() || customer_details.phone_country_code.is_some() { let encrypted_data = crypto_operation( &state.into(), type_name!(domain::Customer), CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: customer_details.name.clone(), email: customer_details .email .clone() .map(|a| a.expose().switch_strategy()), phone: customer_details.phone.clone(), tax_registration_id: customer_details.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form EncryptableCustomer")?; let customer = domain::Customer { customer_id: customer_id.clone(), merchant_id: merchant_id.to_owned().clone(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: None, phone_country_code: customer_details.phone_country_code.to_owned(), metadata: None, connector_customer: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }; Ok(Some( db.insert_customer( customer, key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to insert customer [id - {customer_id:?}] for merchant [id - {merchant_id:?}]", ) })?, )) } else { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!("customer for id - {customer_id:?} not found"), })) } } } } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn decide_payout_connector( state: &SessionState, merchant_context: &domain::MerchantContext, request_straight_through: Option<api::routing::StraightThroughAlgorithm>, routing_data: &mut storage::RoutingData, payout_data: &mut PayoutData, eligible_connectors: Option<Vec<enums::RoutableConnectors>>, ) -> RouterResult<api::ConnectorCallType> { // 1. For existing attempts, use stored connector let payout_attempt = &payout_data.payout_attempt; if let Some(connector_name) = payout_attempt.connector.clone() { // Connector was already decided previously, use the same connector let connector_data = api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &connector_name, api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received in 'routed_through'")?; routing_data.routed_through = Some(connector_name.clone()); return Ok(api::ConnectorCallType::PreDetermined(connector_data.into())); } // Validate and get the business_profile from payout_attempt let business_profile = core_utils::validate_and_get_business_profile( state.store.as_ref(), &(state).into(), merchant_context.get_merchant_key_store(), Some(&payout_attempt.profile_id), merchant_context.get_merchant_account().get_id(), ) .await? .get_required_value("Profile")?; // 2. Check routing algorithm passed in the request if let Some(routing_algorithm) = request_straight_through { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(&routing_algorithm, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { connectors = routing::perform_eligibility_analysis_with_fallback( state, merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payout(payout_data), eligible_connectors, &business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; routing_data.routing_info.algorithm = Some(routing_algorithm); return Ok(api::ConnectorCallType::Retryable(connector_data)); } // 3. Check algorithm passed in routing data if let Some(ref routing_algorithm) = routing_data.algorithm { let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(routing_algorithm, None) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed execution of straight through routing")?; if check_eligibility { connectors = routing::perform_eligibility_analysis_with_fallback( state, merchant_context.get_merchant_key_store(), connectors, &TransactionData::Payout(payout_data), eligible_connectors, &business_profile, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed eligibility analysis and fallback")?; } let first_connector_choice = connectors .first() .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration) .attach_printable("Empty connector list returned")? .clone(); connectors.remove(0); let connector_data = connectors .into_iter() .map(|conn| { api::ConnectorData::get_payout_connector_by_name( &state.conf.connectors, &conn.connector.to_string(), api::GetToken::Connector, payout_attempt.merchant_connector_id.clone(), ) .map(|connector_data| connector_data.into()) }) .collect::<CustomResult<Vec<_>, _>>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid connector name received")?; routing_data.routed_through = Some(first_connector_choice.connector.to_string()); routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id; return Ok(api::ConnectorCallType::Retryable(connector_data)); } // 4. Route connector route_connector_v1_for_payouts( state, merchant_context, &payout_data.business_profile, payout_data, routing_data, eligible_connectors, ) .await } pub async fn get_default_payout_connector( _state: &SessionState, request_connector: Option<serde_json::Value>, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { Ok(request_connector.map_or( api::ConnectorChoice::Decide, api::ConnectorChoice::StraightThrough, )) } #[cfg(feature = "v1")] pub fn should_call_payout_connector_create_customer<'a>( state: &'a SessionState, connector: &'a api::ConnectorData, customer: &'a Option<domain::Customer>, connector_label: &'a str, ) -> (bool, Option<&'a str>) { // Check if create customer is required for the connector match enums::PayoutConnectors::try_from(connector.connector_name) { Ok(connector) => { let connector_needs_customer = state .conf .connector_customer .payout_connector_list .contains(&connector); if connector_needs_customer { let connector_customer_details = customer .as_ref() .and_then(|customer| customer.get_connector_customer_id(connector_label)); let should_call_connector = connector_customer_details.is_none(); (should_call_connector, connector_customer_details) } else { (false, None) } } _ => (false, None), } } #[cfg(feature = "v2")] pub fn should_call_payout_connector_create_customer<'a>( state: &'a SessionState, connector: &'a api::ConnectorData, customer: &'a Option<domain::Customer>, merchant_connector_id: &'a domain::MerchantConnectorAccountTypeDetails, ) -> (bool, Option<&'a str>) { // Check if create customer is required for the connector match enums::PayoutConnectors::try_from(connector.connector_name) { Ok(connector) => { let connector_needs_customer = state .conf .connector_customer .payout_connector_list .contains(&connector); if connector_needs_customer { let connector_customer_details = customer .as_ref() .and_then(|customer| customer.get_connector_customer_id(merchant_connector_id)); let should_call_connector = connector_customer_details.is_none(); (should_call_connector, connector_customer_details) } else { (false, None) } } _ => (false, None), } } pub async fn get_gsm_record( state: &SessionState, error_code: Option<String>, error_message: Option<String>, connector_name: Option<String>, flow: &str, ) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> { let connector_name = connector_name.unwrap_or_default(); let get_gsm = || async { state.store.find_gsm_rule( connector_name.clone(), flow.to_string(), "sub_flow".to_string(), error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response error_message.clone().unwrap_or_default(), ) .await .map_err(|err| { if err.current_context().is_db_not_found() { logger::warn!( "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", connector_name, flow, error_code, error_message ); metrics::AUTO_PAYOUT_RETRY_GSM_MISS_COUNT.add( 1, &[]); } else { metrics::AUTO_PAYOUT_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]); }; err.change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch decision from gsm") }) }; get_gsm() .await .inspect_err(|err| { // warn log should suffice here because we are not propagating this error logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision"); }) .ok() } pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool { !matches!( status, api_enums::PayoutStatus::RequiresCreation | api_enums::PayoutStatus::RequiresConfirmation | api_enums::PayoutStatus::RequiresPayoutMethodData | api_enums::PayoutStatus::RequiresVendorAccountCreation | api_enums::PayoutStatus::Initiated ) } pub(crate) fn validate_payout_status_against_not_allowed_statuses( payout_status: api_enums::PayoutStatus, not_allowed_statuses: &[api_enums::PayoutStatus], action: &'static str, ) -> Result<(), errors::ApiErrorResponse> { fp_utils::when(not_allowed_statuses.contains(&payout_status), || { Err(errors::ApiErrorResponse::PreconditionFailed { message: format!( "You cannot {action} this payout because it has status {payout_status}", ), }) }) } pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool { !matches!( status, api_enums::PayoutStatus::RequiresCreation | api_enums::PayoutStatus::RequiresConfirmation | api_enums::PayoutStatus::RequiresPayoutMethodData | api_enums::PayoutStatus::RequiresVendorAccountCreation // Initiated by the underlying connector | api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::Initiated | api_enums::PayoutStatus::RequiresFulfillment ) } pub fn should_call_retrieve(status: api_enums::PayoutStatus) -> bool { matches!( status, api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::Initiated ) } pub fn is_payout_err_state(status: api_enums::PayoutStatus) -> bool { matches!( status, api_enums::PayoutStatus::Cancelled | api_enums::PayoutStatus::Failed | api_enums::PayoutStatus::Ineligible ) } pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus) -> bool { matches!( status, api_enums::PayoutStatus::RequiresCreation | api_enums::PayoutStatus::RequiresConfirmation | api_enums::PayoutStatus::RequiresPayoutMethodData | api_enums::PayoutStatus::RequiresVendorAccountCreation ) } #[cfg(feature = "olap")] pub(super) async fn filter_by_constraints( db: &dyn StorageInterface, constraints: &api::PayoutListConstraints, merchant_id: &id_type::MerchantId, storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> { let result = db .filter_payouts_by_constraints(merchant_id, &constraints.clone().into(), storage_scheme) .await?; Ok(result) } #[cfg(feature = "v2")] pub async fn update_payouts_and_payout_attempt( _payout_data: &mut PayoutData, _merchant_context: &domain::MerchantContext, _req: &payouts::PayoutCreateRequest, _state: &SessionState, ) -> CustomResult<(), errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] pub async fn update_payouts_and_payout_attempt( payout_data: &mut PayoutData, merchant_context: &domain::MerchantContext, req: &payouts::PayoutCreateRequest, state: &SessionState, ) -> CustomResult<(), errors::ApiErrorResponse> { let payout_attempt = payout_data.payout_attempt.to_owned(); let status = payout_attempt.status; let payout_id = payout_attempt.payout_id.clone(); // Verify update feasibility if is_payout_terminal_state(status) || is_payout_initiated(status) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Payout {} cannot be updated for status {status}", payout_id.get_string_repr() ), })); } // Fetch customer details from request and create new or else use existing customer that was attached let customer = get_customer_details_from_request(req); let customer_id = if customer.customer_id.is_some() || customer.name.is_some() || customer.email.is_some() || customer.phone.is_some() || customer.phone_country_code.is_some() { payout_data.customer_details = get_or_create_customer_details(state, &customer, merchant_context).await?; payout_data .customer_details .as_ref() .map(|customer| customer.customer_id.clone()) } else { payout_data.payouts.customer_id.clone() }; let (billing_address, address_id) = resolve_billing_address_for_payout( state, req.billing.as_ref(), payout_data.payouts.address_id.as_ref(), payout_data.payment_method.as_ref(), merchant_context, customer_id.as_ref(), &payout_id, ) .await?; // Update payout state with resolved billing address payout_data.billing_address = billing_address; // Update DB with new data let payouts = payout_data.payouts.to_owned(); let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into())); let updated_payouts = storage::PayoutsUpdate::Update { amount, destination_currency: req .currency .to_owned() .unwrap_or(payouts.destination_currency), source_currency: req.currency.to_owned().unwrap_or(payouts.source_currency), description: req .description .to_owned() .clone() .or(payouts.description.clone()), recurring: req.recurring.to_owned().unwrap_or(payouts.recurring), auto_fulfill: req.auto_fulfill.to_owned().unwrap_or(payouts.auto_fulfill), return_url: req .return_url .to_owned() .clone() .or(payouts.return_url.clone()), entity_type: req.entity_type.to_owned().unwrap_or(payouts.entity_type), metadata: req.metadata.clone().or(payouts.metadata.clone()), status: Some(status), profile_id: Some(payout_attempt.profile_id.clone()), confirm: req.confirm.to_owned(), payout_type: req .payout_type .to_owned() .or(payouts.payout_type.to_owned()), address_id: address_id.clone(), customer_id: customer_id.clone(), }; let db = &*state.store; payout_data.payouts = db .update_payout( &payouts, updated_payouts, &payout_attempt, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts")?; let updated_business_country = payout_attempt .business_country .map_or(req.business_country.to_owned(), |c| { req.business_country .to_owned() .and_then(|nc| if nc != c { Some(nc) } else { None }) }); let updated_business_label = payout_attempt .business_label .map_or(req.business_label.to_owned(), |l| { req.business_label .to_owned() .and_then(|nl| if nl != l { Some(nl) } else { None }) }); if updated_business_country.is_some() || updated_business_label.is_some() || customer_id.is_some() || address_id.is_some() { let payout_attempt = &payout_data.payout_attempt; let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate { business_country: updated_business_country, business_label: updated_business_label, address_id, customer_id, }; payout_data.payout_attempt = db .update_payout_attempt( payout_attempt, updated_payout_attempt, &payout_data.payouts, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payout_attempt")?; } Ok(()) } pub(super) fn get_customer_details_from_request( request: &payouts::PayoutCreateRequest, ) -> CustomerDetails { let customer_id = request.get_customer_id().map(ToOwned::to_owned); let customer_name = request .customer .as_ref() .and_then(|customer_details| customer_details.name.clone()) .or(request.name.clone()); let customer_email = request .customer .as_ref() .and_then(|customer_details| customer_details.email.clone()) .or(request.email.clone()); let customer_phone = request .customer .as_ref() .and_then(|customer_details| customer_details.phone.clone()) .or(request.phone.clone()); let customer_phone_code = request .customer .as_ref() .and_then(|customer_details| customer_details.phone_country_code.clone()) .or(request.phone_country_code.clone()); let tax_registration_id = request .customer .as_ref() .and_then(|customer_details| customer_details.tax_registration_id.clone()); CustomerDetails { customer_id, name: customer_name, email: customer_email, phone: customer_phone, phone_country_code: customer_phone_code, tax_registration_id, } } pub async fn get_translated_unified_code_and_message( state: &SessionState, unified_code: Option<&UnifiedCode>, unified_message: Option<&UnifiedMessage>, locale: &str, ) -> CustomResult<Option<UnifiedMessage>, errors::ApiErrorResponse> { Ok(unified_code .zip(unified_message) .async_and_then(|(code, message)| async { payment_helpers::get_unified_translation( state, code.0.clone(), message.0.clone(), locale.to_string(), ) .await .map(UnifiedMessage::try_from) }) .await .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "unified_message", })? .or_else(|| unified_message.cloned())) } pub async fn get_additional_payout_data( pm_data: &api::PayoutMethodData, db: &dyn StorageInterface, profile_id: &id_type::ProfileId, ) -> Option<payout_additional::AdditionalPayoutMethodData> { match pm_data { api::PayoutMethodData::Card(card_data) => { let card_isin = Some(card_data.card_number.get_card_isin()); let enable_extended_bin =db .find_config_by_key_unwrap_or( format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(), Some("false".to_string())) .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok(); let card_extended_bin = match enable_extended_bin { Some(config) if config.config == "true" => { Some(card_data.card_number.get_extended_card_bin()) } _ => None, }; let last4 = Some(card_data.card_number.get_last4()); let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| services::logger::warn!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| { payout_additional::AdditionalPayoutMethodData::Card(Box::new( payout_additional::CardAdditionalData { card_issuer: card_info.card_issuer, card_network: card_info.card_network.clone(), bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.expiry_month.clone()), card_exp_year: Some(card_data.expiry_year.clone()), card_holder_name: card_data.card_holder_name.clone(), }, )) }); Some(card_info.unwrap_or_else(|| { payout_additional::AdditionalPayoutMethodData::Card(Box::new( payout_additional::CardAdditionalData { card_issuer: None, card_network: None, bank_code: None, card_type: None, card_issuing_country: None, last4, card_isin, card_extended_bin, card_exp_month: Some(card_data.expiry_month.clone()), card_exp_year: Some(card_data.expiry_year.clone()), card_holder_name: card_data.card_holder_name.clone(), }, )) })) } api::PayoutMethodData::Bank(bank_data) => { Some(payout_additional::AdditionalPayoutMethodData::Bank( Box::new(bank_data.to_owned().into()), )) } api::PayoutMethodData::Wallet(wallet_data) => { Some(payout_additional::AdditionalPayoutMethodData::Wallet( Box::new(wallet_data.to_owned().into()), )) } api::PayoutMethodData::BankRedirect(bank_redirect_data) => { Some(payout_additional::AdditionalPayoutMethodData::BankRedirect( Box::new(bank_redirect_data.to_owned().into()), )) } } } pub async fn resolve_billing_address_for_payout( state: &SessionState, req_billing: Option<&api_models::payments::Address>, existing_address_id: Option<&String>, payment_method: Option<&hyperswitch_domain_models::payment_methods::PaymentMethod>, merchant_context: &domain::MerchantContext, customer_id: Option<&id_type::CustomerId>, payout_id: &id_type::PayoutId, ) -> RouterResult<( Option<hyperswitch_domain_models::address::Address>, Option<String>, )> { let payout_id_as_payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned( payout_id.get_string_repr().to_string(), )) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data for PaymentId conversion".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; match (req_billing, existing_address_id, payment_method) { // Address in request (Some(_), _, _) => { let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, req_billing, None, merchant_context.get_merchant_account().get_id(), customer_id, merchant_context.get_merchant_key_store(), &payout_id_as_payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let address_id = billing_address.as_ref().map(|a| a.address_id.clone()); let hyperswitch_address = billing_address .map(|addr| hyperswitch_domain_models::address::Address::from(&addr)); Ok((hyperswitch_address, address_id)) } // Existing address using address_id (None, Some(address_id), _) => { let billing_address = payment_helpers::create_or_find_address_for_payment_by_request( state, None, Some(address_id), merchant_context.get_merchant_account().get_id(), customer_id, merchant_context.get_merchant_key_store(), &payout_id_as_payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let hyperswitch_address = billing_address .map(|addr| hyperswitch_domain_models::address::Address::from(&addr)); Ok((hyperswitch_address, Some(address_id.clone()))) } // Existing address in stored payment method (None, None, Some(pm)) => { pm.payment_method_billing_address.as_ref().map_or_else( || { logger::info!("No billing address found in payment method"); Ok((None, None)) }, |encrypted_billing_address| { logger::info!("Found encrypted billing address data in payment method"); #[cfg(feature = "v1")] { encrypted_billing_address .clone() .into_inner() .expose() .parse_value::<hyperswitch_domain_models::address::Address>( "payment_method_billing_address", ) .map(|domain_address| { logger::info!("Successfully parsed as hyperswitch_domain_models::address::Address"); (Some(domain_address), None) }) .map_err(|e| { logger::error!("Failed to parse billing address into (hyperswitch_domain_models::address::Address): {:?}", e); errors::ApiErrorResponse::InternalServerError }) .attach_printable("Failed to parse stored billing address") } #[cfg(feature = "v2")] { // TODO: Implement v2 logic when needed logger::warn!("v2 billing address resolution not yet implemented"); Ok((None, None)) } }, ) } (None, None, None) => Ok((None, None)), } } pub fn should_continue_payout<F: Clone + 'static>( router_data: &router_types::PayoutsRouterData<F>, ) -> bool { router_data.response.is_ok() }
{ "crate": "router", "file": "crates/router/src/core/payouts/helpers.rs", "file_size": 66311, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_4600464110749088139
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/refunds.rs // File size: 64558 bytes #[cfg(feature = "olap")] use std::collections::HashMap; #[cfg(feature = "olap")] use api_models::admin::MerchantConnectorInfo; use common_utils::{ ext_traits::{AsyncExt, StringExt}, types::{ConnectorTransactionId, MinorUnit}, }; use diesel_models::{process_tracker::business_status, refund as diesel_refund}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::ErrorResponse, router_request_types::SplitRefundsRequest, }; use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}; use router_env::{instrument, tracing}; use scheduler::{ consumer::types::process_data, errors as sch_errors, utils as process_tracker_utils, }; #[cfg(feature = "olap")] use strum::IntoEnumIterator; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}, payments::{self, access_token, helpers}, refunds::transformers::SplitRefundInput, utils::{ self as core_utils, refunds_transformers as transformers, refunds_validator as validator, }, }, db, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, refunds}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto}, }, utils::{self, OptionExt}, }; // ********************************************** REFUND EXECUTE ********************************************** #[instrument(skip_all)] pub async fn refund_create_core( state: SessionState, merchant_context: domain::MerchantContext, _profile_id: Option<common_utils::id_type::ProfileId>, req: refunds::RefundRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (merchant_id, payment_intent, payment_attempt, amount); merchant_id = merchant_context.get_merchant_account().get_id(); payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), &req.payment_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; utils::when( !(payment_intent.status == enums::IntentStatus::Succeeded || payment_intent.status == enums::IntentStatus::PartiallyCaptured), || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "refund".into(), field_name: "status".into(), current_value: payment_intent.status.to_string(), states: "succeeded, partially_captured".to_string() }) .attach_printable("unable to refund for a unsuccessful payment intent")) }, )?; // Amount is not passed in request refer from payment intent. amount = req .amount .or(payment_intent.amount_captured) .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("amount captured is none in a successful payment")?; //[#299]: Can we change the flow based on some workflow idea utils::when(amount <= MinorUnit::new(0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string() }) .attach_printable("amount less than or equal to zero")) })?; payment_attempt = db .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &req.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; let creds_identifier = req .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); req.merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await }) .await .transpose()?; Box::pin(validate_and_create_refund( &state, &merchant_context, &payment_attempt, &payment_intent, amount, req, creds_identifier, )) .await .map(services::ApplicationResponse::Json) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { let routed_through = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve connector from payment attempt")?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", routed_through.clone())), ); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &routed_through, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), )?; let currency = payment_attempt.currency.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError).attach_printable( "Transaction in invalid. Missing field \"currency\" in payment_attempt.", ) })?; validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let mut router_data = core_utils::construct_refund_router_data( state, &routed_through, merchant_context, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), )) .await?; logger::debug!(refund_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::Execute, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let router_data_res = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await; let option_refund_error_update = router_data_res .as_ref() .err() .and_then(|error| match error.current_context() { errors::ConnectorError::NotImplemented(message) => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some( errors::ConnectorError::NotImplemented(message.to_owned()) .to_string(), ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(format!( "{message} is not supported by {connector}" )), refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, }) } _ => None, }); // Update the refund status as failure if connector_error is NotImplemented if let Some(refund_error_update) = option_refund_error_update { state .store .update_refund( refund.to_owned(), refund_error_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; } let mut refund_router_data_res = router_data_res.to_refund_failed_response()?; // Initiating Integrity check let integrity_result = check_refund_integrity( &refund_router_data_res.request, &refund_router_data_res.response, ); refund_router_data_res.integrity_check = integrity_result; refund_router_data_res } else { router_data }; let refund_update = match router_data_res.response { Err(err) => { let option_gsm = helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::REFUND_FLOW_STR.to_string(), ) .await; // Note: Some connectors do not have a separate list of refund errors // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" let option_gsm = if option_gsm.is_none() { helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::AUTHORIZE_FLOW_STR.to_string(), ) .await } else { option_gsm }; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); let (unified_code, unified_message) = if let Some((code, message)) = gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { (code.to_owned(), message.to_owned()) } else { ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ) }; diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: err.reason.or(Some(err.message)), refund_error_code: Some(err.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), issuer_error_code: err.network_decline_code, issuer_error_message: err.network_error_message, } } Ok(response) => { // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { let (refund_connector_transaction_id, processor_refund_data) = err.connector_transaction_id.map_or((None, None), |txn_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(txn_id); (Some(refund_id), refund_data) }); metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { if response.refund_status == diesel_models::enums::RefundStatus::Success { metrics::SUCCESSFUL_REFUND.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string(), )), ) } let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); diesel_refund::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } } } }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_context, &response, payment_attempt.profile_id.clone(), ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } pub fn check_refund_integrity<T, Request>( request: &Request, refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_refund_id = refund_response_data .as_ref() .map(|resp_data| resp_data.connector_refund_id.clone()) .ok(); request.check_integrity(request, connector_refund_id.to_owned()) } // ********************************************** REFUND SYNC ********************************************** pub async fn refund_response_wrapper<F, Fut, T, Req>( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: Req, f: F, ) -> RouterResponse<refunds::RefundResponse> where F: Fn( SessionState, domain::MerchantContext, Option<common_utils::id_type::ProfileId>, Req, ) -> Fut, Fut: futures::Future<Output = RouterResult<T>>, T: ForeignInto<refunds::RefundResponse>, { Ok(services::ApplicationResponse::Json( f(state, merchant_context, profile_id, request) .await? .foreign_into(), )) } #[instrument(skip_all)] pub async fn refund_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, refund: diesel_refund::Refund, ) -> RouterResult<diesel_refund::Refund> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; let payment_id = &refund.payment_id; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(&state).into(), payment_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await }) .await .transpose()?; let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( &state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { Box::pin(sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, creds_identifier, split_refunds_req, )) .await } else { Ok(refund) }?; Ok(response) } fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { // This implies, we cannot perform a refund sync & `the connector_refund_id` // doesn't exist let predicate1 = refund.connector_refund_id.is_some(); // This allows refund sync at connector level if force_sync is enabled, or // checks if the refund has failed let predicate2 = force_sync || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2 } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { let connector_id = refund.connector.to_string(); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_id, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let currency = payment_attempt.currency.get_required_value("currency")?; let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, &connector_id, merchant_context, (payment_attempt.get_total_amount(), currency), payment_intent, payment_attempt, refund, creds_identifier.clone(), split_refunds, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, creds_identifier.as_deref(), )) .await?; logger::debug!(refund_retrieve_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let router_data_res = if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< api::RSync, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); let mut refund_sync_router_data = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .to_refund_failed_response()?; // Initiating connector integrity checks let integrity_result = check_refund_integrity( &refund_sync_router_data.request, &refund_sync_router_data.response, ); refund_sync_router_data.integrity_check = integrity_result; refund_sync_router_data } else { router_data }; let refund_update = match router_data_res.response { Err(error_message) => { let refund_status = match error_message.status_code { // marking failure for 2xx because this is genuine refund failure 200..=299 => Some(enums::RefundStatus::Failure), _ => None, }; diesel_refund::RefundUpdate::ErrorUpdate { refund_status, refund_error_message: error_message.reason.or(Some(error_message.message)), refund_error_code: Some(error_message.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, issuer_error_code: error_message.network_decline_code, issuer_error_message: error_message.network_error_message, } } Ok(response) => match router_data_res.integrity_check.clone() { Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); let (refund_connector_transaction_id, processor_refund_data) = err .connector_transaction_id .map_or((None, None), |refund_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(refund_id); (Some(refund_id), refund_data) }); diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( "Integrity Check Failed! as data mismatched for fields {}", err.field_names )), refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, processor_refund_data, unified_code: None, unified_message: None, issuer_error_code: None, issuer_error_message: None, } } Ok(()) => { let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); diesel_refund::RefundUpdate::Update { connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), processor_refund_data, } } }, }; let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.refund_id ) })?; utils::trigger_refund_outgoing_webhook( state, merchant_context, &response, payment_attempt.profile_id.clone(), ) .await .map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error)) .ok(); Ok(response) } // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_update_core( state: SessionState, merchant_context: domain::MerchantContext, req: refunds::RefundUpdateRequest, ) -> RouterResponse<refunds::RefundResponse> { let db = state.store.as_ref(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &req.refund_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = db .update_refund( refund, diesel_refund::RefundUpdate::MetadataAndReasonUpdate { metadata: req.metadata, reason: req.reason, updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), }, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!("Unable to update refund with refund_id: {}", req.refund_id) })?; Ok(services::ApplicationResponse::Json(response.foreign_into())) } // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn validate_and_create_refund( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund_amount: MinorUnit, req: refunds::RefundRequest, creds_identifier: Option<String>, ) -> RouterResult<refunds::RefundResponse> { let db = &*state.store; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: req.split_refunds.clone(), })?; // Only for initial dev and testing let refund_type = req.refund_type.unwrap_or_default(); // If Refund Id not passed in request Generate one. let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?; let predicate = req .merchant_id .as_ref() .map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id()); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string() }) .attach_printable("invalid merchant_id in request")) })?; let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; let all_refunds = db .find_refund_by_merchant_id_connector_transaction_id( merchant_context.get_merchant_account().get_id(), &connector_transaction_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let currency = payment_attempt.currency.get_required_value("currency")?; //[#249]: Add Connector Based Validation here. validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "created_at".to_string(), expected_format: format!( "created_at not older than {} days", state.conf.refund.max_age, ), })?; let total_amount_captured = payment_intent .amount_captured .unwrap_or(payment_attempt.get_total_amount()); validator::validate_refund_amount( total_amount_captured.get_amount_as_i64(), &all_refunds, refund_amount.get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; validator::validate_maximum_refund_against_payment_attempt( &all_refunds, state.conf.refund.max_attempts, ) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = diesel_refund::RefundNew { refund_id: refund_id.to_string(), internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"), external_reference_id: Some(refund_id.clone()), payment_id: req.payment_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector_transaction_id, connector, refund_type: req.refund_type.unwrap_or_default().foreign_into(), total_amount: payment_attempt.get_total_amount(), refund_amount, currency, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), refund_status: enums::RefundStatus::Pending, metadata: req.metadata, description: req.reason.clone(), attempt_id: payment_attempt.attempt_id.clone(), refund_reason: req.reason, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: req.split_refunds, connector_refund_id: None, sent_to_gateway: Default::default(), refund_arn: None, updated_by: Default::default(), organization_id: merchant_context .get_merchant_account() .organization_id .clone(), processor_transaction_data, processor_refund_data: None, }; let refund = match db .insert_refund( refund_create_req, merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(refund) => { Box::pin(schedule_refund_execution( state, refund.clone(), refund_type, merchant_context, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await? } Err(err) => { if err.current_context().is_db_unique_violation() { Err(errors::ApiErrorResponse::DuplicateRefundRequest)? } else { return Err(err) .change_context(errors::ApiErrorResponse::RefundNotFound) .attach_printable("Inserting Refund failed"); } } }; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; Ok(refund.foreign_into()) } // ********************************************** Refund list ********************************************** /// If payment-id is provided, lists all the refunds associated with that particular payment-id /// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, req: api_models::refunds::RefundListRequest, ) -> RouterResponse<api_models::refunds::RefundListResponse> { let db = state.store; let limit = validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); let refund_list = db .filter_refund_by_constraints( merchant_context.get_merchant_account().get_id(), &(req.clone(), profile_id_list.clone()).try_into()?, merchant_context.get_merchant_account().storage_scheme, limit, offset, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let data: Vec<refunds::RefundResponse> = refund_list .into_iter() .map(ForeignInto::foreign_into) .collect(); let total_count = db .get_total_count_of_refunds( merchant_context.get_merchant_account().get_id(), &(req, profile_id_list).try_into()?, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { count: data.len(), total_count, data, }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_filter_list( state: SessionState, merchant_context: domain::MerchantContext, req: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundListMetaData> { let db = state.store; let filter_list = db .filter_refund_by_meta_constraints( merchant_context.get_merchant_account().get_id(), &req, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Ok(services::ApplicationResponse::Json(filter_list)) } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_internal_reference_id( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, refund_internal_request_id: String, force_sync: Option<bool>, ) -> RouterResult<diesel_refund::Refund> { let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_internal_request_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let request = refunds::RefundsRetrieveRequest { refund_id: refund.refund_id.clone(), force_sync, merchant_connector_details: None, }; Box::pin(refund_retrieve_core( state.clone(), merchant_context, profile_id, request, refund, )) .await } #[instrument(skip_all)] pub async fn refund_retrieve_core_with_refund_id( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, ) -> RouterResult<diesel_refund::Refund> { let refund_id = request.refund_id.clone(); let db = &*state.store; let merchant_id = merchant_context.get_merchant_account().get_id(); let refund = db .find_refund_by_merchant_id_refund_id( merchant_id, refund_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; Box::pin(refund_retrieve_core( state.clone(), merchant_context, profile_id, request, refund, )) .await } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_manual_update( state: SessionState, req: api_models::refunds::RefundManualUpdateRequest, ) -> RouterResponse<serde_json::Value> { let key_manager_state = &(&state).into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &req.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) .attach_printable("Error while fetching the merchant_account by merchant_id")?; let refund = state .store .find_refund_by_merchant_id_refund_id( merchant_account.get_id(), &req.refund_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let refund_update = diesel_refund::RefundUpdate::ManualUpdate { refund_status: req.status.map(common_enums::RefundStatus::from), refund_error_message: req.error_message, refund_error_code: req.error_code, updated_by: merchant_account.storage_scheme.to_string(), }; state .store .update_refund( refund.to_owned(), refund_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.refund_id ) })?; Ok(services::ApplicationResponse::StatusOk) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_filters_for_refunds( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, ) -> RouterResponse<api_models::refunds::RefundListFilters> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = super::admin::list_payment_connectors( state, merchant_context.get_merchant_account().get_id().to_owned(), profile_id_list, ) .await? { data } else { return Err(errors::ApiErrorResponse::InternalServerError.into()); }; let connector_map = merchant_connector_accounts .into_iter() .filter_map(|merchant_connector_account| { merchant_connector_account .connector_label .clone() .map(|label| { let info = merchant_connector_account.to_merchant_connector_info(&label); (merchant_connector_account.connector_name, info) }) }) .fold( HashMap::new(), |mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| { map.entry(connector_name).or_default().push(info); map }, ); Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListFilters { connector: connector_map, currency: enums::Currency::iter().collect(), refund_status: enums::RefundStatus::iter().collect(), }, )) } #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn get_aggregates_for_refunds( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { let db = state.store.as_ref(); let refund_status_with_count = db .get_refund_status_with_count( merchant_context.get_merchant_account().get_id(), profile_id_list, &time_range, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find status count")?; let mut status_map: HashMap<enums::RefundStatus, i64> = refund_status_with_count.into_iter().collect(); for status in enums::RefundStatus::iter() { status_map.entry(status).or_default(); } Ok(services::ApplicationResponse::Json( api_models::refunds::RefundAggregateResponse { status_with_count: status_map, }, )) } impl ForeignFrom<diesel_refund::Refund> for api::RefundResponse { fn foreign_from(refund: diesel_refund::Refund) -> Self { let refund = refund; Self { payment_id: refund.payment_id, refund_id: refund.refund_id, amount: refund.refund_amount, currency: refund.currency.to_string(), reason: refund.refund_reason, status: refund.refund_status.foreign_into(), profile_id: refund.profile_id, metadata: refund.metadata, error_message: refund.refund_error_message, error_code: refund.refund_error_code, created_at: Some(refund.created_at), updated_at: Some(refund.modified_at), connector: refund.connector, merchant_connector_id: refund.merchant_connector_id, split_refunds: refund.split_refunds, unified_code: refund.unified_code, unified_message: refund.unified_message, issuer_error_code: refund.issuer_error_code, issuer_error_message: refund.issuer_error_message, } } } // ********************************************** PROCESS TRACKER ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn schedule_refund_execution( state: &SessionState, refund: diesel_refund::Refund, refund_type: api_models::refunds::RefundType, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, creds_identifier: Option<String>, split_refunds: Option<SplitRefundsRequest>, ) -> RouterResult<diesel_refund::Refund> { // refunds::RefundResponse> { let db = &*state.store; let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let refund_process = db .find_process_by_id(&task_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the process id")?; let result = match refund.refund_status { enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { match (refund.sent_to_gateway, refund_process) { (false, None) => { // Execute the refund task based on refund_type match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_execute_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { let update_refund = Box::pin(trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, creds_identifier, split_refunds, )) .await; match update_refund { Ok(updated_refund_data) => { add_refund_sync_task(db, &updated_refund_data, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!( "Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id ))?; Ok(updated_refund_data) } Err(err) => Err(err), } } } } _ => { // Sync the refund for status check //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?; Ok(refund) } api_models::refunds::RefundType::Instant => { // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled // sync_refund_with_gateway(data, &refund).await Ok(refund) } } } } } // [#255]: This is not allowed to be otherwise or all _ => Ok(refund), }?; Ok(result) } #[instrument(skip_all)] pub async fn sync_refund_with_gateway_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let key_manager_state = &state.into(); let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>( refund_tracker.tracking_data.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let response = Box::pin(refund_retrieve_core_with_internal_reference_id( state.clone(), merchant_context, None, refund_core.refund_internal_reference_id, Some(true), )) .await?; let terminal_status = [ enums::RefundStatus::Success, enums::RefundStatus::Failure, enums::RefundStatus::TransactionFailure, ]; match response.refund_status { status if terminal_status.contains(&status) => { state .store .as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await? } _ => { _ = retry_refund_sync_task( &*state.store, response.connector, response.merchant_id, refund_tracker.to_owned(), ) .await?; } } Ok(()) } /// Schedule the task for refund retry /// /// Returns bool which indicates whether this was the last refund retry or not pub async fn retry_refund_sync_task( db: &dyn db::StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1) .await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } } #[instrument(skip_all)] pub async fn start_refund_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { match refund_tracker.name.as_deref() { Some("EXECUTE_REFUND") => { Box::pin(trigger_refund_execute_workflow(state, refund_tracker)).await } Some("SYNC_REFUND") => { Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await } _ => Err(errors::ProcessTrackerError::JobNotFound), } } #[instrument(skip_all)] pub async fn trigger_refund_execute_workflow( state: &SessionState, refund_tracker: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>( refund_tracker.tracking_data.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "unable to convert into refund_core {:?}", refund_tracker.tracking_data ) })?; let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &refund_core.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund_core.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let refund = db .find_refund_by_internal_reference_id_merchant_id( &refund_core.refund_internal_reference_id, &refund_core.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; match (&refund.sent_to_gateway, &refund.refund_status) { (false, enums::RefundStatus::Pending) => { let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &refund.merchant_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &refund.connector_transaction_id, &refund_core.payment_id, &refund.merchant_id, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &(state.into()), &payment_attempt.payment_id, &refund.merchant_id, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let split_refunds = core_utils::get_split_refunds(SplitRefundInput { split_payment_request: payment_intent.split_payments.clone(), payment_charges: payment_attempt.charges.clone(), charge_id: payment_attempt.charge_id.clone(), refund_request: refund.split_refunds.clone(), })?; //trigger refund request to gateway let updated_refund = Box::pin(trigger_refund_to_gateway( state, &refund, &merchant_context, &payment_attempt, &payment_intent, None, split_refunds, )) .await?; add_refund_sync_task( db, &updated_refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (true, enums::RefundStatus::Pending) => { // create sync task add_refund_sync_task( db, &refund, storage::ProcessTrackerRunner::RefundWorkflowRouter, ) .await?; } (_, _) => { //mark task as finished db.as_scheduler() .finish_process_with_business_status( refund_tracker.clone(), business_status::COMPLETED_BY_PT, ) .await?; } }; Ok(()) } #[instrument] pub fn refund_to_refund_core_workflow_model( refund: &diesel_refund::Refund, ) -> diesel_refund::RefundCoreWorkflow { diesel_refund::RefundCoreWorkflow { refund_internal_reference_id: refund.internal_reference_id.clone(), connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), processor_transaction_data: refund.processor_transaction_data.clone(), } } #[instrument(skip_all)] pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let schedule_time = get_refund_sync_process_schedule_time(db, &refund.connector, &refund.merchant_id, 0) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch schedule time for refund sync process")? .unwrap_or_else(common_utils::date_time::now); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); Ok(response) } #[instrument(skip_all)] pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id); let tag = ["REFUND"]; let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.refund_id ) })?; Ok(response) } pub async fn get_refund_sync_process_schedule_time( db: &dyn db::StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_refund_sync_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(err) => { logger::error!("Error: while getting connector mapping: {err:?}"); process_data::ConnectorPTMapping::default() } }; let time_delta = process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(process_tracker_utils::get_time_from_delta(time_delta)) }
{ "crate": "router", "file": "crates/router/src/core/refunds.rs", "file_size": 64558, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-6957101065590432410
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/revenue_recovery/types.rs // File size: 63165 bytes use std::{marker::PhantomData, str::FromStr}; use api_models::{ enums as api_enums, payments::{ AmountDetails, PaymentRevenueRecoveryMetadata, PaymentsUpdateIntentRequest, ProxyPaymentsRequest, }, }; use common_utils::{ self, ext_traits::{OptionExt, ValueExt}, id_type, }; use diesel_models::{ enums, payment_intent, process_tracker::business_status, types as diesel_types, }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ api::ApplicationResponse, business_profile, merchant_connector_account, merchant_context::{Context, MerchantContext}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData, PaymentIntent, PaymentIntentData, PaymentStatusData, }, router_data_v2::{self, flow_common_types}, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, ApiModelToDieselModelConvertor, }; use time::PrimitiveDateTime; use super::errors::StorageErrorExt; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, helpers, operations::Operation, transformers::GenerateResponse}, revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow}, webhooks::{ create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow, }, }, db::StorageInterface, logger, routes::SessionState, services::{self, connector_integration_interface::RouterDataConversion}, types::{ self, api as api_types, api::payments as payments_types, domain, storage, transformers::ForeignInto, }, workflows::{ payment_sync, revenue_recovery::{self, get_schedule_time_to_retry_mit_payments}, }, }; type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>; pub const REVENUE_RECOVERY: &str = "revenue_recovery"; /// The status of Passive Churn Payments #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum RevenueRecoveryPaymentsAttemptStatus { Succeeded, Failed, Processing, InvalidStatus(String), // Cancelled, } impl RevenueRecoveryPaymentsAttemptStatus { pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment( &self, db: &dyn StorageInterface, execute_task_process: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering update_pt_status_based_on_attempt_status_for_execute_payment"); match &self { Self::Succeeded | Self::Failed | Self::Processing => { // finish the current execute task db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await?; } Self::InvalidStatus(action) => { logger::debug!( "Invalid Attempt Status for the Recovery Payment : {}", action ); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.update_process(execute_task_process.clone(), pt_update) .await?; } }; Ok(()) } #[allow(clippy::too_many_arguments)] pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync( &self, state: &SessionState, payment_intent: &PaymentIntent, process_tracker: storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: PaymentAttempt, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let db = &*state.store; let recovery_payment_intent = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( payment_intent, ); let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt); let retry_count = process_tracker.retry_count; let psync_response = revenue_recovery_payment_data .psync_data .as_ref() .ok_or(errors::RecoveryError::ValueNotFound) .attach_printable("Psync data not found in revenue recovery payment data")?; match self { Self::Succeeded => { // finish psync task as the payment was a success db.as_scheduler() .finish_process_with_business_status( process_tracker, business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; let event_status = common_enums::EventType::PaymentSucceeded; // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, // Since this is succeeded payment attempt, 'is_hard_decine' will be false. &Some(false), used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; let payments_response = psync_response .clone() .generate_response(state, None, None, None, &merchant_context, profile, None) .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed) .attach_printable("Failed while generating response for payment")?; RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_status, payment_intent, &merchant_context, profile, recovery_payment_attempt .attempt_id .get_string_repr() .to_string(), payments_response ) .await?; // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, &payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; } Self::Failed => { // finish psync task db.as_scheduler() .finish_process_with_business_status( process_tracker.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka : {:?}", e ); }; let error_code = recovery_payment_attempt.error_code; let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) .await .ok(); // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, &process_tracker, profile, merchant_context, payment_intent, revenue_recovery_payment_data, psync_response.payment_attempt.get_id(), )) .await?; } Self::Processing => { // do a psync payment let action = Box::pin(Action::payment_sync_call( state, revenue_recovery_payment_data, payment_intent, &process_tracker, profile, merchant_context, payment_attempt, )) .await?; //handle the response Box::pin(action.psync_response_handler( state, payment_intent, &process_tracker, revenue_recovery_metadata, revenue_recovery_payment_data, )) .await?; } Self::InvalidStatus(status) => logger::debug!( "Invalid Attempt Status for the Recovery Payment : {}", status ), } Ok(()) } } pub enum Decision { Execute, Psync(enums::AttemptStatus, id_type::GlobalAttemptId), InvalidDecision, ReviewForSuccessfulPayment, ReviewForFailedPayment(enums::TriggeredBy), } impl Decision { pub async fn get_decision_based_on_params( state: &SessionState, intent_status: enums::IntentStatus, called_connector: enums::PaymentConnectorTransmission, active_attempt_id: Option<id_type::GlobalAttemptId>, revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_id: &id_type::GlobalPaymentId, ) -> RecoveryResult<Self> { logger::info!("Entering get_decision_based_on_params"); Ok(match (intent_status, called_connector, active_attempt_id) { ( enums::IntentStatus::Failed, enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, None, ) => Self::Execute, ( enums::IntentStatus::Processing, enums::PaymentConnectorTransmission::ConnectorCallSucceeded, Some(_), ) => { let psync_data = revenue_recovery_core::api::call_psync_api( state, payment_id, revenue_recovery_data, true, true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = psync_data.payment_attempt; Self::Psync(payment_attempt.status, payment_attempt.get_id().clone()) } ( enums::IntentStatus::Failed, enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, Some(_), ) => { let psync_data = revenue_recovery_core::api::call_psync_api( state, payment_id, revenue_recovery_data, true, true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = psync_data.payment_attempt; let attempt_triggered_by = payment_attempt .feature_metadata .and_then(|metadata| { metadata.revenue_recovery.map(|revenue_recovery_metadata| { revenue_recovery_metadata.attempt_triggered_by }) }) .get_required_value("Attempt Triggered By") .change_context(errors::RecoveryError::ValueNotFound)?; Self::ReviewForFailedPayment(attempt_triggered_by) } (enums::IntentStatus::Succeeded, _, _) => Self::ReviewForSuccessfulPayment, _ => Self::InvalidDecision, }) } } #[derive(Debug, Clone)] pub enum Action { SyncPayment(PaymentAttempt), RetryPayment(PrimitiveDateTime), TerminalFailure(PaymentAttempt), SuccessfulPayment(PaymentAttempt), ReviewPayment, ManualReviewAction, } impl Action { #[allow(clippy::too_many_arguments)] pub async fn execute_payment( state: &SessionState, _merchant_id: &id_type::MerchantId, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata, latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<Self> { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to deserialize the tracking data from process tracker")?; let last_token_used = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .payment_processor_token .clone() }); let recovery_algorithm = tracking_data.revenue_recovery_retry; let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type( state, &connector_customer_id, recovery_algorithm, last_token_used.as_deref(), ) .await { Ok(scheduled_token_opt) => scheduled_token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get PSP token status" ); None } }; match scheduled_token { Some(scheduled_token) => { let response = revenue_recovery_core::api::call_proxy_api( state, payment_intent, revenue_recovery_payment_data, revenue_recovery_metadata, &scheduled_token .payment_processor_token_details .payment_processor_token, ) .await; let recovery_payment_intent = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( payment_intent, ); // handle proxy api's response match response { Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_data.payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(process.retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; let is_hard_decline = revenue_recovery::check_hard_decline( state, &payment_data.payment_attempt, ) .await .ok(); // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, &is_hard_decline, Some(&scheduled_token.payment_processor_token_details.payment_processor_token), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; let event_status = common_enums::EventType::PaymentSucceeded; let payments_response = payment_data .clone() .generate_response( state, None, None, None, &merchant_context, profile, None, ) .change_context( errors::RecoveryError::PaymentsResponseGenerationFailed, ) .attach_printable("Failed while generating response for payment")?; RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_status, payment_intent, &merchant_context, profile, payment_data.payment_attempt.id.get_string_repr().to_string(), payments_response ) .await?; Ok(Self::SuccessfulPayment( payment_data.payment_attempt.clone(), )) } RevenueRecoveryPaymentsAttemptStatus::Failed => { let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_data.payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(process.retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; let error_code = payment_data .payment_attempt .clone() .error .map(|error| error.code); let is_hard_decline = revenue_recovery::check_hard_decline( state, &payment_data.payment_attempt, ) .await .ok(); let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, Some(&scheduled_token .payment_processor_token_details .payment_processor_token) , ) .await; // unlocking the token let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, latest_attempt_id, )) .await?; // Return terminal failure to finish the current execute workflow Ok(Self::TerminalFailure(payment_data.payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::Processing => { Ok(Self::SyncPayment(payment_data.payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => { logger::info!(?action, "Invalid Payment Status For PCR Payment"); Ok(Self::ManualReviewAction) } }, Err(err) => // check for an active attempt being constructed or not { logger::error!(execute_payment_res=?err); Ok(Self::ReviewPayment) } } } None => { let response = revenue_recovery_core::api::call_psync_api( state, payment_intent.get_id(), revenue_recovery_payment_data, true, true, ) .await; let payment_status_data = response .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = payment_status_data.payment_attempt; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token available, finishing CALCULATE_WORKFLOW" ); state .store .as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_FINISH, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to finish CALCULATE_WORKFLOW")?; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW finished successfully" ); Ok(Self::TerminalFailure(payment_attempt.clone())) } } } pub async fn execute_payment_task_response_handler( &self, state: &SessionState, payment_intent: &PaymentIntent, execute_task_process: &storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering execute_payment_task_response_handler"); let db = &*state.store; match self { Self::SyncPayment(payment_attempt) => { revenue_recovery_core::insert_psync_pcr_task_to_pt( revenue_recovery_payment_data.billing_mca.get_id().clone(), db, revenue_recovery_payment_data .merchant_account .get_id() .to_owned(), payment_intent.id.clone(), revenue_recovery_payment_data.profile.get_id().to_owned(), payment_attempt.id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, revenue_recovery_payment_data.retry_algorithm, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to create a psync workflow in the process tracker")?; db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::RetryPayment(schedule_time) => { db.as_scheduler() .retry_process(execute_task_process.clone(), *schedule_time) .await?; // update the connector payment transmission field to Unsuccessful and unset active attempt id revenue_recovery_metadata.set_payment_transmission_field_for_api_request( enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, ); let payment_update_req = PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( payment_intent .feature_metadata .clone() .unwrap_or_default() .convert_back() .set_payment_revenue_recovery_metadata_using_api( revenue_recovery_metadata.clone(), ), api_enums::UpdateActiveAttempt::Unset, ); logger::info!( "Call made to payments update intent api , with the request body {:?}", payment_update_req ); revenue_recovery_core::api::update_payment_intent_api( state, payment_intent.id.clone(), revenue_recovery_payment_data, payment_update_req, ) .await .change_context(errors::RecoveryError::PaymentCallFailed)?; Ok(()) } Self::TerminalFailure(payment_attempt) => { db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_FAILURE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // TODO: Add support for retrying failed outgoing recordback webhooks Ok(()) } Self::SuccessfulPayment(payment_attempt) => { db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // Record back to billing connector for terminal status // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::ReviewPayment => { // requeue the process tracker in case of error response let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; Ok(()) } Self::ManualReviewAction => { logger::debug!("Invalid Payment Status For PCR Payment"); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; Ok(()) } } } pub async fn payment_sync_call( state: &SessionState, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, payment_attempt: PaymentAttempt, ) -> RecoveryResult<Self> { logger::info!("Entering payment_sync_call"); let response = revenue_recovery_core::api::call_psync_api( state, payment_intent.get_id(), revenue_recovery_payment_data, true, true, ) .await; let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt); match response { Ok(_payment_data) => match payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, // Since this is succeeded, 'hard_decine' will be false. &Some(false), used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; Ok(Self::SuccessfulPayment(payment_attempt)) } RevenueRecoveryPaymentsAttemptStatus::Failed => { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let error_code = payment_attempt.clone().error.map(|error| error.code); let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) .await .ok(); let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, used_token.as_deref(), ) .await; // unlocking the token let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, payment_attempt.get_id(), )) .await?; Ok(Self::TerminalFailure(payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::Processing => { Ok(Self::SyncPayment(payment_attempt)) } RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => { logger::info!(?action, "Invalid Payment Status For PCR PSync Payment"); Ok(Self::ManualReviewAction) } }, Err(err) => // if there is an error while psync we create a new Review Task { logger::error!(sync_payment_response=?err); Ok(Self::ReviewPayment) } } } pub async fn psync_response_handler( &self, state: &SessionState, payment_intent: &PaymentIntent, psync_task_process: &storage::ProcessTracker, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering psync_response_handler"); let db = &*state.store; let connector_customer_id = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .connector_customer_id .clone() }); match self { Self::SyncPayment(payment_attempt) => { // get a schedule time for psync // and retry the process if there is a schedule time // if None mark the pt status as Retries Exceeded and finish the task payment_sync::recovery_retry_sync_task( state, connector_customer_id, revenue_recovery_metadata.connector.to_string(), revenue_recovery_payment_data .merchant_account .get_id() .clone(), psync_task_process.clone(), ) .await?; Ok(()) } Self::RetryPayment(schedule_time) => { // finish the psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // fetch the execute task let task = revenue_recovery_core::EXECUTE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = payment_intent .get_id() .get_execute_revenue_recovery_id(task, runner); let execute_task_process = db .as_scheduler() .find_process_by_id(&process_tracker_id) .await .change_context(errors::RecoveryError::ProcessTrackerFailure)? .get_required_value("Process Tracker")?; // retry the execute tasks db.as_scheduler() .retry_process(execute_task_process, *schedule_time) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::TerminalFailure(payment_attempt) => { // TODO: Add support for retrying failed outgoing recordback webhooks // finish the current psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::SuccessfulPayment(payment_attempt) => { // finish the current psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::ReviewPayment => { // requeue the process tracker task in case of psync api error let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from(business_status::PSYNC_WORKFLOW_REQUEUE)), }; db.as_scheduler() .update_process(psync_task_process.clone(), pt_update) .await?; Ok(()) } Self::ManualReviewAction => { logger::debug!("Invalid Payment Status For PCR Payment"); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::PSYNC_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.as_scheduler() .update_process(psync_task_process.clone(), pt_update) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } } } pub(crate) async fn decide_retry_failure_action( state: &SessionState, merchant_id: &id_type::MerchantId, pt: storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<Self> { let db = &*state.store; let next_retry_count = pt.retry_count + 1; let error_message = payment_attempt .error .as_ref() .map(|details| details.message.clone()); let error_code = payment_attempt .error .as_ref() .map(|details| details.code.clone()); let connector_name = payment_attempt .connector .clone() .ok_or(errors::RecoveryError::ValueNotFound) .attach_printable("unable to derive payment connector from payment attempt")?; let gsm_record = helpers::get_gsm_record( state, error_code, error_message, connector_name, REVENUE_RECOVERY.to_string(), ) .await; let is_hard_decline = gsm_record .and_then(|gsm_record| gsm_record.error_category) .map(|gsm_error_category| { gsm_error_category == common_enums::ErrorCategory::HardDecline }) .unwrap_or(false); let schedule_time = revenue_recovery_payment_data .get_schedule_time_based_on_retry_type( state, merchant_id, next_retry_count, payment_attempt, payment_intent, is_hard_decline, ) .await; match schedule_time { Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)), None => Ok(Self::TerminalFailure(payment_attempt.clone())), } } } /// Reopen calculate workflow when payment fails pub async fn reopen_calculate_workflow_on_payment_failure( state: &SessionState, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, payment_intent: &PaymentIntent, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<()> { let db = &*state.store; let id = payment_intent.id.clone(); let task = revenue_recovery_core::CALCULATE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to deserialize the tracking data from process tracker")?; let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { payment_attempt_id: latest_attempt_id.clone(), ..old_tracking_data }; let tracking_data = serde_json::to_value(new_tracking_data) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to serialize the tracking data for process tracker")?; // Construct the process tracker ID for CALCULATE_WORKFLOW let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr()); logger::info!( payment_id = %id.get_string_repr(), process_tracker_id = %process_tracker_id, "Attempting to reopen CALCULATE_WORKFLOW on payment failure" ); // Find the existing CALCULATE_WORKFLOW process tracker let calculate_process = db .find_process_by_id(&process_tracker_id) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?; match calculate_process { Some(process) => { logger::info!( payment_id = %id.get_string_repr(), process_tracker_id = %process_tracker_id, current_status = %process.business_status, current_retry_count = process.retry_count, "Found existing CALCULATE_WORKFLOW, updating status and retry count" ); // Update the process tracker to reopen the calculate workflow // 1. Change status from "finish" to "pending" // 2. Increase retry count by 1 // 3. Set business status to QUEUED // 4. Schedule for immediate execution let new_retry_count = process.retry_count + 1; let new_schedule_time = common_utils::date_time::now() + time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .reopen_workflow_buffer_time_in_seconds, ); let pt_update = storage::ProcessTrackerUpdate::Update { name: Some(task.to_string()), retry_count: Some(new_retry_count), schedule_time: Some(new_schedule_time), tracking_data: Some(tracking_data), business_status: Some(String::from(business_status::PENDING)), status: Some(common_enums::ProcessTrackerStatus::Pending), updated_at: Some(common_utils::date_time::now()), }; db.update_process(process.clone(), pt_update) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update CALCULATE_WORKFLOW process tracker")?; logger::info!( payment_id = %id.get_string_repr(), process_tracker_id = %process_tracker_id, new_retry_count = new_retry_count, new_schedule_time = %new_schedule_time, "Successfully reopened CALCULATE_WORKFLOW with increased retry count" ); } None => { logger::info!( payment_id = %id.get_string_repr(), process_tracker_id = %process_tracker_id, "CALCULATE_WORKFLOW process tracker not found, creating new entry" ); let task = "CALCULATE_WORKFLOW"; let db = &*state.store; // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id} let process_tracker_id = format!("{runner}_{task}_{}", id.get_string_repr()); // Set scheduled time to current time + buffer time set in configuration let schedule_time = common_utils::date_time::now() + time::Duration::seconds( state .conf .revenue_recovery .recovery_timestamp .reopen_workflow_buffer_time_in_seconds, ); let new_retry_count = process.retry_count + 1; // Check if a process tracker entry already exists for this payment intent let existing_entry = db .as_scheduler() .find_process_by_id(&process_tracker_id) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable( "Failed to check for existing calculate workflow process tracker entry", )?; // No entry exists - create a new one router_env::logger::info!( "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry... ", id.get_string_repr() ); let tag = ["PCR"]; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_entry = storage::ProcessTrackerNew::new( &process_tracker_id, task, runner, tag, process.tracking_data.clone(), Some(new_retry_count), schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to construct calculate workflow process tracker entry")?; // Insert into process tracker with status New db.as_scheduler() .insert_process(process_tracker_entry) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable( "Failed to enter calculate workflow process_tracker_entry in DB", )?; router_env::logger::info!( "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}", id.get_string_repr() ); logger::info!( payment_id = %id.get_string_repr(), process_tracker_id = %process_tracker_id, "Successfully created new CALCULATE_WORKFLOW entry using perform_calculate_workflow" ); } } Ok(()) } // TODO: Move these to impl based functions async fn record_back_to_billing_connector( state: &SessionState, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, billing_mca: &merchant_connector_account::MerchantConnectorAccount, ) -> RecoveryResult<()> { logger::info!("Entering record_back_to_billing_connector"); let connector_name = billing_mca.connector_name.to_string(); let connector_data = api_types::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_name, api_types::GetToken::Connector, Some(billing_mca.get_id()), ) .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("invalid connector name received in billing merchant connector account")?; let connector_integration: services::BoxedRevenueRecoveryRecordBackInterface< router_flow_types::InvoiceRecordBack, revenue_recovery_request::InvoiceRecordBackRequest, revenue_recovery_response::InvoiceRecordBackResponse, > = connector_data.connector.get_connector_integration(); let router_data = construct_invoice_record_back_router_data( state, billing_mca, payment_attempt, payment_intent, )?; let response = services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed while handling response of record back to billing connector")?; match response.response { Ok(response) => Ok(response), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed while recording back to billing connector") } }?; Ok(()) } pub fn construct_invoice_record_back_router_data( state: &SessionState, billing_mca: &merchant_connector_account::MerchantConnectorAccount, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData> { logger::info!("Entering construct_invoice_record_back_router_data"); let auth_type: types::ConnectorAuthType = helpers::MerchantConnectorAccountType::DbVal(Box::new(billing_mca.clone())) .get_connector_account_details() .parse_value("ConnectorAuthType") .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)?; let merchant_reference_id = payment_intent .merchant_reference_id .clone() .ok_or(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable( "Merchant reference id not found while recording back to billing connector", )?; let connector_name = billing_mca.get_connector_name_as_string(); let connector = common_enums::connector_enums::Connector::from_str(connector_name.as_str()) .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Cannot find connector from the connector_name")?; let connector_params = hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params( &state.conf.connectors, connector, ) .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable(format!( "cannot find connector params for this connector {connector} in this flow", ))?; let router_data = router_data_v2::RouterDataV2 { flow: PhantomData::<router_flow_types::InvoiceRecordBack>, tenant_id: state.tenant.tenant_id.clone(), resource_common_data: flow_common_types::InvoiceRecordBackData { connector_meta_data: None, }, connector_auth_type: auth_type, request: revenue_recovery_request::InvoiceRecordBackRequest { merchant_reference_id, amount: payment_attempt.get_total_amount(), currency: payment_intent.amount_details.currency, payment_method_type: Some(payment_attempt.payment_method_subtype), attempt_status: payment_attempt.status, connector_transaction_id: payment_attempt .connector_payment_id .as_ref() .map(|id| common_utils::types::ConnectorTransactionId::TxnId(id.clone())), connector_params, }, response: Err(types::ErrorResponse::default()), }; let old_router_data = flow_common_types::InvoiceRecordBackData::to_old_router_data(router_data) .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Cannot construct record back router data")?; Ok(old_router_data) } pub fn get_payment_processor_token_id_from_payment_attempt( payment_attempt: &PaymentAttempt, ) -> Option<String> { let used_token = payment_attempt .connector_token_details .as_ref() .and_then(|t| t.connector_mandate_id.clone()); logger::info!("Used token in the payment attempt : {:?}", used_token); used_token } pub struct RevenueRecoveryOutgoingWebhook; impl RevenueRecoveryOutgoingWebhook { #[allow(clippy::too_many_arguments)] pub async fn send_outgoing_webhook_based_on_revenue_recovery_status( state: &SessionState, event_class: common_enums::EventClass, event_status: common_enums::EventType, payment_intent: &PaymentIntent, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_attempt_id: String, payments_response: ApplicationResponse<api_models::payments::PaymentsResponse>, ) -> RecoveryResult<()> { match payments_response { ApplicationResponse::JsonWithHeaders((response, _headers)) => { let outgoing_webhook_content = api_models::webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( response, )); create_event_and_trigger_outgoing_webhook( state.clone(), profile.clone(), merchant_context.get_merchant_key_store(), event_status, event_class, payment_attempt_id, enums::EventObjectType::PaymentDetails, outgoing_webhook_content, payment_intent.created_at, ) .await .change_context(errors::RecoveryError::InvalidTask) .attach_printable("Failed to send out going webhook")?; Ok(()) } _other_variant => { // Handle other successful response types if needed logger::warn!("Unexpected application response variant for outgoing webhook"); Err(errors::RecoveryError::RevenueRecoveryOutgoingWebhookFailed.into()) } } } }
{ "crate": "router", "file": "crates/router/src/core/revenue_recovery/types.rs", "file_size": 63165, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_1651507726055824913
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/routes/routing.rs // File size: 62111 bytes //! Analysis for usage of Routing in Payment flows //! //! Functions that are used to perform the api level configuration, retrieval, updation //! of Routing configs. use actix_web::{web, HttpRequest, Responder}; use api_models::{ enums, routing::{ self as routing_types, RoutingEvaluateRequest, RoutingEvaluateResponse, RoutingRetrieveQuery, }, }; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_context::MerchantKeyStore; use payment_methods::core::errors::ApiErrorResponse; use router_env::{ tracing::{self, instrument}, Flow, }; use crate::{ core::{ api_locking, conditional_config, payments::routing::utils::{DecisionEngineApiHandler, EuclidApiClient}, routing, surcharge_decision_config, }, db::errors::StorageErrorExt, routes::AppState, services, services::{api as oss_api, authentication as auth, authorization::permissions::Permission}, types::domain, }; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_routing_algorithm_under_profile( state, merchant_context, auth.profile_id, payload.clone(), transaction_type .or(payload.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_create_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingCreateConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_routing_algorithm_under_profile( state, merchant_context, Some(auth.profile.get_id().clone()), payload, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_link_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, json_payload: web::Json<routing_types::RoutingActivatePayload>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingLinkConfig; Box::pin(oss_api::server_wrap( flow, state, &req, path.into_inner(), |state, auth: auth::AuthenticationData, algorithm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::link_routing_config( state, merchant_context, auth.profile_id, algorithm, transaction_type .or(json_payload.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_link_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<routing_types::RoutingAlgorithmId>, transaction_type: &enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingLinkConfig; let wrapper = routing_types::RoutingLinkWrapper { profile_id: path.into_inner(), algorithm_id: json_payload.into_inner(), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::link_routing_config_under_profile( state, merchant_context, wrapper.profile_id, wrapper.algorithm_id.routing_algorithm_id, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, ) -> impl Responder { let algorithm_id = path.into_inner(); let flow = Flow::RoutingRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, algorithm_id, |state, auth: auth::AuthenticationData, algorithm_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_algorithm_from_algorithm_id( state, merchant_context, auth.profile_id, algorithm_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::RoutingId>, ) -> impl Responder { let algorithm_id = path.into_inner(); let flow = Flow::RoutingRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, algorithm_id, |state, auth: auth::AuthenticationData, algorithm_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_algorithm_from_algorithm_id( state, merchant_context, Some(auth.profile.get_id().clone()), algorithm_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn list_routing_configs( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingRetrieveDictionary; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_merchant_routing_dictionary( state, merchant_context, None, query_params.clone(), transaction_type .or(query_params.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn list_routing_configs_for_profile( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingRetrieveDictionary; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, auth: auth::AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_merchant_routing_dictionary( state, merchant_context, auth.profile_id.map(|profile_id| vec![profile_id]), query_params.clone(), transaction_type .or(query_params.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_unlink_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> impl Responder { let flow = Flow::RoutingUnlinkConfig; let path = path.into_inner(); Box::pin(oss_api::server_wrap( flow, state, &req, path.clone(), |state, auth: auth::AuthenticationData, path, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::unlink_routing_config_under_profile( state, merchant_context, path, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_unlink_config( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<routing_types::RoutingConfigRequest>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { let flow = Flow::RoutingUnlinkConfig; Box::pin(oss_api::server_wrap( flow, state, &req, payload.into_inner(), |state, auth: auth::AuthenticationData, payload_req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::unlink_routing_config( state, merchant_context, payload_req.clone(), auth.profile_id, transaction_type .or(payload_req.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_update_default_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, ) -> impl Responder { let wrapper = routing_types::ProfileDefaultRoutingConfig { profile_id: path.into_inner(), connectors: json_payload.into_inner(), }; Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, wrapper, |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_fallback_routing( state, merchant_context, wrapper.profile_id, wrapper.connectors, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_update_default_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, updated_config, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_routing_config( state, merchant_context, updated_config, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_default_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, ) -> impl Responder { let path = path.into_inner(); Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, path.clone(), |state, auth: auth::AuthenticationData, profile_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_fallback_algorithm_for_profile( state, merchant_context, profile_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::MerchantRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_default_config( state: web::Data<AppState>, req: HttpRequest, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_routing_config( state, auth.profile_id, merchant_context, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn upsert_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::surcharge_decision_configs::SurchargeDecisionConfigReq>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::upsert_surcharge_decision_config( state, merchant_context, update_decision, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn delete_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerDeleteConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, (), _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::delete_surcharge_decision_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_surcharge_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); surcharge_decision_config::retrieve_surcharge_decision_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantSurchargeDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn upsert_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::conditional_configs::DecisionManager>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::upsert_conditional_config(state, merchant_context, update_decision) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn upsert_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::conditional_configs::DecisionManagerRequest>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { conditional_config::upsert_conditional_config( state, auth.key_store, update_decision, auth.profile, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn delete_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerDeleteConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, (), _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::delete_conditional_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v2"))] #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { conditional_config::retrieve_conditional_config(state, auth.key_store, auth.profile) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn retrieve_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, ) -> impl Responder { let flow = Flow::DecisionManagerRetrieveConfig; Box::pin(oss_api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); conditional_config::retrieve_conditional_config(state, merchant_context) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantThreeDsDecisionManagerRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn routing_retrieve_linked_config( state: web::Data<AppState>, req: HttpRequest, query: web::Query<routing_types::RoutingRetrieveLinkQuery>, transaction_type: Option<enums::TransactionType>, ) -> impl Responder { use crate::services::authentication::AuthenticationData; let flow = Flow::RoutingRetrieveActiveConfig; let query = query.into_inner(); if let Some(profile_id) = query.profile_id.clone() { Box::pin(oss_api::server_wrap( flow, state, &req, query.clone(), |state, auth: AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_linked_routing_config( state, merchant_context, auth.profile_id, query_params, transaction_type .or(query.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } else { Box::pin(oss_api::server_wrap( flow, state, &req, query.clone(), |state, auth: AuthenticationData, query_params, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_linked_routing_config( state, merchant_context, auth.profile_id, query_params, transaction_type .or(query.transaction_type) .unwrap_or(enums::TransactionType::Payment), ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } } #[cfg(all(feature = "olap", feature = "v2"))] #[instrument(skip_all)] pub async fn routing_retrieve_linked_config( state: web::Data<AppState>, req: HttpRequest, query: web::Query<RoutingRetrieveQuery>, path: web::Path<common_utils::id_type::ProfileId>, transaction_type: &enums::TransactionType, ) -> impl Responder { use crate::services::authentication::AuthenticationData; let flow = Flow::RoutingRetrieveActiveConfig; let wrapper = routing_types::RoutingRetrieveLinkQueryWrapper { routing_query: query.into_inner(), profile_id: path.into_inner(), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_routing_config_under_profile( state, merchant_context, wrapper.routing_query, wrapper.profile_id, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn routing_retrieve_default_config_for_profiles( state: web::Data<AppState>, req: HttpRequest, transaction_type: &enums::TransactionType, ) -> impl Responder { Box::pin(oss_api::server_wrap( Flow::RoutingRetrieveDefaultConfig, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_default_routing_config_for_profiles( state, merchant_context, transaction_type, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), #[cfg(feature = "release")] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::MerchantRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "olap")] #[instrument(skip_all)] pub async fn routing_update_default_config_for_profile( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::ProfileId>, json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, transaction_type: &enums::TransactionType, ) -> impl Responder { let routing_payload_wrapper = routing_types::RoutingPayloadWrapper { updated_config: json_payload.into_inner(), profile_id: path.into_inner(), }; Box::pin(oss_api::server_wrap( Flow::RoutingUpdateDefaultConfig, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::update_default_routing_config_for_profile( state, merchant_context, wrapper.updated_config, wrapper.profile_id, transaction_type, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn toggle_success_based_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let wrapper = routing_types::ToggleDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ToggleDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::toggle_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::SuccessRateBasedRouting, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn create_success_based_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::CreateDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, success_based_config: web::Json<routing_types::SuccessBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::CreateDynamicRoutingConfig; let wrapper = routing_types::CreateDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, payload: api_models::routing::DynamicRoutingPayload::SuccessBasedRoutingPayload( success_based_config.into_inner(), ), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::CreateDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::SuccessRateBasedRouting, wrapper.payload, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn success_based_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::SuccessBasedRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.clone().algorithm_id, profile_id: path.clone().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, _, wrapper: routing_types::SuccessBasedRoutingPayloadWrapper, _| async { Box::pin(routing::success_based_routing_update_configs( state, wrapper.updated_config, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn elimination_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::EliminationRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::EliminationRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.clone().algorithm_id, profile_id: path.clone().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, _, wrapper: routing_types::EliminationRoutingPayloadWrapper, _| async { Box::pin(routing::elimination_routing_update_configs( state, wrapper.updated_config, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn contract_based_routing_setup_config( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::ToggleDynamicRoutingPath>, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, json_payload: Option<web::Json<routing_types::ContractBasedRoutingConfig>>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let routing_payload_wrapper = routing_types::ContractBasedRoutingSetupPayloadWrapper { config: json_payload.map(|json| json.into_inner()), profile_id: path.into_inner().profile_id, features_to_enable: query.into_inner().enable, }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ContractBasedRoutingSetupPayloadWrapper, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(routing::contract_based_dynamic_routing_setup( state, merchant_context, wrapper.profile_id, wrapper.features_to_enable, wrapper.config, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn contract_based_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::ContractBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; let routing_payload_wrapper = routing_types::ContractBasedRoutingPayloadWrapper { updated_config: json_payload.into_inner(), algorithm_id: path.algorithm_id.clone(), profile_id: path.profile_id.clone(), }; Box::pin(oss_api::server_wrap( flow, state, &req, routing_payload_wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ContractBasedRoutingPayloadWrapper, _| async { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(routing::contract_based_routing_update_configs( state, wrapper.updated_config, merchant_context, wrapper.algorithm_id, wrapper.profile_id, )) .await }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn toggle_elimination_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::ToggleDynamicRouting; let wrapper = routing_types::ToggleDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::ToggleDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::toggle_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::EliminationRouting, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn create_elimination_routing( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::CreateDynamicRoutingQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, elimination_config: web::Json<routing_types::EliminationRoutingConfig>, ) -> impl Responder { let flow = Flow::CreateDynamicRoutingConfig; let wrapper = routing_types::CreateDynamicRoutingWrapper { feature_to_enable: query.into_inner().enable, profile_id: path.into_inner().profile_id, payload: api_models::routing::DynamicRoutingPayload::EliminationRoutingPayload( elimination_config.into_inner(), ), }; Box::pin(oss_api::server_wrap( flow, state, &req, wrapper.clone(), |state, auth: auth::AuthenticationData, wrapper: routing_types::CreateDynamicRoutingWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::create_specific_dynamic_routing( state, merchant_context, wrapper.feature_to_enable, wrapper.profile_id, api_models::routing::DynamicRoutingType::EliminationRouting, wrapper.payload, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn set_dynamic_routing_volume_split( state: web::Data<AppState>, req: HttpRequest, query: web::Query<api_models::routing::DynamicRoutingVolumeSplitQuery>, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::VolumeSplitOnRoutingType; let routing_info = api_models::routing::RoutingVolumeSplit { routing_type: api_models::routing::RoutingType::Dynamic, split: query.into_inner().split, }; let payload = api_models::routing::RoutingVolumeSplitWrapper { routing_info, profile_id: path.into_inner().profile_id, }; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, payload: api_models::routing::RoutingVolumeSplitWrapper, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::configure_dynamic_routing_volume_split( state, merchant_context, payload.profile_id, payload.routing_info, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: payload.profile_id, required_permission: Permission::ProfileRoutingWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn get_dynamic_routing_volume_split( state: web::Data<AppState>, req: HttpRequest, path: web::Path<routing_types::ToggleDynamicRoutingPath>, ) -> impl Responder { let flow = Flow::VolumeSplitOnRoutingType; let payload = path.into_inner(); Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, auth: auth::AuthenticationData, payload, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); routing::retrieve_dynamic_routing_volume_split( state, merchant_context, payload.profile_id, ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuthProfileFromRoute { profile_id: payload.profile_id, required_permission: Permission::ProfileRoutingRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } const EUCLID_API_TIMEOUT: u64 = 5; #[cfg(all(feature = "olap", feature = "v1"))] #[instrument(skip_all)] pub async fn evaluate_routing_rule( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<RoutingEvaluateRequest>, ) -> impl Responder { let json_payload = json_payload.into_inner(); let flow = Flow::RoutingEvaluateRule; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.clone(), |state, _auth: auth::AuthenticationData, payload, _| async move { let euclid_response: RoutingEvaluateResponse = EuclidApiClient::send_decision_engine_request( &state, services::Method::Post, "routing/evaluate", Some(payload), Some(EUCLID_API_TIMEOUT), None, ) .await .change_context(ApiErrorResponse::InternalServerError)? .response .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Failed to evaluate routing rule")?; Ok(services::ApplicationResponse::Json(euclid_response)) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } use actix_web::HttpResponse; #[instrument(skip_all, fields(flow = ?Flow::DecisionEngineRuleMigration))] pub async fn migrate_routing_rules_for_profile( state: web::Data<AppState>, req: HttpRequest, query: web::Query<routing_types::RuleMigrationQuery>, ) -> HttpResponse { let flow = Flow::DecisionEngineRuleMigration; Box::pin(oss_api::server_wrap( flow, state, &req, query.into_inner(), |state, _, query_params, _| async move { let merchant_id = query_params.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(routing::migrate_rules_for_profile( state, merchant_context, query_params, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } async fn get_merchant_account( state: &super::SessionState, merchant_id: &common_utils::id_type::MerchantId, ) -> common_utils::errors::CustomResult<(MerchantKeyStore, domain::MerchantAccount), ApiErrorResponse> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn call_decide_gateway_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::OpenRouterDecideGatewayRequest>, ) -> impl Responder { let flow = Flow::DecisionEngineDecideGatewayCall; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, payload, _| routing::decide_gateway_open_router(state.clone(), payload), &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn call_update_gateway_score_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::UpdateScorePayload>, ) -> impl Responder { let flow = Flow::DecisionEngineGatewayFeedbackCall; Box::pin(oss_api::server_wrap( flow, state, &req, payload.clone(), |state, _auth, payload, _| { routing::update_gateway_score_open_router(state.clone(), payload) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
{ "crate": "router", "file": "crates/router/src/routes/routing.rs", "file_size": 62111, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-355530700020337995
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/payments/flows/session_flow.rs // File size: 61509 bytes use api_models::{admin as admin_types, payments as payment_types}; use async_trait::async_trait; use common_utils::{ ext_traits::ByteSliceExt, request::RequestContent, types::{AmountConvertor, StringMajorUnitForConnector}, }; use error_stack::{Report, ResultExt}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::PaymentIntentData; use masking::{ExposeInterface, ExposeOptionInterface}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ consts::PROTOCOL, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, customers, helpers, transformers, PaymentData}, }, headers, logger, routes::{self, app::settings, metrics}, services, types::{ self, api::{self, enums}, domain, }, utils::OptionExt, }; #[cfg(feature = "v2")] #[async_trait] impl ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for PaymentIntentData<api::Session> { async fn construct_router_data<'a>( &self, state: &routes::SessionState, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails, merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data_for_sdk_session( state, self.clone(), connector_id, merchant_context, customer, merchant_connector_account, merchant_recipient_data, header_payload, )) .await } } #[cfg(feature = "v1")] #[async_trait] impl ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for PaymentData<api::Session> { async fn construct_router_data<'a>( &self, state: &routes::SessionState, connector_id: &str, merchant_context: &domain::MerchantContext, customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>, payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Session, types::PaymentsSessionData, >( state, self.clone(), connector_id, merchant_context, customer, merchant_connector_account, merchant_recipient_data, header_payload, payment_method, payment_method_type, )) .await } } #[async_trait] impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessionRouterData { async fn decide_flows<'a>( self, state: &routes::SessionState, connector: &api::ConnectorData, call_connector_action: payments::CallConnectorAction, _connector_request: Option<services::Request>, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, _return_raw_connector_response: Option<bool>, ) -> RouterResult<Self> { metrics::SESSION_TOKEN_CREATED.add( 1, router_env::metric_attributes!(("connector", connector.connector_name.to_string())), ); self.decide_flow( state, connector, Some(true), call_connector_action, business_profile, header_payload, ) .await } async fn add_access_token<'a>( &self, state: &routes::SessionState, connector: &api::ConnectorData, merchant_context: &domain::MerchantContext, creds_identifier: Option<&str>, ) -> RouterResult<types::AddAccessTokenResult> { Box::pin(access_token::add_access_token( state, connector, merchant_context, self, creds_identifier, )) .await } async fn create_connector_customer<'a>( &self, state: &routes::SessionState, connector: &api::ConnectorData, ) -> RouterResult<Option<String>> { customers::create_connector_customer( state, connector, self, types::ConnectorCustomerData::try_from(self)?, ) .await } } /// This function checks if for a given connector, payment_method and payment_method_type, /// the list of required_field_type is present in dynamic fields #[cfg(feature = "v1")] fn is_dynamic_fields_required( required_fields: &settings::RequiredFields, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, connector: types::Connector, required_field_type: Vec<enums::FieldType>, ) -> bool { required_fields .0 .get(&payment_method) .and_then(|pm_type| pm_type.0.get(&payment_method_type)) .and_then(|required_fields_for_connector| { required_fields_for_connector.fields.get(&connector) }) .map(|required_fields_final| { required_fields_final .non_mandate .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) || required_fields_final .mandate .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) || required_fields_final .common .iter() .any(|(_, val)| required_field_type.contains(&val.field_type)) }) .unwrap_or(false) } /// This function checks if for a given connector, payment_method and payment_method_type, /// the list of required_field_type is present in dynamic fields #[cfg(feature = "v2")] fn is_dynamic_fields_required( required_fields: &settings::RequiredFields, payment_method: enums::PaymentMethod, payment_method_type: enums::PaymentMethodType, connector: types::Connector, required_field_type: Vec<enums::FieldType>, ) -> bool { required_fields .0 .get(&payment_method) .and_then(|pm_type| pm_type.0.get(&payment_method_type)) .and_then(|required_fields_for_connector| { required_fields_for_connector.fields.get(&connector) }) .map(|required_fields_final| { required_fields_final .non_mandate .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) || required_fields_final .mandate .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) || required_fields_final .common .iter() .flatten() .any(|field_info| required_field_type.contains(&field_info.field_type)) }) .unwrap_or(false) } fn build_apple_pay_session_request( state: &routes::SessionState, request: payment_types::ApplepaySessionRequest, apple_pay_merchant_cert: masking::Secret<String>, apple_pay_merchant_cert_key: masking::Secret<String>, ) -> RouterResult<services::Request> { let mut url = state.conf.connectors.applepay.base_url.to_owned(); url.push_str("paymentservices/paymentSession"); let session_request = services::RequestBuilder::new() .method(services::Method::Post) .url(url.as_str()) .attach_default_headers() .headers(vec![( headers::CONTENT_TYPE.to_string(), "application/json".to_string().into(), )]) .set_body(RequestContent::Json(Box::new(request))) .add_certificate(Some(apple_pay_merchant_cert)) .add_certificate_key(Some(apple_pay_merchant_cert_key)) .build(); Ok(session_request) } async fn create_applepay_session_token( state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { let delayed_response = is_session_response_delayed(state, connector); if delayed_response { let delayed_response_apple_pay_session = Some(payment_types::ApplePaySessionResponse::NoSessionResponse( api_models::payments::NullObject, )); create_apple_pay_session_response( router_data, delayed_response_apple_pay_session, None, // Apple pay payment request will be none for delayed session response connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, header_payload, ) } else { // Get the apple pay metadata let apple_pay_metadata = helpers::get_applepay_metadata(router_data.connector_meta_data.clone()) .attach_printable( "Failed to to fetch apple pay certificates during session call", )?; // Get payment request data , apple pay session request and merchant keys let ( payment_request_data, apple_pay_session_request_optional, apple_pay_merchant_cert, apple_pay_merchant_cert_key, apple_pay_merchant_identifier, merchant_business_country, merchant_configured_domain_optional, ) = match apple_pay_metadata { payment_types::ApplepaySessionTokenMetadata::ApplePayCombined( apple_pay_combined_metadata, ) => match apple_pay_combined_metadata { payment_types::ApplePayCombinedMetadata::Simplified { payment_request_data, session_token_data, } => { logger::info!("Apple pay simplified flow"); let merchant_identifier = state .conf .applepay_merchant_configs .get_inner() .common_merchant_identifier .clone() .expose(); let merchant_business_country = session_token_data.merchant_business_country; let apple_pay_session_request = get_session_request_for_simplified_apple_pay( merchant_identifier.clone(), session_token_data.clone(), ); let apple_pay_merchant_cert = state .conf .applepay_decrypt_keys .get_inner() .apple_pay_merchant_cert .clone(); let apple_pay_merchant_cert_key = state .conf .applepay_decrypt_keys .get_inner() .apple_pay_merchant_cert_key .clone(); ( payment_request_data, Ok(apple_pay_session_request), apple_pay_merchant_cert, apple_pay_merchant_cert_key, merchant_identifier, merchant_business_country, Some(session_token_data.initiative_context), ) } payment_types::ApplePayCombinedMetadata::Manual { payment_request_data, session_token_data, } => { logger::info!("Apple pay manual flow"); let apple_pay_session_request = get_session_request_for_manual_apple_pay( session_token_data.clone(), header_payload.x_merchant_domain.clone(), ); let merchant_business_country = session_token_data.merchant_business_country; ( payment_request_data, apple_pay_session_request, session_token_data.certificate.clone(), session_token_data.certificate_keys, session_token_data.merchant_identifier, merchant_business_country, session_token_data.initiative_context, ) } }, payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { logger::info!("Apple pay manual flow"); let apple_pay_session_request = get_session_request_for_manual_apple_pay( apple_pay_metadata.session_token_data.clone(), header_payload.x_merchant_domain.clone(), ); let merchant_business_country = apple_pay_metadata .session_token_data .merchant_business_country; ( apple_pay_metadata.payment_request_data, apple_pay_session_request, apple_pay_metadata.session_token_data.certificate.clone(), apple_pay_metadata .session_token_data .certificate_keys .clone(), apple_pay_metadata.session_token_data.merchant_identifier, merchant_business_country, apple_pay_metadata.session_token_data.initiative_context, ) } }; // Get amount info for apple pay let amount_info = get_apple_pay_amount_info( payment_request_data.label.as_str(), router_data.request.to_owned(), )?; let required_billing_contact_fields = if business_profile .always_collect_billing_details_from_wallet_connector .unwrap_or(false) { Some(payment_types::ApplePayBillingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, ])) } else if business_profile .collect_billing_details_from_wallet_connector .unwrap_or(false) { let billing_variants = enums::FieldType::get_billing_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, connector.connector_name, billing_variants, ) .then_some(payment_types::ApplePayBillingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, ])) } else { None }; let required_shipping_contact_fields = if business_profile .always_collect_shipping_details_from_wallet_connector .unwrap_or(false) { Some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else if business_profile .collect_shipping_details_from_wallet_connector .unwrap_or(false) { let shipping_variants = enums::FieldType::get_shipping_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, enums::PaymentMethodType::ApplePay, connector.connector_name, shipping_variants, ) .then_some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::PostalAddress, payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else { None }; // If collect_shipping_details_from_wallet_connector is false, we check if // collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in // ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields // does not contain Email and Phone. let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some() && required_shipping_contact_fields.is_none() { Some(payment_types::ApplePayShippingContactFields(vec![ payment_types::ApplePayAddressParameters::Phone, payment_types::ApplePayAddressParameters::Email, ])) } else { required_shipping_contact_fields }; // Get apple pay payment request let applepay_payment_request = get_apple_pay_payment_request( amount_info, payment_request_data, router_data.request.to_owned(), apple_pay_merchant_identifier.as_str(), merchant_business_country, required_billing_contact_fields, required_shipping_contact_fields_updated, )?; let apple_pay_session_response = match ( header_payload.browser_name.clone(), header_payload.x_client_platform.clone(), ) { (Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web)) | (None, None) => { let apple_pay_session_request = apple_pay_session_request_optional .attach_printable("Failed to obtain apple pay session request")?; let applepay_session_request = build_apple_pay_session_request( state, apple_pay_session_request.clone(), apple_pay_merchant_cert.clone(), apple_pay_merchant_cert_key.clone(), )?; let response = services::call_connector_api( state, applepay_session_request, "create_apple_pay_session_token", ) .await; let updated_response = match ( response.as_ref().ok(), header_payload.x_merchant_domain.clone(), ) { (Some(Err(error)), Some(_)) => { logger::error!( "Retry apple pay session call with the merchant configured domain {error:?}" ); let merchant_configured_domain = merchant_configured_domain_optional .get_required_value("apple pay domain") .attach_printable("Failed to get domain for apple pay session call")?; let apple_pay_retry_session_request = payment_types::ApplepaySessionRequest { initiative_context: merchant_configured_domain, ..apple_pay_session_request }; let applepay_retry_session_request = build_apple_pay_session_request( state, apple_pay_retry_session_request, apple_pay_merchant_cert, apple_pay_merchant_cert_key, )?; services::call_connector_api( state, applepay_retry_session_request, "create_apple_pay_session_token", ) .await } _ => response, }; // logging the error if present in session call response log_session_response_if_error(&updated_response); updated_response .ok() .and_then(|apple_pay_res| { apple_pay_res .map(|res| { let response: Result< payment_types::NoThirdPartySdkSessionResponse, Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("NoThirdPartySdkSessionResponse"); // logging the parsing failed error if let Err(error) = response.as_ref() { logger::error!(?error); }; response.ok() }) .ok() }) .flatten() } _ => { logger::debug!("Skipping apple pay session call based on the browser name"); None } }; let session_response = apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk); create_apple_pay_session_response( router_data, session_response, Some(applepay_payment_request), connector.connector_name.to_string(), delayed_response, payment_types::NextActionCall::Confirm, header_payload, ) } } fn create_paze_session_token( router_data: &types::PaymentsSessionRouterData, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { let paze_wallet_details = router_data .connector_wallets_details .clone() .parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_wallets_details".to_string(), expected_format: "paze_metadata_format".to_string(), })?; let required_amount_type = StringMajorUnitForConnector; let transaction_currency_code = router_data.request.currency; let transaction_amount = required_amount_type .convert(router_data.request.minor_amount, transaction_currency_code) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for paze".to_string(), })?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::Paze(Box::new( payment_types::PazeSessionTokenResponse { client_id: paze_wallet_details.data.client_id, client_name: paze_wallet_details.data.client_name, client_profile_id: paze_wallet_details.data.client_profile_id, transaction_currency_code, transaction_amount, email_address: router_data.request.email.clone(), }, )), }), ..router_data.clone() }) } fn create_samsung_pay_session_token( state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, header_payload: hyperswitch_domain_models::payments::HeaderPayload, connector: &api::ConnectorData, business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { let samsung_pay_session_token_data = router_data .connector_wallets_details .clone() .parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_wallets_details".to_string(), expected_format: "samsung_pay_metadata_format".to_string(), })?; let required_amount_type = StringMajorUnitForConnector; let samsung_pay_amount = required_amount_type .convert( router_data.request.minor_amount, router_data.request.currency, ) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for Samsung Pay".to_string(), })?; let merchant_domain = match header_payload.x_client_platform { Some(common_enums::ClientPlatform::Web) => Some( header_payload .x_merchant_domain .get_required_value("samsung pay domain") .attach_printable("Failed to get domain for samsung pay session call")?, ), _ => None, }; let samsung_pay_wallet_details = match samsung_pay_session_token_data.data { payment_types::SamsungPayCombinedMetadata::MerchantCredentials( samsung_pay_merchant_credentials, ) => samsung_pay_merchant_credentials, payment_types::SamsungPayCombinedMetadata::ApplicationCredentials( _samsung_pay_application_credentials, ) => Err(errors::ApiErrorResponse::NotSupported { message: "Samsung Pay decryption flow with application credentials is not implemented" .to_owned(), })?, }; let formatted_payment_id = router_data.payment_id.replace("_", "-"); let billing_address_required = is_billing_address_required_to_be_collected_from_wallet( state, connector, business_profile, enums::PaymentMethodType::SamsungPay, ); let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet( state, connector, business_profile, enums::PaymentMethodType::SamsungPay, ); Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::SamsungPay(Box::new( payment_types::SamsungPaySessionTokenResponse { version: "2".to_string(), service_id: samsung_pay_wallet_details.service_id, order_number: formatted_payment_id, merchant_payment_information: payment_types::SamsungPayMerchantPaymentInformation { name: samsung_pay_wallet_details.merchant_display_name, url: merchant_domain, country_code: samsung_pay_wallet_details.merchant_business_country, }, amount: payment_types::SamsungPayAmountDetails { amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly, currency_code: router_data.request.currency, total_amount: samsung_pay_amount, }, protocol: payment_types::SamsungPayProtocolType::Protocol3ds, allowed_brands: samsung_pay_wallet_details.allowed_brands, billing_address_required, shipping_address_required, }, )), }), ..router_data.clone() }) } /// Function to determine whether the billing address is required to be collected from the wallet, /// based on business profile settings, the payment method type, and the connector's required fields /// for the specific payment method. /// /// If `always_collect_billing_details_from_wallet_connector` is enabled, it indicates that the /// billing address is always required to be collected from the wallet. /// /// If only `collect_billing_details_from_wallet_connector` is enabled, the billing address will be /// collected only if the connector required fields for the specific payment method type contain /// the billing fields. fn is_billing_address_required_to_be_collected_from_wallet( state: &routes::SessionState, connector: &api::ConnectorData, business_profile: &domain::Profile, payment_method_type: enums::PaymentMethodType, ) -> bool { let always_collect_billing_details_from_wallet_connector = business_profile .always_collect_billing_details_from_wallet_connector .unwrap_or(false); if always_collect_billing_details_from_wallet_connector { always_collect_billing_details_from_wallet_connector } else if business_profile .collect_billing_details_from_wallet_connector .unwrap_or(false) { let billing_variants = enums::FieldType::get_billing_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, payment_method_type, connector.connector_name, billing_variants, ) } else { false } } /// Function to determine whether the shipping address is required to be collected from the wallet, /// based on business profile settings, the payment method type, and the connector required fields /// for the specific payment method type. /// /// If `always_collect_shipping_details_from_wallet_connector` is enabled, it indicates that the /// shipping address is always required to be collected from the wallet. /// /// If only `collect_shipping_details_from_wallet_connector` is enabled, the shipping address will be /// collected only if the connector required fields for the specific payment method type contain /// the shipping fields. fn is_shipping_address_required_to_be_collected_form_wallet( state: &routes::SessionState, connector: &api::ConnectorData, business_profile: &domain::Profile, payment_method_type: enums::PaymentMethodType, ) -> bool { let always_collect_shipping_details_from_wallet_connector = business_profile .always_collect_shipping_details_from_wallet_connector .unwrap_or(false); if always_collect_shipping_details_from_wallet_connector { always_collect_shipping_details_from_wallet_connector } else if business_profile .collect_shipping_details_from_wallet_connector .unwrap_or(false) { let shipping_variants = enums::FieldType::get_shipping_variants(); is_dynamic_fields_required( &state.conf.required_fields, enums::PaymentMethod::Wallet, payment_method_type, connector.connector_name, shipping_variants, ) } else { false } } fn get_session_request_for_simplified_apple_pay( apple_pay_merchant_identifier: String, session_token_data: payment_types::SessionTokenForSimplifiedApplePay, ) -> payment_types::ApplepaySessionRequest { payment_types::ApplepaySessionRequest { merchant_identifier: apple_pay_merchant_identifier, display_name: "Apple pay".to_string(), initiative: "web".to_string(), initiative_context: session_token_data.initiative_context, } } fn get_session_request_for_manual_apple_pay( session_token_data: payment_types::SessionTokenInfo, merchant_domain: Option<String>, ) -> RouterResult<payment_types::ApplepaySessionRequest> { let initiative_context = merchant_domain .or_else(|| session_token_data.initiative_context.clone()) .get_required_value("apple pay domain") .attach_printable("Failed to get domain for apple pay session call")?; Ok(payment_types::ApplepaySessionRequest { merchant_identifier: session_token_data.merchant_identifier.clone(), display_name: session_token_data.display_name.clone(), initiative: session_token_data.initiative.to_string(), initiative_context, }) } fn get_apple_pay_amount_info( label: &str, session_data: types::PaymentsSessionData, ) -> RouterResult<payment_types::AmountInfo> { let required_amount_type = StringMajorUnitForConnector; let apple_pay_amount = required_amount_type .convert(session_data.minor_amount, session_data.currency) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for applePay".to_string(), })?; let amount_info = payment_types::AmountInfo { label: label.to_string(), total_type: Some("final".to_string()), amount: apple_pay_amount, }; Ok(amount_info) } fn get_apple_pay_payment_request( amount_info: payment_types::AmountInfo, payment_request_data: payment_types::PaymentRequestMetadata, session_data: types::PaymentsSessionData, merchant_identifier: &str, merchant_business_country: Option<api_models::enums::CountryAlpha2>, required_billing_contact_fields: Option<payment_types::ApplePayBillingContactFields>, required_shipping_contact_fields: Option<payment_types::ApplePayShippingContactFields>, ) -> RouterResult<payment_types::ApplePayPaymentRequest> { let applepay_payment_request = payment_types::ApplePayPaymentRequest { country_code: merchant_business_country.or(session_data.country).ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "country_code", }, )?, currency_code: session_data.currency, total: amount_info, merchant_capabilities: Some(payment_request_data.merchant_capabilities), supported_networks: Some(payment_request_data.supported_networks), merchant_identifier: Some(merchant_identifier.to_string()), required_billing_contact_fields, required_shipping_contact_fields, recurring_payment_request: session_data.apple_pay_recurring_details, }; Ok(applepay_payment_request) } fn create_apple_pay_session_response( router_data: &types::PaymentsSessionRouterData, session_response: Option<payment_types::ApplePaySessionResponse>, apple_pay_payment_request: Option<payment_types::ApplePayPaymentRequest>, connector_name: String, delayed_response: bool, next_action: payment_types::NextActionCall, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { match session_response { Some(response) => Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::ApplePay(Box::new( payment_types::ApplepaySessionTokenResponse { session_token_data: Some(response), payment_request_data: apple_pay_payment_request, connector: connector_name, delayed_session_token: delayed_response, sdk_next_action: { payment_types::SdkNextAction { next_action } }, connector_reference_id: None, connector_sdk_public_key: None, connector_merchant_id: None, }, )), }), ..router_data.clone() }), None => { match ( header_payload.browser_name, header_payload.x_client_platform, ) { ( Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web), ) | (None, None) => Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::NoSessionTokenReceived, }), ..router_data.clone() }), _ => Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::ApplePay(Box::new( payment_types::ApplepaySessionTokenResponse { session_token_data: None, payment_request_data: apple_pay_payment_request, connector: connector_name, delayed_session_token: delayed_response, sdk_next_action: { payment_types::SdkNextAction { next_action } }, connector_reference_id: None, connector_sdk_public_key: None, connector_merchant_id: None, }, )), }), ..router_data.clone() }), } } } } fn create_gpay_session_token( state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { // connector_wallet_details is being parse into admin types to check specifically if google_pay field is present // this is being done because apple_pay details from metadata is also being filled into connector_wallets_details let google_pay_wallets_details = router_data .connector_wallets_details .clone() .parse_value::<admin_types::ConnectorWalletDetails>("ConnectorWalletDetails") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .attach_printable(format!( "cannot parse connector_wallets_details from the given value {:?}", router_data.connector_wallets_details )) .map_err(|err| { logger::debug!( "Failed to parse connector_wallets_details for google_pay flow: {:?}", err ); }) .ok() .and_then(|connector_wallets_details| connector_wallets_details.google_pay); let connector_metadata = router_data.connector_meta_data.clone(); let delayed_response = is_session_response_delayed(state, connector); if delayed_response { Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::ThirdPartyResponse( payment_types::GooglePayThirdPartySdk { delayed_session_token: true, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, }, ), )), }), ..router_data.clone() }) } else { let is_billing_details_required = is_billing_address_required_to_be_collected_from_wallet( state, connector, business_profile, enums::PaymentMethodType::GooglePay, ); let required_amount_type = StringMajorUnitForConnector; let google_pay_amount = required_amount_type .convert( router_data.request.minor_amount, router_data.request.currency, ) .change_context(errors::ApiErrorResponse::PreconditionFailed { message: "Failed to convert amount to string major unit for googlePay".to_string(), })?; let session_data = router_data.request.clone(); let transaction_info = payment_types::GpayTransactionInfo { country_code: session_data.country.unwrap_or_default(), currency_code: router_data.request.currency, total_price_status: "Final".to_string(), total_price: google_pay_amount, }; let required_shipping_contact_fields = is_shipping_address_required_to_be_collected_form_wallet( state, connector, business_profile, enums::PaymentMethodType::GooglePay, ); if google_pay_wallets_details.is_some() { let gpay_data = router_data .connector_wallets_details .clone() .parse_value::<payment_types::GooglePayWalletDetails>("GooglePayWalletDetails") .change_context(errors::ConnectorError::NoConnectorWalletDetails) .attach_printable(format!( "cannot parse gpay connector_wallets_details from the given value {:?}", router_data.connector_wallets_details )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_wallets_details".to_string(), expected_format: "gpay_connector_wallets_details_format".to_string(), })?; let payment_types::GooglePayProviderDetails::GooglePayMerchantDetails(gpay_info) = gpay_data.google_pay.provider_details.clone(); let gpay_allowed_payment_methods = get_allowed_payment_methods_from_cards( gpay_data, &gpay_info.merchant_info.tokenization_specification, is_billing_details_required, )?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::GooglePaySession( payment_types::GooglePaySessionResponse { merchant_info: payment_types::GpayMerchantInfo { merchant_name: gpay_info.merchant_info.merchant_name, merchant_id: gpay_info.merchant_info.merchant_id, }, allowed_payment_methods: vec![gpay_allowed_payment_methods], transaction_info, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, delayed_session_token: false, secrets: None, shipping_address_required: required_shipping_contact_fields, // We pass Email as a required field irrespective of // collect_billing_details_from_wallet_connector or // collect_shipping_details_from_wallet_connector as it is common to both. email_required: required_shipping_contact_fields || is_billing_details_required, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: required_shipping_contact_fields, }, }, ), )), }), ..router_data.clone() }) } else { let billing_address_parameters = is_billing_details_required.then_some( payment_types::GpayBillingAddressParameters { phone_number_required: is_billing_details_required, format: payment_types::GpayBillingAddressFormat::FULL, }, ); let gpay_data = connector_metadata .clone() .parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData") .change_context(errors::ConnectorError::NoConnectorMetaData) .attach_printable(format!( "cannot parse gpay metadata from the given value {connector_metadata:?}" )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "gpay_metadata_format".to_string(), })?; let gpay_allowed_payment_methods = gpay_data .data .allowed_payment_methods .into_iter() .map( |allowed_payment_methods| payment_types::GpayAllowedPaymentMethods { parameters: payment_types::GpayAllowedMethodsParameters { billing_address_required: Some(is_billing_details_required), billing_address_parameters: billing_address_parameters.clone(), ..allowed_payment_methods.parameters }, ..allowed_payment_methods }, ) .collect(); Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::GooglePay(Box::new( payment_types::GpaySessionTokenResponse::GooglePaySession( payment_types::GooglePaySessionResponse { merchant_info: gpay_data.data.merchant_info, allowed_payment_methods: gpay_allowed_payment_methods, transaction_info, connector: connector.connector_name.to_string(), sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::Confirm, }, delayed_session_token: false, secrets: None, shipping_address_required: required_shipping_contact_fields, // We pass Email as a required field irrespective of // collect_billing_details_from_wallet_connector or // collect_shipping_details_from_wallet_connector as it is common to both. email_required: required_shipping_contact_fields || is_billing_details_required, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: required_shipping_contact_fields, }, }, ), )), }), ..router_data.clone() }) } } } /// Card Type for Google Pay Allowerd Payment Methods pub(crate) const CARD: &str = "CARD"; fn get_allowed_payment_methods_from_cards( gpay_info: payment_types::GooglePayWalletDetails, gpay_token_specific_data: &payment_types::GooglePayTokenizationSpecification, is_billing_details_required: bool, ) -> RouterResult<payment_types::GpayAllowedPaymentMethods> { let billing_address_parameters = is_billing_details_required.then_some(payment_types::GpayBillingAddressParameters { phone_number_required: is_billing_details_required, format: payment_types::GpayBillingAddressFormat::FULL, }); let protocol_version: Option<String> = gpay_token_specific_data .parameters .public_key .as_ref() .map(|_| PROTOCOL.to_string()); Ok(payment_types::GpayAllowedPaymentMethods { parameters: payment_types::GpayAllowedMethodsParameters { billing_address_required: Some(is_billing_details_required), billing_address_parameters: billing_address_parameters.clone(), ..gpay_info.google_pay.cards }, payment_method_type: CARD.to_string(), tokenization_specification: payment_types::GpayTokenizationSpecification { token_specification_type: gpay_token_specific_data.tokenization_type.to_string(), parameters: payment_types::GpayTokenParameters { protocol_version, public_key: gpay_token_specific_data.parameters.public_key.clone(), gateway: gpay_token_specific_data.parameters.gateway.clone(), gateway_merchant_id: gpay_token_specific_data .parameters .gateway_merchant_id .clone() .expose_option(), stripe_publishable_key: gpay_token_specific_data .parameters .stripe_publishable_key .clone() .expose_option(), stripe_version: gpay_token_specific_data .parameters .stripe_version .clone() .expose_option(), }, }, }) } fn is_session_response_delayed( state: &routes::SessionState, connector: &api::ConnectorData, ) -> bool { let connectors_with_delayed_response = &state .conf .delayed_session_response .connectors_with_delayed_session_response; connectors_with_delayed_response.contains(&connector.connector_name) } fn log_session_response_if_error( response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>, ) { if let Err(error) = response.as_ref() { logger::error!(?error); }; response .as_ref() .ok() .map(|res| res.as_ref().map_err(|error| logger::error!(?error))); } #[async_trait] pub trait RouterDataSession where Self: Sized, { async fn decide_flow<'a, 'b>( &'b self, state: &'a routes::SessionState, connector: &api::ConnectorData, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self>; } fn create_paypal_sdk_session_token( _state: &routes::SessionState, router_data: &types::PaymentsSessionRouterData, connector: &api::ConnectorData, _business_profile: &domain::Profile, ) -> RouterResult<types::PaymentsSessionRouterData> { let connector_metadata = router_data.connector_meta_data.clone(); let paypal_sdk_data = connector_metadata .clone() .parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData") .change_context(errors::ConnectorError::NoConnectorMetaData) .attach_printable(format!( "cannot parse paypal_sdk metadata from the given value {connector_metadata:?}" )) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "connector_metadata".to_string(), expected_format: "paypal_sdk_metadata_format".to_string(), })?; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::Paypal(Box::new( payment_types::PaypalSessionTokenResponse { connector: connector.connector_name.to_string(), session_token: paypal_sdk_data.data.client_id, sdk_next_action: payment_types::SdkNextAction { next_action: payment_types::NextActionCall::PostSessionTokens, }, client_token: None, transaction_info: None, }, )), }), ..router_data.clone() }) } async fn create_amazon_pay_session_token( router_data: &types::PaymentsSessionRouterData, state: &routes::SessionState, ) -> RouterResult<types::PaymentsSessionRouterData> { let amazon_pay_session_token_data = router_data .connector_wallets_details .clone() .parse_value::<payment_types::AmazonPaySessionTokenData>("AmazonPaySessionTokenData") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_id or store_id", })?; let amazon_pay_metadata = amazon_pay_session_token_data.data; let merchant_id = amazon_pay_metadata.merchant_id; let store_id = amazon_pay_metadata.store_id; let amazonpay_supported_currencies = payments::cards::list_countries_currencies_for_connector_payment_method_util( state.conf.pm_filters.clone(), enums::Connector::Amazonpay, enums::PaymentMethodType::AmazonPay, ) .await .currencies; // currently supports only the US region hence USD is the only supported currency payment_types::AmazonPayDeliveryOptions::validate_currency( router_data.request.currency, amazonpay_supported_currencies.clone(), ) .change_context(errors::ApiErrorResponse::CurrencyNotSupported { message: "USD is the only supported currency.".to_string(), })?; let ledger_currency = router_data.request.currency; // currently supports only the 'automatic' capture_method let payment_intent = payment_types::AmazonPayPaymentIntent::AuthorizeWithCapture; let required_amount_type = StringMajorUnitForConnector; let total_tax_amount = required_amount_type .convert( router_data.request.order_tax_amount.unwrap_or_default(), router_data.request.currency, ) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let total_base_amount = required_amount_type .convert( router_data.request.minor_amount, router_data.request.currency, ) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let delivery_options_request = router_data .request .metadata .clone() .and_then(|metadata| { metadata .expose() .get("delivery_options") .and_then(|value| value.as_array().cloned()) }) .ok_or(errors::ApiErrorResponse::MissingRequiredField { field_name: "metadata.delivery_options", })?; let mut delivery_options = payment_types::AmazonPayDeliveryOptions::parse_delivery_options_request( &delivery_options_request, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "delivery_options".to_string(), expected_format: r#""delivery_options": [{"id": String, "price": {"amount": Number, "currency_code": String}, "shipping_method":{"shipping_method_name": String, "shipping_method_code": String}, "is_default": Boolean}]"#.to_string(), })?; let default_amount = payment_types::AmazonPayDeliveryOptions::get_default_delivery_amount( delivery_options.clone(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "is_default", })?; for option in &delivery_options { payment_types::AmazonPayDeliveryOptions::validate_currency( option.price.currency_code, amazonpay_supported_currencies.clone(), ) .change_context(errors::ApiErrorResponse::CurrencyNotSupported { message: "USD is the only supported currency.".to_string(), })?; } payment_types::AmazonPayDeliveryOptions::insert_display_amount( &mut delivery_options, router_data.request.currency, ) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })?; let total_shipping_amount = match router_data.request.shipping_cost { Some(shipping_cost) => { if shipping_cost == default_amount { required_amount_type .convert(shipping_cost, router_data.request.currency) .change_context(errors::ApiErrorResponse::AmountConversionFailed { amount_type: "StringMajorUnit", })? } else { return Err(errors::ApiErrorResponse::InvalidDataValue { field_name: "shipping_cost", }) .attach_printable(format!( "Provided shipping_cost ({shipping_cost}) does not match the default delivery amount ({default_amount})" )); } } None => { return Err(errors::ApiErrorResponse::MissingRequiredField { field_name: "shipping_cost", } .into()); } }; Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::AmazonPay(Box::new( payment_types::AmazonPaySessionTokenResponse { merchant_id, ledger_currency, store_id, payment_intent, total_shipping_amount, total_tax_amount, total_base_amount, delivery_options, }, )), }), ..router_data.clone() }) } #[async_trait] impl RouterDataSession for types::PaymentsSessionRouterData { async fn decide_flow<'a, 'b>( &'b self, state: &'a routes::SessionState, connector: &api::ConnectorData, _confirm: Option<bool>, call_connector_action: payments::CallConnectorAction, business_profile: &domain::Profile, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<Self> { match connector.get_token { api::GetToken::GpayMetadata => { create_gpay_session_token(state, self, connector, business_profile) } api::GetToken::SamsungPayMetadata => create_samsung_pay_session_token( state, self, header_payload, connector, business_profile, ), api::GetToken::ApplePayMetadata => { create_applepay_session_token( state, self, connector, business_profile, header_payload, ) .await } api::GetToken::PaypalSdkMetadata => { create_paypal_sdk_session_token(state, self, connector, business_profile) } api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload), api::GetToken::Connector => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Session, types::PaymentsSessionData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, connector_integration, self, call_connector_action, None, None, ) .await .to_payment_failed_response()?; Ok(resp) } api::GetToken::AmazonPayMetadata => create_amazon_pay_session_token(self, state).await, } } }
{ "crate": "router", "file": "crates/router/src/core/payments/flows/session_flow.rs", "file_size": 61509, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-1202885729092151010
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/customers.rs // File size: 58261 bytes use common_utils::{ crypto::Encryptable, errors::ReportSwitchExt, ext_traits::AsyncExt, id_type, pii, type_name, types::{ keymanager::{Identifier, KeyManagerState, ToEncryptable}, Description, }, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::payment_methods as payment_methods_domain; use masking::{ExposeInterface, Secret, SwitchStrategy}; use payment_methods::controller::PaymentMethodsController; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] use crate::core::payment_methods::cards::create_encrypted_data; #[cfg(feature = "v1")] use crate::utils::CustomerAddress; use crate::{ core::{ errors::{self, StorageErrorExt}, payment_methods::{cards, network_tokenization}, utils::{ self, customer_validation::{CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT}, }, }, db::StorageInterface, pii::PeekInterface, routes::{metrics, SessionState}, services, types::{ api::customers, domain::{self, types}, storage::{self, enums}, transformers::ForeignFrom, }, }; pub const REDACTED: &str = "Redacted"; #[instrument(skip(state))] pub async fn create_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_data: customers::CustomerRequest, connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db: &dyn StorageInterface = state.store.as_ref(); let key_manager_state = &(&state).into(); let merchant_reference_id = customer_data.get_merchant_reference_id(); let merchant_id = merchant_context.get_merchant_account().get_id(); let merchant_reference_id_customer = MerchantReferenceIdForCustomer { merchant_reference_id: merchant_reference_id.as_ref(), merchant_id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; // We first need to validate whether the customer with the given customer id already exists // this may seem like a redundant db call, as the insert_customer will anyway return this error // // Consider a scenario where the address is inserted and then when inserting the customer, // it errors out, now the address that was inserted is not deleted merchant_reference_id_customer .verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db) .await?; let domain_customer = customer_data .create_domain_model_from_request( &connector_customer_details, db, &merchant_reference_id, &merchant_context, key_manager_state, &state, ) .await?; let customer = db .insert_customer( domain_customer, key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?; customer_data.generate_response(&customer) } #[async_trait::async_trait] trait CustomerCreateBridge { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { // Setting default billing address to Db let address = self.get_address(); let merchant_id = merchant_context.get_merchant_account().get_id(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let customer_billing_address_struct = AddressStructForDbEntry { address: address.as_ref(), customer_data: self, merchant_id, customer_id: merchant_reference_id.as_ref(), storage_scheme: merchant_context.get_merchant_account().storage_scheme, key_store: merchant_context.get_merchant_key_store(), key_manager_state, state, }; let address_from_db = customer_billing_address_struct .encrypt_customer_address_and_set_to_db(db) .await?; let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self.email.clone().map(|a| a.expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let connector_customer = connector_customer_details.as_ref().map(|details_vec| { let mut map = serde_json::Map::new(); for details in details_vec { let merchant_connector_id = details.merchant_connector_id.get_string_repr().to_string(); let connector_customer_id = details.connector_customer_id.clone(); map.insert(merchant_connector_id, connector_customer_id.into()); } pii::SecretSerdeValue::new(serde_json::Value::Object(map)) }); Ok(domain::Customer { customer_id: merchant_reference_id .to_owned() .ok_or(errors::CustomersErrorResponse::InternalServerError)?, merchant_id: merchant_id.to_owned(), name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), connector_customer, address_id: address_from_db.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, version: common_types::consts::API_VERSION, tax_registration_id: encryptable_customer.tax_registration_id, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerCreateBridge for customers::CustomerRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, _db: &'a dyn StorageInterface, merchant_reference_id: &'a Option<id_type::CustomerId>, merchant_context: &'a domain::MerchantContext, key_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_customer_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_customer_billing_address .async_map(|billing_address| { create_encrypted_data( key_state, merchant_context.get_merchant_key_store(), billing_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_customer_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_customer_shipping_address .async_map(|shipping_address| { create_encrypted_data( key_state, merchant_context.get_merchant_key_store(), shipping_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let merchant_id = merchant_context.get_merchant_account().get_id().clone(); let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: Some(self.name.clone()), email: Some(self.email.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch() .attach_printable("Failed while encrypting Customer")?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let connector_customer = connector_customer_details.as_ref().map(|details_vec| { let map: std::collections::HashMap<_, _> = details_vec .iter() .map(|details| { ( details.merchant_connector_id.clone(), details.connector_customer_id.to_string(), ) }) .collect(); common_types::customers::ConnectorCustomerMap::new(map) }); Ok(domain::Customer { id: id_type::GlobalCustomerId::generate(&state.conf.cell_information.id), merchant_reference_id: merchant_reference_id.to_owned(), merchant_id, name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: encryptable_customer.phone, description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), connector_customer, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), default_payment_method_id: None, updated_by: None, default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), version: common_types::consts::API_VERSION, status: common_enums::DeleteStatus::Active, tax_registration_id: encryptable_customer.tax_registration_id, }) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } #[cfg(feature = "v1")] struct AddressStructForDbEntry<'a> { address: Option<&'a api_models::payments::AddressDetails>, customer_data: &'a customers::CustomerRequest, merchant_id: &'a id_type::MerchantId, customer_id: Option<&'a id_type::CustomerId>, storage_scheme: common_enums::MerchantStorageScheme, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, } #[cfg(feature = "v1")] impl AddressStructForDbEntry<'_> { async fn encrypt_customer_address_and_set_to_db( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let encrypted_customer_address = self .address .async_map(|addr| async { self.customer_data .get_domain_address( self.state, addr.clone(), self.merchant_id, self.customer_id .ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point. self.key_store.key.get_inner().peek(), self.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address") }) .await .transpose()?; encrypted_customer_address .async_map(|encrypt_add| async { db.insert_address_for_customers(self.key_manager_state, encrypt_add, self.key_store) .await .switch() .attach_printable("Failed while inserting new address") }) .await .transpose() } } struct MerchantReferenceIdForCustomer<'a> { merchant_reference_id: Option<&'a id_type::CustomerId>, merchant_id: &'a id_type::MerchantId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v1")] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|cust| async { self.verify_if_merchant_reference_not_present_by_merchant_reference_id(cust, db) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference_id( &self, cus: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_customer_id_merchant_id( self.key_manager_state, cus, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(feature = "v2")] impl<'a> MerchantReferenceIdForCustomer<'a> { async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id( &self, db: &dyn StorageInterface, ) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> { self.merchant_reference_id .async_map(|merchant_ref| async { self.verify_if_merchant_reference_not_present_by_merchant_reference( merchant_ref, db, ) .await }) .await .transpose() } async fn verify_if_merchant_reference_not_present_by_merchant_reference( &self, merchant_ref: &'a id_type::CustomerId, db: &dyn StorageInterface, ) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> { match db .find_customer_by_merchant_reference_id_merchant_id( self.key_manager_state, merchant_ref, self.merchant_id, self.key_store, self.merchant_account.storage_scheme, ) .await { Err(err) => { if !err.current_context().is_db_not_found() { Err(err).switch() } else { Ok(()) } } Ok(_) => Err(report!( errors::CustomersErrorResponse::CustomerAlreadyExists )), } } } #[cfg(feature = "v1")] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_context: domain::MerchantContext, _profile_id: Option<id_type::ProfileId>, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( key_manager_state, &customer_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()? .ok_or(errors::CustomersErrorResponse::CustomerNotFound)?; let address = match &response.address_id { Some(address_id) => Some(api_models::payments::AddressDetails::from( db.find_address_by_address_id( key_manager_state, address_id, merchant_context.get_merchant_key_store(), ) .await .switch()?, )), None => None, }; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((response, address)), )) } #[cfg(feature = "v2")] #[instrument(skip(state))] pub async fn retrieve_customer( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::GlobalCustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let response = db .find_customer_by_global_id( key_manager_state, &id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(response), )) } #[instrument(skip(state))] pub async fn list_customers( state: SessionState, merchant_id: id_type::MerchantId, _profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, request: customers::CustomerListRequest, ) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> { let db = state.store.as_ref(); let customer_list_constraints = crate::db::customers::CustomerListConstraints { limit: request .limit .unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT), offset: request.offset, customer_id: request.customer_id, time_range: None, }; let domain_customers = db .list_customers_by_merchant_id( &(&state).into(), &merchant_id, &key_store, customer_list_constraints, ) .await .switch()?; #[cfg(feature = "v1")] let customers = domain_customers .into_iter() .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None))) .collect(); #[cfg(feature = "v2")] let customers = domain_customers .into_iter() .map(customers::CustomerResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json(customers)) } #[instrument(skip(state))] pub async fn list_customers_with_count( state: SessionState, merchant_id: id_type::MerchantId, _profile_id_list: Option<Vec<id_type::ProfileId>>, key_store: domain::MerchantKeyStore, request: customers::CustomerListRequestWithConstraints, ) -> errors::CustomerResponse<customers::CustomerListResponse> { let db = state.store.as_ref(); let limit = utils::customer_validation::validate_customer_list_limit(request.limit) .change_context(errors::CustomersErrorResponse::InvalidRequestData { message: format!( "limit should be between {CUSTOMER_LIST_LOWER_LIMIT} and {CUSTOMER_LIST_UPPER_LIMIT}" ), })?; let customer_list_constraints = crate::db::customers::CustomerListConstraints { limit: request.limit.unwrap_or(limit), offset: request.offset, customer_id: request.customer_id, time_range: request.time_range, }; let domain_customers = db .list_customers_by_merchant_id_with_count( &(&state).into(), &merchant_id, &key_store, customer_list_constraints, ) .await .switch()?; #[cfg(feature = "v1")] let customers: Vec<customers::CustomerResponse> = domain_customers .0 .into_iter() .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None))) .collect(); #[cfg(feature = "v2")] let customers: Vec<customers::CustomerResponse> = domain_customers .0 .into_iter() .map(customers::CustomerResponse::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( customers::CustomerListResponse { data: customers.into_iter().map(|c| c.0).collect(), total_count: domain_customers.1, }, )) } #[cfg(feature = "v2")] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_context: domain::MerchantContext, id: id_type::GlobalCustomerId, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); id.redact_customer_details_and_generate_response( db, &merchant_context, key_manager_state, &state, ) .await } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::GlobalCustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_global_id( key_manager_state, self, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let merchant_reference_id = customer_orig.merchant_reference_id.clone(); let customer_mandates = db.find_mandate_by_global_customer_id(self).await.switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_list_by_global_customer_id( key_manager_state, merchant_context.get_merchant_key_store(), self, None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::delete_card_by_locker_id( state, self, merchant_context.get_merchant_account().get_id(), ) .await .switch()?; } // No solution as of now, need to discuss this further with payment_method_v2 // db.delete_payment_method( // key_manager_state, // key_store, // pm, // ) // .await // .switch()?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let updated_customer = storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: Some(redacted_encrypted_value.clone()), email: Box::new(Some(redacted_encrypted_email)), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: None, connector_customer: Box::new(None), default_billing_address: None, default_shipping_address: None, default_payment_method_id: None, status: Some(common_enums::DeleteStatus::Redacted), tax_registration_id: Some(redacted_encrypted_value), })); db.update_customer_by_global_id( key_manager_state, self, customer_orig, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { id: self.clone(), merchant_reference_id, customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[async_trait::async_trait] trait CustomerDeleteBridge { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse>; } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn delete_customer( state: SessionState, merchant_context: domain::MerchantContext, customer_id: id_type::CustomerId, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let db = &*state.store; let key_manager_state = &(&state).into(); customer_id .redact_customer_details_and_generate_response( db, &merchant_context, key_manager_state, &state, ) .await } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerDeleteBridge for id_type::CustomerId { async fn redact_customer_details_and_generate_response<'a>( &'a self, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, ) -> errors::CustomerResponse<customers::CustomerDeleteResponse> { let customer_orig = db .find_customer_by_customer_id_merchant_id( key_manager_state, self, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let customer_mandates = db .find_mandate_by_merchant_id_customer_id( merchant_context.get_merchant_account().get_id(), self, ) .await .switch()?; for mandate in customer_mandates.into_iter() { if mandate.mandate_status == enums::MandateStatus::Active { Err(errors::CustomersErrorResponse::MandateActive)? } } match db .find_payment_method_by_customer_id_merchant_id_list( key_manager_state, merchant_context.get_merchant_key_store(), self, merchant_context.get_merchant_account().get_id(), None, ) .await { // check this in review Ok(customer_payment_methods) => { for pm in customer_payment_methods.into_iter() { if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) { cards::PmCards { state, merchant_context, } .delete_card_from_locker( self, merchant_context.get_merchant_account().get_id(), pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id), ) .await .switch()?; if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id { network_tokenization::delete_network_token_from_locker_and_token_service( state, self, merchant_context.get_merchant_account().get_id(), pm.payment_method_id.clone(), pm.network_token_locker_id, network_token_ref_id, merchant_context, ) .await .switch()?; } } db.delete_payment_method_by_merchant_id_payment_method_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().get_id(), &pm.payment_method_id, ) .await .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed to delete payment method while redacting customer details", )?; } } Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable( "failed find_payment_method_by_customer_id_merchant_id_list", ) }? } }; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let identifier = Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ); let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation( key_manager_state, type_name!(storage::Address), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .switch()?; let redacted_encrypted_email = Encryptable::new( redacted_encrypted_value .clone() .into_inner() .switch_strategy(), redacted_encrypted_value.clone().into_encrypted(), ); let update_address = storage::AddressUpdate::Update { city: Some(REDACTED.to_string()), country: None, line1: Some(redacted_encrypted_value.clone()), line2: Some(redacted_encrypted_value.clone()), line3: Some(redacted_encrypted_value.clone()), state: Some(redacted_encrypted_value.clone()), zip: Some(redacted_encrypted_value.clone()), first_name: Some(redacted_encrypted_value.clone()), last_name: Some(redacted_encrypted_value.clone()), phone_number: Some(redacted_encrypted_value.clone()), country_code: Some(REDACTED.to_string()), updated_by: merchant_context .get_merchant_account() .storage_scheme .to_string(), email: Some(redacted_encrypted_email), origin_zip: Some(redacted_encrypted_value.clone()), }; match db .update_address_by_merchant_id_customer_id( key_manager_state, self, merchant_context.get_merchant_account().get_id(), update_address, merchant_context.get_merchant_key_store(), ) .await { Ok(_) => Ok(()), Err(error) => { if error.current_context().is_db_not_found() { Ok(()) } else { Err(error) .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("failed update_address_by_merchant_id_customer_id") } } }?; let updated_customer = storage::CustomerUpdate::Update { name: Some(redacted_encrypted_value.clone()), email: Some( types::crypto_operation( key_manager_state, type_name!(storage::Customer), types::CryptoOperation::Encrypt(REDACTED.to_string().into()), identifier, key, ) .await .and_then(|val| val.try_into_operation()) .switch()?, ), phone: Box::new(Some(redacted_encrypted_value.clone())), description: Some(Description::from_str_unchecked(REDACTED)), phone_country_code: Some(REDACTED.to_string()), metadata: Box::new(None), connector_customer: Box::new(None), address_id: None, tax_registration_id: Some(redacted_encrypted_value.clone()), }; db.update_customer_by_customer_id_merchant_id( key_manager_state, self.clone(), merchant_context.get_merchant_account().get_id().to_owned(), customer_orig, updated_customer, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; let response = customers::CustomerDeleteResponse { customer_id: self.clone(), customer_deleted: true, address_deleted: true, payment_methods_deleted: true, }; metrics::CUSTOMER_REDACTED.add(1, &[]); Ok(services::ApplicationResponse::Json(response)) } } #[instrument(skip(state))] pub async fn update_customer( state: SessionState, merchant_context: domain::MerchantContext, update_customer: customers::CustomerUpdateRequestInternal, ) -> errors::CustomerResponse<customers::CustomerResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); //Add this in update call if customer can be updated anywhere else #[cfg(feature = "v1")] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { merchant_reference_id: &update_customer.customer_id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; #[cfg(feature = "v2")] let verify_id_for_update_customer = VerifyIdForUpdateCustomer { id: &update_customer.id, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, }; let customer = verify_id_for_update_customer .verify_id_and_get_customer_object(db) .await?; let updated_customer = update_customer .request .create_domain_model_from_request( &None, db, &merchant_context, key_manager_state, &state, &customer, ) .await?; update_customer.request.generate_response(&updated_customer) } #[async_trait::async_trait] trait CustomerUpdateBridge { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>; fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse>; } #[cfg(feature = "v1")] struct AddressStructForDbUpdate<'a> { update_customer: &'a customers::CustomerUpdateRequest, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, } #[cfg(feature = "v1")] impl AddressStructForDbUpdate<'_> { async fn update_address_if_sent( &self, db: &dyn StorageInterface, ) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> { let address = if let Some(addr) = &self.update_customer.address { match self.domain_customer.address_id.clone() { Some(address_id) => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let update_address = self .update_customer .get_address_update( self.state, customer_address, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, self.merchant_account.get_id().clone(), ) .await .switch() .attach_printable("Failed while encrypting Address while Update")?; Some( db.update_address( self.key_manager_state, address_id, update_address, self.key_store, ) .await .switch() .attach_printable(format!( "Failed while updating address: merchant_id: {:?}, customer_id: {:?}", self.merchant_account.get_id(), self.domain_customer.customer_id ))?, ) } None => { let customer_address: api_models::payments::AddressDetails = addr.clone(); let address = self .update_customer .get_domain_address( self.state, customer_address, self.merchant_account.get_id(), &self.domain_customer.customer_id, self.key_store.key.get_inner().peek(), self.merchant_account.storage_scheme, ) .await .switch() .attach_printable("Failed while encrypting address")?; Some( db.insert_address_for_customers( self.key_manager_state, address, self.key_store, ) .await .switch() .attach_printable("Failed while inserting new address")?, ) } } } else { match &self.domain_customer.address_id { Some(address_id) => Some( db.find_address_by_address_id( self.key_manager_state, address_id, self.key_store, ) .await .switch()?, ), None => None, } }; Ok(address) } } #[cfg(feature = "v1")] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { merchant_reference_id: &'a id_type::CustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v2")] #[derive(Debug)] struct VerifyIdForUpdateCustomer<'a> { id: &'a id_type::GlobalCustomerId, merchant_account: &'a domain::MerchantAccount, key_store: &'a domain::MerchantKeyStore, key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v1")] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_customer_id_merchant_id( self.key_manager_state, self.merchant_reference_id, self.merchant_account.get_id(), self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(feature = "v2")] impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, ) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> { let customer = db .find_customer_by_global_id( self.key_manager_state, self.id, self.key_store, self.merchant_account.storage_scheme, ) .await .switch()?; Ok(customer) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, _connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let update_address_for_update_customer = AddressStructForDbUpdate { update_customer: self, merchant_account: merchant_context.get_merchant_account(), key_store: merchant_context.get_merchant_key_store(), key_manager_state, state, domain_customer, }; let address = update_address_for_update_customer .update_address_if_sent(db) .await?; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_customer_id_merchant_id( key_manager_state, domain_customer.customer_id.to_owned(), merchant_context.get_merchant_account().get_id().to_owned(), domain_customer.to_owned(), storage::CustomerUpdate::Update { name: encryptable_customer.name, email: encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), phone: Box::new(encryptable_customer.phone), tax_registration_id: encryptable_customer.tax_registration_id, phone_country_code: self.phone_country_code.clone(), metadata: Box::new(self.metadata.clone()), description: self.description.clone(), connector_customer: Box::new(None), address_id: address.clone().map(|addr| addr.address_id), }, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { let address = self.get_address(); Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from((customer.clone(), address)), )) } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl CustomerUpdateBridge for customers::CustomerUpdateRequest { async fn create_domain_model_from_request<'a>( &'a self, connector_customer_details: &'a Option< Vec<payment_methods_domain::ConnectorCustomerDetails>, >, db: &'a dyn StorageInterface, merchant_context: &'a domain::MerchantContext, key_manager_state: &'a KeyManagerState, state: &'a SessionState, domain_customer: &'a domain::Customer, ) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> { let default_billing_address = self.get_default_customer_billing_address(); let encrypted_customer_billing_address = default_billing_address .async_map(|billing_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer billing address")?; let default_shipping_address = self.get_default_customer_shipping_address(); let encrypted_customer_shipping_address = default_shipping_address .async_map(|shipping_address| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), shipping_address, ) }) .await .transpose() .change_context(errors::CustomersErrorResponse::InternalServerError) .attach_printable("Unable to encrypt default customer shipping address")?; let key = merchant_context .get_merchant_key_store() .key .get_inner() .peek(); let encrypted_data = types::crypto_operation( key_manager_state, type_name!(domain::Customer), types::CryptoOperation::BatchEncrypt( domain::FromRequestEncryptableCustomer::to_encryptable( domain::FromRequestEncryptableCustomer { name: self.name.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), phone: self.phone.clone(), tax_registration_id: self.tax_registration_id.clone(), }, ), ), Identifier::Merchant( merchant_context .get_merchant_key_store() .merchant_id .clone(), ), key, ) .await .and_then(|val| val.try_into_batchoperation()) .switch()?; let encryptable_customer = domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) .change_context(errors::CustomersErrorResponse::InternalServerError)?; let response = db .update_customer_by_global_id( key_manager_state, &domain_customer.id, domain_customer.to_owned(), storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate { name: encryptable_customer.name, email: Box::new(encryptable_customer.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable })), phone: Box::new(encryptable_customer.phone), tax_registration_id: encryptable_customer.tax_registration_id, phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), description: self.description.clone(), connector_customer: Box::new(None), default_billing_address: encrypted_customer_billing_address.map(Into::into), default_shipping_address: encrypted_customer_shipping_address.map(Into::into), default_payment_method_id: Some(self.default_payment_method_id.clone()), status: None, })), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .switch()?; Ok(response) } fn generate_response<'a>( &'a self, customer: &'a domain::Customer, ) -> errors::CustomerResponse<customers::CustomerResponse> { Ok(services::ApplicationResponse::Json( customers::CustomerResponse::foreign_from(customer.clone()), )) } } pub async fn migrate_customers( state: SessionState, customers_migration: Vec<payment_methods_domain::PaymentMethodCustomerMigrate>, merchant_context: domain::MerchantContext, ) -> errors::CustomerResponse<()> { for customer_migration in customers_migration { match create_customer( state.clone(), merchant_context.clone(), customer_migration.customer, customer_migration.connector_customer_details, ) .await { Ok(_) => (), Err(e) => match e.current_context() { errors::CustomersErrorResponse::CustomerAlreadyExists => (), _ => return Err(e), }, } } Ok(services::ApplicationResponse::Json(())) }
{ "crate": "router", "file": "crates/router/src/core/customers.rs", "file_size": 58261, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_6309432663834079066
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/types.rs // File size: 57525 bytes // FIXME: Why were these data types grouped this way? // // Folder `types` is strange for Rust ecosystem, nevertheless it might be okay. // But folder `enum` is even more strange I unlikely okay. Why should not we introduce folders `type`, `structs` and `traits`? :) // Is it better to split data types according to business logic instead. // For example, customers/address/dispute/mandate is "models". // Separation of concerns instead of separation of forms. pub mod api; pub mod authentication; pub mod connector_transformers; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; pub mod payment_methods; pub mod pm_auth; use masking::Secret; pub mod storage; pub mod transformers; use std::marker::PhantomData; pub use api_models::{enums::Connector, mandates}; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v2")] use common_utils::errors::CustomResult; pub use common_utils::{pii, pii::Email, request::RequestContent, types::MinorUnit}; #[cfg(feature = "v2")] use error_stack::ResultExt; #[cfg(feature = "frm")] pub use hyperswitch_domain_models::router_data_v2::FrmFlowData; use hyperswitch_domain_models::router_flow_types::{ self, access_token_auth::AccessTokenAuth, dispute::{Accept, Defend, Dsync, Evidence, Fetch}, files::{Retrieve, Upload}, mandate_revoke::MandateRevoke, payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, CreateOrder, ExtendAuthorization, ExternalVaultProxy, IncrementalAuthorization, InitPayment, PSync, PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, }; pub use hyperswitch_domain_models::{ payment_address::PaymentAddress, router_data::{ AccessToken, AccessTokenAuthenticationResponse, AdditionalPaymentMethodConnectorResponse, ConnectorAuthType, ConnectorResponseData, ErrorResponse, GooglePayPaymentMethodDetails, GooglePayPredecryptDataInternal, L2L3Data, PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData, }, router_data_v2::{ AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData, ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData, RefundFlowData, RouterDataV2, UasFlowData, WebhookSourceVerifyData, }, router_request_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest, InvoiceRecordBackRequest, }, unified_authentication_service::{ UasAuthenticationRequestData, UasAuthenticationResponseData, UasConfirmationRequestData, UasPostAuthenticationRequestData, UasPreAuthenticationRequestData, }, AcceptDisputeRequestData, AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData, BrowserInformation, ChargeRefunds, ChargeRefundsOptions, CompleteAuthorizeData, CompleteAuthorizeRedirectResponse, ConnectorCustomerData, CreateOrderRequestData, DefendDisputeRequestData, DestinationChargeRefund, DirectChargeRefund, DisputeSyncData, ExternalVaultProxyPaymentsData, FetchDisputesRequestData, MandateRevokeRequestData, MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData, ResponseId, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, VaultRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ revenue_recovery::{ BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse, InvoiceRecordBackResponse, }, AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse, MandateReference, MandateRevokeResponseData, PaymentsResponseData, PreprocessingResponseId, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse, TaxCalculationResponseData, UploadFileResponse, VaultResponseData, VerifyWebhookSourceResponseData, VerifyWebhookStatus, }, }; #[cfg(feature = "payouts")] pub use hyperswitch_domain_models::{ router_data_v2::PayoutFlowData, router_request_types::PayoutsData, router_response_types::PayoutsResponseData, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ PayoutCancelType, PayoutCreateType, PayoutEligibilityType, PayoutFulfillType, PayoutQuoteType, PayoutRecipientAccountType, PayoutRecipientType, PayoutSyncType, }; pub use hyperswitch_interfaces::{ disputes::DisputePayload, types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, FetchDisputesType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostCaptureVoidType, PaymentsPostProcessingType, PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, RetrieveFileType, SdkSessionUpdateType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, VerifyWebhookSourceType, }, }; #[cfg(feature = "v2")] use crate::core::errors; pub use crate::core::payments::CustomerDetails; use crate::{ consts, core::payments::{OperationSessionGetters, PaymentData}, services, types::transformers::{ForeignFrom, ForeignTryFrom}, }; pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; pub type ExternalVaultProxyPaymentsRouterData = RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>; pub type PaymentsPreProcessingRouterData = RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>; pub type PaymentsPostProcessingRouterData = RouterData<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>; pub type PaymentsAuthorizeSessionTokenRouterData = RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsInitRouterData = RouterData<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsBalanceRouterData = RouterData<Balance, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsIncrementalAuthorizationRouterData = RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >; pub type PaymentsExtendAuthorizationRouterData = RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type CreateOrderRouterData = RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>; pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsPostSessionTokensRouterData = RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; pub type PaymentsUpdateMetadataRouterData = RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureRouterData = RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>; pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>; pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>; pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>; pub type TokenizationRouterData = RouterData< router_flow_types::PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData, >; pub type ConnectorCustomerRouterData = RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; pub type PaymentsResponseRouterData<R> = ResponseRouterData<Authorize, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsCancelResponseRouterData<R> = ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsCancelPostCaptureResponseRouterData<R> = ResponseRouterData<PostCaptureVoid, R, PaymentsCancelPostCaptureData, PaymentsResponseData>; pub type PaymentsExtendAuthorizationResponseRouterData<R> = ResponseRouterData< ExtendAuthorization, R, PaymentsExtendAuthorizationData, PaymentsResponseData, >; pub type PaymentsBalanceResponseRouterData<R> = ResponseRouterData<Balance, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type PaymentsSyncResponseRouterData<R> = ResponseRouterData<PSync, R, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsSessionResponseRouterData<R> = ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>; pub type PaymentsInitResponseRouterData<R> = ResponseRouterData<InitPayment, R, PaymentsAuthorizeData, PaymentsResponseData>; pub type SdkSessionUpdateResponseRouterData<R> = ResponseRouterData<SdkSessionUpdate, R, SdkPaymentsSessionUpdateData, PaymentsResponseData>; pub type PaymentsCaptureResponseRouterData<R> = ResponseRouterData<Capture, R, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsPreprocessingResponseRouterData<R> = ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>; pub type TokenizationResponseRouterData<R> = ResponseRouterData<PaymentMethodToken, R, PaymentMethodTokenizationData, PaymentsResponseData>; pub type ConnectorCustomerResponseRouterData<R> = ResponseRouterData<CreateConnectorCustomer, R, ConnectorCustomerData, PaymentsResponseData>; pub type RefundsResponseRouterData<F, R> = ResponseRouterData<F, R, RefundsData, RefundsResponseData>; pub type SetupMandateRouterData = RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; pub type AcceptDisputeRouterData = RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>; pub type VerifyWebhookSourceRouterData = RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >; pub type SubmitEvidenceRouterData = RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>; pub type UploadFileRouterData = RouterData<Upload, UploadFileRequestData, UploadFileResponse>; pub type RetrieveFileRouterData = RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>; pub type DefendDisputeRouterData = RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>; pub type FetchDisputesRouterData = RouterData<Fetch, FetchDisputesRequestData, FetchDisputesResponse>; pub type DisputeSyncRouterData = RouterData<Dsync, DisputeSyncData, DisputeSyncResponse>; pub type MandateRevokeRouterData = RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutsResponseRouterData<F, R> = ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>; #[cfg(feature = "payouts")] pub type PayoutActionData = Vec<( storage::Payouts, storage::PayoutAttempt, Option<domain::Customer>, Option<api_models::payments::Address>, )>; #[cfg(feature = "payouts")] pub trait PayoutIndividualDetailsExt { type Error; fn get_external_account_account_holder_type(&self) -> Result<String, Self::Error>; } pub trait Capturable { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { None } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _get_amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { None } } #[cfg(feature = "v1")] impl Capturable for PaymentsAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data.get_capture_method().unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } #[cfg(feature = "v1")] impl Capturable for PaymentsCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, _payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { Some(self.amount_to_capture) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Processing | common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } #[cfg(feature = "v1")] impl Capturable for CompleteAuthorizeData { fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { amount_captured.or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let amount_capturable_from_intent_status = match payment_data .get_capture_method() .unwrap_or_default() { common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::SequentialAutomatic => { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::Processing => None, } }, common_enums::CaptureMethod::Manual => Some(payment_data.payment_attempt.get_total_amount().get_amount_as_i64()), // In case of manual multiple, amount capturable must be inferred from all captures. common_enums::CaptureMethod::ManualMultiple | // Scheduled capture is not supported as of now common_enums::CaptureMethod::Scheduled => None, }; amount_capturable .or(amount_capturable_from_intent_status) .or(Some( payment_data .payment_attempt .get_total_amount() .get_amount_as_i64(), )) } } impl Capturable for SetupMandateRequestData {} impl Capturable for PaymentsTaxCalculationData {} impl Capturable for SdkPaymentsSessionUpdateData {} impl Capturable for PaymentsPostSessionTokensData {} impl Capturable for PaymentsUpdateMetadataData {} impl Capturable for PaymentsCancelData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None, } } } impl Capturable for PaymentsCancelPostCaptureData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => Some(0), common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Failed | common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } impl Capturable for PaymentsApproveData {} impl Capturable for PaymentsRejectData {} impl Capturable for PaymentsSessionData {} impl Capturable for PaymentsIncrementalAuthorizationData { fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, amount_capturable: Option<i64>, _attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { amount_capturable.or(Some(self.total_amount)) } } impl Capturable for PaymentsSyncData { #[cfg(feature = "v1")] fn get_captured_amount<F>( &self, amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { payment_data .payment_attempt .amount_to_capture .or(payment_data.payment_intent.amount_captured) .or(amount_captured.map(MinorUnit::new)) .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v2")] fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // TODO: add a getter for this payment_data .payment_attempt .amount_details .get_amount_to_capture() .or_else(|| Some(payment_data.payment_attempt.get_total_amount())) .map(|amt| amt.get_amount_as_i64()) } #[cfg(feature = "v1")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { amount_capturable.or(Some(MinorUnit::get_amount_as_i64( payment_data.payment_attempt.amount_capturable, ))) } } #[cfg(feature = "v2")] fn get_amount_capturable<F>( &self, payment_data: &PaymentData<F>, amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { if attempt_status.is_terminal_status() { Some(0) } else { None } } } impl Capturable for PaymentsExtendAuthorizationData { fn get_captured_amount<F>( &self, _amount_captured: Option<i64>, payment_data: &PaymentData<F>, ) -> Option<i64> where F: Clone, { // return previously captured amount payment_data .payment_intent .amount_captured .map(|amt| amt.get_amount_as_i64()) } fn get_amount_capturable<F>( &self, _payment_data: &PaymentData<F>, _amount_capturable: Option<i64>, attempt_status: common_enums::AttemptStatus, ) -> Option<i64> where F: Clone, { let intent_status = common_enums::IntentStatus::foreign_from(attempt_status); match intent_status { common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture | common_enums::IntentStatus::PartiallyCaptured | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Failed | common_enums::IntentStatus::Expired | common_enums::IntentStatus::Succeeded => Some(0), common_enums::IntentStatus::RequiresCustomerAction | common_enums::IntentStatus::RequiresMerchantAction | common_enums::IntentStatus::RequiresPaymentMethod | common_enums::IntentStatus::RequiresConfirmation | common_enums::IntentStatus::RequiresCapture | common_enums::IntentStatus::PartiallyCapturedAndCapturable | common_enums::IntentStatus::Processing | common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => None, } } } pub struct AddAccessTokenResult { pub access_token_result: Result<Option<AccessToken>, ErrorResponse>, pub connector_supports_access_token: bool, } pub struct PaymentMethodTokenResult { pub payment_method_token_result: Result<Option<String>, ErrorResponse>, pub is_payment_method_tokenization_performed: bool, pub connector_response: Option<ConnectorResponseData>, } #[derive(Clone)] pub struct CreateOrderResult { pub create_order_result: Result<String, ErrorResponse>, } pub struct PspTokenResult { pub token: Result<String, ErrorResponse>, } #[derive(Debug, Clone, Copy)] pub enum Redirection { Redirect, NoRedirect, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PollConfig { pub delay_in_secs: i8, pub frequency: i8, } impl PollConfig { pub fn get_poll_config_key(connector: String) -> String { format!("poll_config_external_three_ds_{connector}") } } impl Default for PollConfig { fn default() -> Self { Self { delay_in_secs: consts::DEFAULT_POLL_DELAY_IN_SECS, frequency: consts::DEFAULT_POLL_FREQUENCY, } } } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub business_profile: domain::Profile, } #[cfg(feature = "v2")] #[derive(Clone, Debug)] pub struct RedirectPaymentFlowResponse<D> { pub payment_data: D, pub profile: domain::Profile, } #[cfg(feature = "v1")] #[derive(Clone, Debug)] pub struct AuthenticatePaymentFlowResponse { pub payments_response: api_models::payments::PaymentsResponse, pub poll_config: PollConfig, pub business_profile: domain::Profile, } #[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)] pub struct ConnectorResponse { pub merchant_id: common_utils::id_type::MerchantId, pub connector: String, pub payment_id: common_utils::id_type::PaymentId, pub amount: i64, pub connector_transaction_id: String, pub return_url: Option<String>, pub three_ds_form: Option<services::RedirectForm>, } pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: RouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum RecipientIdType { ConnectorId(Secret<String>), LockerId(Secret<String>), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { Iban { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bacs { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, FasterPayments { account_number: Secret<String>, sort_code: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Sepa { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, SepaInstant { iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Elixir { account_number: Secret<String>, iban: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Bankgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, Plusgiro { number: Secret<String>, name: String, connector_recipient_id: Option<RecipientIdType>, }, } impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData { fn foreign_from(from: MerchantAccountData) -> Self { match from { MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: match connector_recipient_id { Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()), _ => None, }, }, } } } impl From<api_models::admin::MerchantAccountData> for MerchantAccountData { fn from(from: api_models::admin::MerchantAccountData) -> Self { match from { api_models::admin::MerchantAccountData::Iban { iban, name, connector_recipient_id, } => Self::Iban { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bacs { account_number, sort_code, name, connector_recipient_id, } => Self::Bacs { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::FasterPayments { account_number, sort_code, name, connector_recipient_id, } => Self::FasterPayments { account_number, sort_code, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Sepa { iban, name, connector_recipient_id, } => Self::Sepa { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::SepaInstant { iban, name, connector_recipient_id, } => Self::SepaInstant { iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Elixir { account_number, iban, name, connector_recipient_id, } => Self::Elixir { account_number, iban, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Bankgiro { number, name, connector_recipient_id, } => Self::Bankgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, api_models::admin::MerchantAccountData::Plusgiro { number, name, connector_recipient_id, } => Self::Plusgiro { number, name, connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId), }, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { ConnectorRecipientId(Secret<String>), WalletId(Secret<String>), AccountData(MerchantAccountData), } impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData { fn foreign_from(value: MerchantRecipientData) -> Self { match value { MerchantRecipientData::ConnectorRecipientId(id) => Self::ConnectorRecipientId(id), MerchantRecipientData::WalletId(id) => Self::WalletId(id), MerchantRecipientData::AccountData(data) => { Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data)) } } } } impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData { fn from(value: api_models::admin::MerchantRecipientData) -> Self { match value { api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Self::ConnectorRecipientId(id) } api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id), api_models::admin::MerchantRecipientData::AccountData(data) => { Self::AccountData(data.into()) } } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } impl ForeignFrom<api_models::admin::AdditionalMerchantData> for AdditionalMerchantData { fn foreign_from(value: api_models::admin::AdditionalMerchantData) -> Self { match value { api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData(MerchantRecipientData::from(data)) } } } } impl ForeignFrom<AdditionalMerchantData> for api_models::admin::AdditionalMerchantData { fn foreign_from(value: AdditionalMerchantData) -> Self { match value { AdditionalMerchantData::OpenBankingRecipientData(data) => { Self::OpenBankingRecipientData( api_models::admin::MerchantRecipientData::foreign_from(data), ) } } } } impl ForeignFrom<api_models::admin::ConnectorAuthType> for ConnectorAuthType { fn foreign_from(value: api_models::admin::ConnectorAuthType) -> Self { match value { api_models::admin::ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, api_models::admin::ConnectorAuthType::HeaderKey { api_key } => { Self::HeaderKey { api_key } } api_models::admin::ConnectorAuthType::BodyKey { api_key, key1 } => { Self::BodyKey { api_key, key1 } } api_models::admin::ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, api_models::admin::ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, api_models::admin::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } api_models::admin::ConnectorAuthType::NoKey => Self::NoKey, api_models::admin::ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType { fn foreign_from(from: ConnectorAuthType) -> Self { match from { ConnectorAuthType::TemporaryAuth => Self::TemporaryAuth, ConnectorAuthType::HeaderKey { api_key } => Self::HeaderKey { api_key }, ConnectorAuthType::BodyKey { api_key, key1 } => Self::BodyKey { api_key, key1 }, ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } => Self::SignatureKey { api_key, key1, api_secret, }, ConnectorAuthType::MultiAuthKey { api_key, key1, api_secret, key2, } => Self::MultiAuthKey { api_key, key1, api_secret, key2, }, ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { Self::CurrencyAuthKey { auth_key_map } } ConnectorAuthType::NoKey => Self::NoKey, ConnectorAuthType::CertificateAuth { certificate, private_key, } => Self::CertificateAuth { certificate, private_key, }, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ConnectorsList { pub connectors: Vec<String>, } impl ForeignFrom<&PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &PaymentsAuthorizeRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl ForeignFrom<&ExternalVaultProxyPaymentsRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &ExternalVaultProxyPaymentsRouterData) -> Self { Self { amount_to_capture: data.amount_captured, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: Some(data.request.amount), } } } impl<'a> ForeignFrom<&'a SetupMandateRouterData> for AuthorizeSessionTokenData { fn foreign_from(data: &'a SetupMandateRouterData) -> Self { Self { amount_to_capture: data.request.amount, currency: data.request.currency, connector_transaction_id: data.payment_id.clone(), amount: data.request.amount, } } } pub trait Tokenizable { fn set_session_token(&mut self, token: Option<String>); } impl Tokenizable for SetupMandateRequestData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for PaymentsAuthorizeData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl Tokenizable for CompleteAuthorizeData { fn set_session_token(&mut self, _token: Option<String>) {} } impl Tokenizable for ExternalVaultProxyPaymentsData { fn set_session_token(&mut self, token: Option<String>) { self.session_token = token; } } impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { fn foreign_from(data: &SetupMandateRouterData) -> Self { Self { currency: data.request.currency, payment_method_data: data.request.payment_method_data.clone(), confirm: data.request.confirm, statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(), mandate_id: data.request.mandate_id.clone(), setup_future_usage: data.request.setup_future_usage, off_session: data.request.off_session, setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), customer_name: data.request.customer_name.clone(), amount: 0, order_tax_amount: Some(MinorUnit::zero()), minor_amount: MinorUnit::new(0), statement_descriptor: None, capture_method: None, webhook_url: None, complete_authorize_url: None, browser_info: data.request.browser_info.clone(), order_details: None, order_category: None, session_token: None, enrolled_for_3ds: true, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: None, surcharge_details: None, request_incremental_authorization: data.request.request_incremental_authorization, metadata: None, request_extended_authorization: None, authentication_data: None, customer_acceptance: data.request.customer_acceptance.clone(), split_payments: None, // TODO: allow charges on mandates? merchant_order_reference_id: None, integrity_object: None, additional_payment_method_data: None, shipping_cost: data.request.shipping_cost, merchant_account_id: None, merchant_config_currency: None, connector_testing_data: data.request.connector_testing_data.clone(), order_id: None, locale: None, payment_channel: None, enable_partial_authorization: data.request.enable_partial_authorization, enable_overcapture: None, is_stored_credential: data.request.is_stored_credential, mit_category: None, } } } impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)> for RouterData<F2, T2, PaymentsResponseData> { fn foreign_from(item: (&RouterData<F1, T1, PaymentsResponseData>, T2)) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), #[cfg(feature = "payouts")] payout_method_data: data.payout_method_data.clone(), #[cfg(feature = "payouts")] quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_status: None, payment_method_balance: data.payment_method_balance.clone(), connector_api_version: data.connector_api_version.clone(), connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), dispute_id: data.dispute_id.clone(), refund_id: data.refund_id.clone(), connector_response: data.connector_response.clone(), integrity_check: Ok(()), additional_merchant_data: data.additional_merchant_data.clone(), header_payload: data.header_payload.clone(), connector_mandate_request_reference_id: data .connector_mandate_request_reference_id .clone(), authentication_id: data.authentication_id.clone(), psd2_sca_exemption_type: data.psd2_sca_exemption_type, raw_connector_response: data.raw_connector_response.clone(), is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: data.l2_l3_data.clone(), minor_amount_capturable: data.minor_amount_capturable, authorized_amount: data.authorized_amount, } } } #[cfg(feature = "payouts")] impl<F1, F2> ForeignFrom<( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, )> for RouterData<F2, PayoutsData, PayoutsResponseData> { fn foreign_from( item: ( &RouterData<F1, PayoutsData, PayoutsResponseData>, PayoutsData, ), ) -> Self { let data = item.0; let request = item.1; Self { flow: PhantomData, request, merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, payment_method_type: data.payment_method_type, connector_auth_type: data.connector_auth_type.clone(), description: data.description.clone(), address: data.address.clone(), auth_type: data.auth_type, connector_meta_data: data.connector_meta_data.clone(), connector_wallets_details: data.connector_wallets_details.clone(), amount_captured: data.amount_captured, minor_amount_captured: data.minor_amount_captured, access_token: data.access_token.clone(), response: data.response.clone(), payment_id: data.payment_id.clone(), session_token: data.session_token.clone(), reference_id: data.reference_id.clone(), customer_id: data.customer_id.clone(), payment_method_token: None, recurring_mandate_payment_data: None, preprocessing_id: None, connector_customer: data.connector_customer.clone(), connector_request_reference_id: data.connector_request_reference_id.clone(), payout_method_data: data.payout_method_data.clone(), quote_id: data.quote_id.clone(), test_mode: data.test_mode, payment_method_balance: None, payment_method_status: None, connector_api_version: None, connector_http_status_code: data.connector_http_status_code, external_latency: data.external_latency, apple_pay_flow: None, frm_metadata: None, refund_id: None, dispute_id: None, connector_response: data.connector_response.clone(), integrity_check: Ok(()), header_payload: data.header_payload.clone(), authentication_id: None, psd2_sca_exemption_type: None, additional_merchant_data: data.additional_merchant_data.clone(), connector_mandate_request_reference_id: None, raw_connector_response: None, is_payment_id_from_merchant: data.is_payment_id_from_merchant, l2_l3_data: None, minor_amount_capturable: None, authorized_amount: None, } } } #[cfg(feature = "v2")] impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata> for api_models::admin::MerchantConnectorAccountFeatureMetadata { fn foreign_from(item: &domain::MerchantConnectorAccountFeatureMetadata) -> Self { let revenue_recovery = item .revenue_recovery .as_ref() .map( |revenue_recovery_metadata| api_models::admin::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, billing_account_reference: revenue_recovery_metadata .mca_reference .recovery_to_billing .clone(), }, ); Self { revenue_recovery } } } #[cfg(feature = "v2")] impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata> for domain::MerchantConnectorAccountFeatureMetadata { type Error = errors::ApiErrorResponse; fn foreign_try_from( feature_metadata: &api_models::admin::MerchantConnectorAccountFeatureMetadata, ) -> Result<Self, Self::Error> { let revenue_recovery = feature_metadata .revenue_recovery .as_ref() .map(|revenue_recovery_metadata| { domain::AccountReferenceMap::new( revenue_recovery_metadata.billing_account_reference.clone(), ) .map(|mca_reference| domain::RevenueRecoveryMetadata { max_retry_count: revenue_recovery_metadata.max_retry_count, billing_connector_retry_threshold: revenue_recovery_metadata .billing_connector_retry_threshold, mca_reference, }) }) .transpose()?; Ok(Self { revenue_recovery }) } }
{ "crate": "router", "file": "crates/router/src/types.rs", "file_size": 57525, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_8030692834289367941
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/db/events.rs // File size: 56186 bytes use std::collections::HashSet; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait EventInterface where domain::Event: Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>, { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError>; } #[async_trait::async_trait] impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; event .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_idempotent_event_id( &conn, merchant_id, idempotent_event_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_primary_object_id( &conn, merchant_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_constraints( &conn, merchant_id, created_after, created_before, limit, offset, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_by_merchant_id_initial_attempt_id( &conn, merchant_id, initial_attempt_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_primary_object_id( &conn, profile_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_constraints( &conn, profile_id, created_after, created_before, limit, offset, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( merchant_key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::count_initial_attempts_by_constraints( &conn, merchant_id, profile_id, created_after, created_before, event_types, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl EventInterface for MockDb { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let stored_event = Conversion::convert(event) .await .change_context(errors::StorageError::EncryptionError)?; locked_events.push(stored_event.clone()); stored_event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and event_id = {event_id}" )) .into(), ) } async fn find_event_by_merchant_id_idempotent_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, idempotent_event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.idempotent_event_id == Some(idempotent_event_id.to_string()) }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and idempotent_event_id = {idempotent_event_id}" )) .into(), ) } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id == Some(initial_attempt_id.to_owned()) }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let event_to_update = locked_events .iter_mut() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .ok_or(errors::StorageError::MockDbError)?; match event { domain::EventUpdate::UpdateResponse { is_webhook_notified, response, } => { event_to_update.is_webhook_notified = is_webhook_notified; event_to_update.response = response.map(Into::into); } domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => { event_to_update.is_overall_delivery_successful = Some(is_overall_delivery_successful) } } event_to_update .clone() .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, event_types: HashSet<common_enums::EventType>, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let locked_events = self.events.lock().await; let iter_events = locked_events.iter().filter(|event| { let check = event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.merchant_id == Some(merchant_id.to_owned())) && (event.business_profile_id == profile_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event_types.is_empty() || event_types.contains(&event.event_type)) && (event.is_overall_delivery_successful == is_delivered); check }); let events = iter_events.cloned().collect::<Vec<_>>(); i64::try_from(events.len()) .change_context(errors::StorageError::MockDbError) .attach_printable("Failed to convert usize to i64") } } #[cfg(test)] mod tests { use std::sync::Arc; use api_models::webhooks as api_webhooks; use common_enums::IntentStatus; use common_utils::{ generate_organization_id_of_default_length, type_name, types::{keymanager::Identifier, MinorUnit}, }; use diesel_models::{ business_profile::WebhookDetails, enums::{self}, events::EventMetadata, }; use futures::future::join_all; use hyperswitch_domain_models::{ master_key::MasterKeyInterface, merchant_account::MerchantAccountSetter, }; use time::macros::datetime; use tokio::time::{timeout, Duration}; use crate::{ core::webhooks as webhooks_core, db::{events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MockDb}, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::{ api, domain::{self, MerchantAccount}, }, }; #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v1")] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::PaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v2")] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::GlobalPaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } #[cfg(feature = "v1")] #[allow(clippy::panic_in_result_fn)] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_concurrent_webhook_insertion_with_redis_lock( ) -> Result<(), Box<dyn std::error::Error>> { // Test concurrent webhook insertion with a Redis lock to prevent race conditions let conf = Settings::new()?; let tx: tokio::sync::oneshot::Sender<()> = tokio::sync::oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let tenant_id = common_utils::id_type::TenantId::try_from_string("public".to_string())?; let state = Arc::new(app_state) .get_session_state(&tenant_id, None, || {}) .map_err(|_| "failed to get session state")?; let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("juspay_merchant"))?; let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1"))?; let key_manager_state = &(&state).into(); let master_key = state.store.get_master_key(); let aes_key = services::generate_aes256_key()?; let merchant_key_store = state .store .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt(aes_key.to_vec().into()), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await? .try_into_operation()?, created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await?; let merchant_account_to_insert = MerchantAccount::from(MerchantAccountSetter { merchant_id: merchant_id.clone(), merchant_name: None, merchant_details: None, return_url: None, webhook_details: Some(WebhookDetails { webhook_version: None, webhook_username: None, webhook_password: None, webhook_url: Some(masking::Secret::new( "https://example.com/webhooks".to_string(), )), payment_created_enabled: None, payment_succeeded_enabled: Some(true), payment_failed_enabled: None, payment_statuses_enabled: None, refund_statuses_enabled: None, payout_statuses_enabled: None, multiple_webhooks_list: None, }), sub_merchants_enabled: None, parent_merchant_id: None, enable_payment_response_hash: true, payment_response_hash_key: None, redirect_to_merchant_with_http_post: false, publishable_key: "pk_test_11DviC2G2fb3lAJoes1q3A2222233327".to_string(), locker_id: None, storage_scheme: enums::MerchantStorageScheme::PostgresOnly, metadata: None, routing_algorithm: None, primary_business_details: serde_json::json!({ "country": "US", "business": "default" }), intent_fulfillment_time: Some(1), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), frm_routing_algorithm: None, payout_routing_algorithm: None, organization_id: generate_organization_id_of_default_length(), is_recon_enabled: true, default_profile: None, recon_status: enums::ReconStatus::NotRequested, payment_link_config: None, pm_collect_link_config: None, is_platform_account: false, merchant_account_type: common_enums::MerchantAccountType::Standard, product_type: None, version: common_enums::ApiVersion::V1, }); let merchant_account = state .store .insert_merchant( key_manager_state, merchant_account_to_insert, &merchant_key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account, merchant_key_store.clone(), ))); let merchant_id = merchant_id.clone(); // Clone merchant_id to avoid move let business_profile_to_insert = domain::Profile::from(domain::ProfileSetter { merchant_country_code: None, profile_id: business_profile_id.clone(), merchant_id: merchant_id.clone(), profile_name: "test_concurrent_profile".to_string(), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), return_url: None, enable_payment_response_hash: true, payment_response_hash_key: None, redirect_to_merchant_with_http_post: false, webhook_details: Some(WebhookDetails { webhook_version: None, webhook_username: None, webhook_password: None, webhook_url: Some(masking::Secret::new( "https://example.com/webhooks".to_string(), )), payment_created_enabled: None, payment_succeeded_enabled: Some(true), payment_failed_enabled: None, payment_statuses_enabled: None, refund_statuses_enabled: None, payout_statuses_enabled: None, multiple_webhooks_list: None, }), metadata: None, routing_algorithm: None, intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, is_recon_enabled: false, applepay_verified_domains: None, payment_link_config: None, session_expiry: None, authentication_connector_details: None, payout_link_config: None, is_extended_card_info_enabled: None, extended_card_info_config: None, is_connector_agnostic_mit_enabled: None, use_billing_as_payment_method_billing: None, collect_shipping_details_from_wallet_connector: None, collect_billing_details_from_wallet_connector: None, outgoing_webhook_custom_http_headers: None, always_collect_billing_details_from_wallet_connector: None, always_collect_shipping_details_from_wallet_connector: None, tax_connector_id: None, is_tax_connector_enabled: false, dynamic_routing_algorithm: None, is_network_tokenization_enabled: false, is_auto_retries_enabled: false, max_auto_retries_enabled: None, always_request_extended_authorization: None, is_click_to_pay_enabled: false, authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, is_clear_pan_retries_enabled: false, force_3ds_challenge: false, is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, is_pre_network_tokenization_enabled: false, merchant_category_code: None, dispute_polling_interval: None, is_manual_retry_enabled: None, always_enable_overcapture: None, external_vault_details: domain::ExternalVaultDetails::Skip, billing_processor_id: None, is_l2_l3_enabled: false, }); let business_profile = state .store .insert_business_profile( key_manager_state, &merchant_key_store.clone(), business_profile_to_insert, ) .await?; // Same inputs for all threads let event_type = enums::EventType::PaymentSucceeded; let event_class = enums::EventClass::Payments; let primary_object_id = Arc::new("concurrent_payment_id".to_string()); let primary_object_type = enums::EventObjectType::PaymentDetails; let payment_id = common_utils::id_type::PaymentId::try_from(std::borrow::Cow::Borrowed( "pay_mbabizu24mvu3mela5njyhpit10", ))?; let primary_object_created_at = Some(common_utils::date_time::now()); let expected_response = api::PaymentsResponse { payment_id, status: IntentStatus::Succeeded, amount: MinorUnit::new(6540), amount_capturable: MinorUnit::new(0), amount_received: None, client_secret: None, created: None, currency: "USD".to_string(), customer_id: None, description: Some("Its my first payment request".to_string()), refunds: None, mandate_id: None, merchant_id, net_amount: MinorUnit::new(6540), connector: None, customer: None, disputes: None, attempts: None, captures: None, mandate_data: None, setup_future_usage: None, off_session: None, capture_on: None, capture_method: None, payment_method: None, payment_method_data: None, payment_token: None, shipping: None, billing: None, order_details: None, email: None, name: None, phone: None, return_url: None, authentication_type: None, statement_descriptor_name: None, statement_descriptor_suffix: None, next_action: None, cancellation_reason: None, error_code: None, error_message: None, unified_code: None, unified_message: None, payment_experience: None, payment_method_type: None, connector_label: None, business_country: None, business_label: None, business_sub_label: None, allowed_payment_method_types: None, ephemeral_key: None, manual_retry_allowed: None, connector_transaction_id: None, frm_message: None, metadata: None, connector_metadata: None, feature_metadata: None, reference_id: None, payment_link: None, profile_id: None, surcharge_details: None, attempt_count: 1, merchant_decision: None, merchant_connector_id: None, incremental_authorization_allowed: None, authorization_count: None, incremental_authorizations: None, external_authentication_details: None, external_3ds_authentication_attempted: None, expires_on: None, fingerprint: None, browser_info: None, payment_method_id: None, payment_method_status: None, updated: None, split_payments: None, frm_metadata: None, merchant_order_reference_id: None, capture_before: None, extended_authorization_applied: None, order_tax_amount: None, connector_mandate_id: None, shipping_cost: None, card_discovery: None, mit_category: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, issuer_error_code: None, issuer_error_message: None, is_iframe_redirection_enabled: None, whole_connector_response: None, payment_channel: None, network_transaction_id: None, enable_partial_authorization: None, is_overcapture_enabled: None, enable_overcapture: None, network_details: None, is_stored_credential: None, request_extended_authorization: None, }; let content = api_webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(expected_response)); // Run 10 concurrent webhook creations let mut handles = vec![]; for _ in 0..10 { let state_clone = state.clone(); let merchant_context_clone = merchant_context.clone(); let business_profile_clone = business_profile.clone(); let content_clone = content.clone(); let primary_object_id_clone = primary_object_id.clone(); let handle = tokio::spawn(async move { webhooks_core::create_event_and_trigger_outgoing_webhook( state_clone, merchant_context_clone, business_profile_clone, event_type, event_class, (*primary_object_id_clone).to_string(), primary_object_type, content_clone, primary_object_created_at, ) .await .map_err(|e| format!("create_event_and_trigger_outgoing_webhook failed: {e}")) }); handles.push(handle); } // Await all tasks // We give the whole batch 20 s; if they don't finish something is wrong. let results = timeout(Duration::from_secs(20), join_all(handles)) .await .map_err(|_| "tasks hung for >20 s – possible dead-lock / endless retry")?; for res in results { // Any task that panicked or returned Err will make the test fail here. let _ = res.map_err(|e| format!("task panicked: {e}"))?; } // Collect all initial-attempt events for this payment let events = state .store .list_initial_events_by_merchant_id_primary_object_id( key_manager_state, &business_profile.merchant_id, &primary_object_id.clone(), merchant_context.get_merchant_key_store(), ) .await?; assert_eq!( events.len(), 1, "Expected exactly 1 row in events table, found {}", events.len() ); Ok(()) } }
{ "crate": "router", "file": "crates/router/src/db/events.rs", "file_size": 56186, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-7495256651845769483
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/utils.rs // File size: 54956 bytes pub mod chat; #[cfg(feature = "olap")] pub mod connector_onboarding; pub mod currency; pub mod db_utils; pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; #[cfg(feature = "olap")] pub mod user; #[cfg(feature = "olap")] pub mod user_role; #[cfg(feature = "olap")] pub mod verify_connector; use std::fmt::Debug; use api_models::{ enums, payments::{self}, webhooks, }; use common_utils::types::keymanager::KeyManagerState; pub use common_utils::{ crypto::{self, Encryptable}, ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt}, fp_utils::when, id_type, pii, validation::validate_email, }; #[cfg(feature = "v1")] use common_utils::{ type_name, types::keymanager::{Identifier, ToEncryptable}, }; use error_stack::ResultExt; pub use hyperswitch_connectors::utils::QrImage; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v1")] use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{ExposeInterface, SwitchStrategy}; use nanoid::nanoid; use serde::de::DeserializeOwned; use serde_json::Value; #[cfg(feature = "v1")] use subscriptions::subscription_handler::SubscriptionHandler; use tracing_futures::Instrument; pub use self::ext_traits::{OptionExt, ValidateCall}; use crate::{ consts, core::{ authentication::types::ExternalThreeDSConnectorMetadata, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payments as payments_core, }, headers::ACCEPT_LANGUAGE, logger, routes::{metrics, SessionState}, services::{self, authentication::get_header_value_by_key}, types::{self, domain, transformers::ForeignInto}, }; #[cfg(feature = "v1")] use crate::{core::webhooks as webhooks_core, types::storage}; pub mod error_parser { use std::fmt::Display; use actix_web::{ error::{Error, JsonPayloadError}, http::StatusCode, HttpRequest, ResponseError, }; #[derive(Debug)] struct CustomJsonError { err: JsonPayloadError, } // Display is a requirement defined by the actix crate for implementing ResponseError trait impl Display for CustomJsonError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str( serde_json::to_string(&serde_json::json!({ "error": { "error_type": "invalid_request", "message": self.err.to_string(), "code": "IR_06", } })) .as_deref() .unwrap_or("Invalid Json Error"), ) } } impl ResponseError for CustomJsonError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } pub fn custom_json_error_handler(err: JsonPayloadError, _req: &HttpRequest) -> Error { Error::from(CustomJsonError { err }) } } #[inline] pub fn generate_id(length: usize, prefix: &str) -> String { format!("{}_{}", prefix, nanoid!(length, &consts::ALPHABETS)) } pub trait ConnectorResponseExt: Sized { fn get_response(self) -> RouterResult<types::Response>; fn get_error_response(self) -> RouterResult<types::Response>; fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> { self.get_response()? .response .parse_struct(type_name) .change_context(errors::ApiErrorResponse::InternalServerError) } } impl<E> ConnectorResponseExt for Result<Result<types::Response, types::Response>, error_stack::Report<E>> { fn get_error_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Ok(res) => { logger::error!(response=?res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting error response, received response: {res:?}" )) } Err(err_res) => Ok(err_res), }) } fn get_response(self) -> RouterResult<types::Response> { self.map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError)) .attach_printable("Error while receiving response") .and_then(|inner| match inner { Err(err_res) => { logger::error!(error_response=?err_res); Err(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( "Expecting response, received error response: {err_res:?}" )) } Ok(res) => Ok(res), }) } } #[inline] pub fn get_payout_attempt_id(payout_id: &str, attempt_count: i16) -> String { format!("{payout_id}_{attempt_count}") } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_payment_id_type( state: &SessionState, payment_id_type: payments::PaymentIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let key_manager_state: KeyManagerState = state.into(); let db = &*state.store; match payment_id_type { payments::PaymentIdType::PaymentIntentId(payment_id) => db .find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound), payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => { let attempt = db .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_context.get_merchant_account().get_id(), &connector_transaction_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PaymentAttemptId(attempt_id) => { let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &key_manager_state, &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } payments::PaymentIdType::PreprocessingId(_) => { Err(errors::ApiErrorResponse::PaymentNotFound)? } } } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_refund_id_type( state: &SessionState, refund_id_type: webhooks::RefundIdType, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let refund = match refund_id_type { webhooks::RefundIdType::RefundId(id) => db .find_refund_by_merchant_id_refund_id( merchant_context.get_merchant_account().get_id(), &id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, webhooks::RefundIdType::ConnectorRefundId(id) => db .find_refund_by_merchant_id_connector_refund_id_connector( merchant_context.get_merchant_account().get_id(), &id, connector_name, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?, }; let attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &refund.attempt_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &attempt.payment_id, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_payment_intent_from_mandate_id_type( state: &SessionState, mandate_id_type: webhooks::MandateIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<PaymentIntent, errors::ApiErrorResponse> { let db = &*state.store; let mandate = match mandate_id_type { webhooks::MandateIdType::MandateId(mandate_id) => db .find_mandate_by_merchant_id_mandate_id( merchant_context.get_merchant_account().get_id(), mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db .find_mandate_by_merchant_id_connector_mandate_id( merchant_context.get_merchant_account().get_id(), connector_mandate_id.as_str(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?, }; db.find_payment_intent_by_payment_id_merchant_id( &state.into(), &mandate .original_payment_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("original_payment_id not present in mandate record")?, merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) } #[cfg(feature = "v1")] pub async fn find_mca_from_authentication_id_type( state: &SessionState, authentication_id_type: webhooks::AuthenticationIdType, merchant_context: &domain::MerchantContext, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let authentication = match authentication_id_type { webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db .find_authentication_by_merchant_id_authentication_id( merchant_context.get_merchant_account().get_id(), &authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?, webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => { db.find_authentication_by_merchant_id_connector_authentication_id( merchant_context.get_merchant_account().get_id().clone(), connector_authentication_id, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)? } }; #[cfg(feature = "v1")] { // raise error if merchant_connector_id is not present since it should we be present in the current flow let mca_id = authentication .merchant_connector_id .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("merchant_connector_id not present in authentication record")?; db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( &state.into(), merchant_context.get_merchant_account().get_id(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: mca_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] //get mca using id { let _ = key_store; let _ = authentication; todo!() } } #[cfg(feature = "v1")] pub async fn get_mca_from_payment_intent( state: &SessionState, merchant_context: &domain::MerchantContext, payment_intent: PaymentIntent, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let key_manager_state: &KeyManagerState = &state.into(); #[cfg(feature = "v1")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( &payment_intent.active_attempt.get_id(), merchant_context.get_merchant_account().get_id(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; #[cfg(feature = "v2")] let payment_attempt = db .find_payment_attempt_by_attempt_id_merchant_id( key_manager_state, key_store, &payment_intent.active_attempt.get_id(), merchant_account.get_id(), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; match payment_attempt.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = key_store; let _ = key_manager_state; let _ = connector_name; todo!() } } None => { let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")? .clone(); #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { //get mca using id let _ = profile_id; todo!() } } } } #[cfg(feature = "payouts")] pub async fn get_mca_from_payout_attempt( state: &SessionState, merchant_context: &domain::MerchantContext, payout_id_type: webhooks::PayoutIdType, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; let payout = match payout_id_type { webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_context.get_merchant_account().get_id(), &payout_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_context.get_merchant_account().get_id(), &connector_payout_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?, }; let key_manager_state: &KeyManagerState = &state.into(); match payout.merchant_connector_id { Some(merchant_connector_id) => { #[cfg(feature = "v1")] { db.find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_context.get_merchant_account().get_id(), &merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), }, ) } #[cfg(feature = "v2")] { //get mca using id let _id = merchant_connector_id; let _ = merchant_context.get_merchant_key_store(); let _ = connector_name; let _ = key_manager_state; todo!() } } None => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &payout.profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {}", payout.profile_id.get_string_repr(), connector_name ), }, ) } #[cfg(feature = "v2")] { todo!() } } } } #[cfg(feature = "v1")] pub async fn get_mca_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, merchant_context: &domain::MerchantContext, connector_name: &str, ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> { let db = &*state.store; #[cfg(feature = "v1")] let default_profile_id = merchant_context .get_merchant_account() .default_profile .as_ref(); #[cfg(feature = "v2")] let default_profile_id = Option::<&String>::None; match default_profile_id { Some(profile_id) => { #[cfg(feature = "v1")] { db.find_merchant_connector_account_by_profile_id_connector_name( &state.into(), profile_id, connector_name, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: format!( "profile_id {} and connector_name {connector_name}", profile_id.get_string_repr() ), }, ) } #[cfg(feature = "v2")] { let _db = db; let _profile_id = profile_id; todo!() } } _ => match object_reference_id { webhooks::ObjectReferenceId::PaymentId(payment_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_payment_id_type( state, payment_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::RefundId(refund_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_refund_id_type( state, refund_id_type, merchant_context, connector_name, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::MandateId(mandate_id_type) => { get_mca_from_payment_intent( state, merchant_context, find_payment_intent_from_mandate_id_type( state, mandate_id_type, merchant_context, ) .await?, connector_name, ) .await } webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) => { find_mca_from_authentication_id_type( state, authentication_id_type, merchant_context, ) .await } webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => { #[cfg(feature = "v1")] { let subscription_state = state.clone().into(); let subscription_handler = SubscriptionHandler::new(&subscription_state, merchant_context); let mut subscription_with_handler = subscription_handler .find_subscription(subscription_id_type) .await?; subscription_with_handler.get_mca(connector_name).await } #[cfg(feature = "v2")] { let _db = db; todo!() } } #[cfg(feature = "payouts")] webhooks::ObjectReferenceId::PayoutId(payout_id_type) => { get_mca_from_payout_attempt(state, merchant_context, payout_id_type, connector_name) .await } }, } } // validate json format for the error pub fn handle_json_response_deserialization_failure( res: types::Response, connector: &'static str, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { metrics::RESPONSE_DESERIALIZATION_FAILURE .add(1, router_env::metric_attributes!(("connector", connector))); let response_data = String::from_utf8(res.response.to_vec()) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; // check for whether the response is in json format match serde_json::from_str::<Value>(&response_data) { // in case of unexpected response but in json format Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?, // in case of unexpected response but in html or string format Err(error_msg) => { logger::error!(deserialization_error=?error_msg); logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data); Ok(types::ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(), reason: Some(response_data), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } } pub fn get_http_status_code_type( status_code: u16, ) -> CustomResult<String, errors::ApiErrorResponse> { let status_code_type = match status_code { 100..=199 => "1xx", 200..=299 => "2xx", 300..=399 => "3xx", 400..=499 => "4xx", 500..=599 => "5xx", _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid http status code")?, }; Ok(status_code_type.to_string()) } pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) { if let Some(status_code) = option_status_code { let status_code_type = get_http_status_code_type(status_code).ok(); match status_code_type.as_deref() { Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]), Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]), Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]), Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]), Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]), _ => logger::info!("Skip metrics as invalid http status code received from connector"), }; } else { logger::info!("Skip metrics as no http status code received from connector") } } #[cfg(feature = "v1")] #[async_trait::async_trait] pub trait CustomerAddress { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>; async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError>; } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl CustomerAddress for api_models::customers::CustomerUpdateRequest { async fn get_address_update( &self, state: &SessionState, address_details: payments::AddressDetails, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, merchant_id: id_type::MerchantId, ) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(storage::AddressUpdate::Update { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }) } async fn get_domain_address( &self, state: &SessionState, address_details: payments::AddressDetails, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, key: &[u8], storage_scheme: storage::enums::MerchantStorageScheme, ) -> CustomResult<domain::CustomerAddress, common_utils::errors::CryptoError> { let encrypted_data = crypto_operation( &state.into(), type_name!(storage::Address), CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable( domain::FromRequestEncryptableAddress { line1: address_details.line1.clone(), line2: address_details.line2.clone(), line3: address_details.line3.clone(), state: address_details.state.clone(), first_name: address_details.first_name.clone(), last_name: address_details.last_name.clone(), zip: address_details.zip.clone(), phone_number: self.phone.clone(), email: self .email .as_ref() .map(|a| a.clone().expose().switch_strategy()), origin_zip: address_details.origin_zip.clone(), }, )), Identifier::Merchant(merchant_id.to_owned()), key, ) .await .and_then(|val| val.try_into_batchoperation())?; let encryptable_address = domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { city: address_details.city, country: address_details.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, zip: encryptable_address.zip, state: encryptable_address.state, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: self.phone_country_code.clone(), merchant_id: merchant_id.to_owned(), address_id: generate_id(consts::ID_LENGTH, "add"), created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), updated_by: storage_scheme.to_string(), email: encryptable_address.email.map(|email| { let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), origin_zip: encryptable_address.origin_zip, }; Ok(domain::CustomerAddress { address, customer_id: customer_id.to_owned(), }) } } pub fn add_apple_pay_flow_metrics( apple_pay_flow: &Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } pub fn add_apple_pay_payment_status_metrics( payment_attempt_status: enums::AttemptStatus, apple_pay_flow: Option<domain::ApplePayFlow>, connector: Option<String>, merchant_id: id_type::MerchantId, ) { if payment_attempt_status == enums::AttemptStatus::Charged { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT .add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } else if payment_attempt_status == enums::AttemptStatus::Failure { if let Some(flow) = apple_pay_flow { match flow { domain::ApplePayFlow::Simplified(_) => { metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ) } domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add( 1, router_env::metric_attributes!( ( "connector", connector.to_owned().unwrap_or("null".to_string()), ), ("merchant_id", merchant_id.clone()), ), ), } } } } pub fn check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata( metadata: Option<Value>, ) -> bool { let external_three_ds_connector_metadata: Option<ExternalThreeDSConnectorMetadata> = metadata .parse_value("ExternalThreeDSConnectorMetadata") .map_err(|err| logger::warn!(parsing_error=?err,"Error while parsing ExternalThreeDSConnectorMetadata")) .ok(); external_three_ds_connector_metadata .and_then(|metadata| metadata.pull_mechanism_for_external_3ds_enabled) .unwrap_or(true) } #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_account: domain::MerchantAccount, business_profile: domain::Profile, key_store: &domain::MerchantKeyStore, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { todo!() } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn trigger_payments_webhook<F, Op, D>( merchant_context: domain::MerchantContext, business_profile: domain::Profile, payment_data: D, customer: Option<domain::Customer>, state: &SessionState, operation: Op, ) -> RouterResult<()> where F: Send + Clone + Sync, Op: Debug, D: payments_core::OperationSessionGetters<F>, { let status = payment_data.get_payment_intent().status; let should_trigger_webhook = business_profile .get_payment_webhook_statuses() .contains(&status); if should_trigger_webhook { let captures = payment_data .get_multiple_capture_data() .map(|multiple_capture_data| { multiple_capture_data .get_all_captures() .into_iter() .cloned() .collect() }); let payment_id = payment_data.get_payment_intent().get_id().to_owned(); let payments_response = crate::core::payments::transformers::payments_to_payments_response( payment_data, captures, customer, services::AuthFlow::Merchant, &state.base_url, &operation, &state.conf.connector_request_reference_id_config, None, None, None, )?; let event_type = status.into(); if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) = payments_response { let cloned_state = state.clone(); // This spawns this futures in a background thread, the exception inside this future won't affect // the current thread and the lifecycle of spawn thread is not handled by runtime. // So when server shutdown won't wait for this thread's completion. if let Some(event_type) = event_type { tokio::spawn( async move { let primary_object_created_at = payments_response_json.created; Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, merchant_context.clone(), business_profile, event_type, diesel_models::enums::EventClass::Payments, payment_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PaymentDetails, webhooks::OutgoingWebhookContent::PaymentDetails(Box::new( payments_response_json, )), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!( "Outgoing webhook not sent because of missing event type status mapping" ); } } } Ok(()) } type Handle<T> = tokio::task::JoinHandle<RouterResult<T>>; pub async fn flatten_join_error<T>(handle: Handle<T>) -> RouterResult<T> { match handle.await { Ok(Ok(t)) => Ok(t), Ok(Err(err)) => Err(err), Err(err) => Err(err) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Join Error"), } } #[cfg(feature = "v1")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, ) -> RouterResult<()> { let refund_status = refund.refund_status; let key_manager_state = &(state).into(); let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), &profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let should_trigger_webhook = business_profile .get_refund_webhook_statuses() .contains(&refund_status); if should_trigger_webhook { let event_type = refund_status.into(); let refund_response: api_models::refunds::RefundResponse = refund.clone().foreign_into(); let refund_id = refund_response.refund_id.clone(); let cloned_state = state.clone(); let cloned_merchant_context = merchant_context.clone(); let primary_object_created_at = refund_response.created_at; if let Some(outgoing_event_type) = event_type { tokio::spawn( async move { Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, cloned_merchant_context, business_profile, outgoing_event_type, diesel_models::enums::EventClass::Refunds, refund_id.to_string(), diesel_models::enums::EventObjectType::RefundDetails, webhooks::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!("Outgoing webhook not sent because of missing event type status mapping"); }; } Ok(()) } #[cfg(feature = "v2")] pub async fn trigger_refund_outgoing_webhook( state: &SessionState, merchant_account: &domain::MerchantAccount, refund: &diesel_models::Refund, profile_id: id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { todo!() } pub fn get_locale_from_header(headers: &actix_web::http::header::HeaderMap) -> String { get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers) .ok() .flatten() .map(|val| val.to_string()) .unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()) } #[cfg(all(feature = "payouts", feature = "v1"))] pub async fn trigger_payouts_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, payout_response: &api_models::payouts::PayoutCreateResponse, ) -> RouterResult<()> { let key_manager_state = &(state).into(); let profile_id = &payout_response.profile_id; let business_profile = state .store .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let status = &payout_response.status; let should_trigger_webhook = business_profile .get_payout_webhook_statuses() .contains(status); if should_trigger_webhook { let event_type = (*status).into(); if let Some(event_type) = event_type { let cloned_merchant_context = merchant_context.clone(); let cloned_state = state.clone(); let cloned_response = payout_response.clone(); // This spawns this futures in a background thread, the exception inside this future won't affect // the current thread and the lifecycle of spawn thread is not handled by runtime. // So when server shutdown won't wait for this thread's completion. tokio::spawn( async move { let primary_object_created_at = cloned_response.created; Box::pin(webhooks_core::create_event_and_trigger_outgoing_webhook( cloned_state, cloned_merchant_context, business_profile, event_type, diesel_models::enums::EventClass::Payouts, cloned_response.payout_id.get_string_repr().to_owned(), diesel_models::enums::EventObjectType::PayoutDetails, webhooks::OutgoingWebhookContent::PayoutDetails(Box::new(cloned_response)), primary_object_created_at, )) .await } .in_current_span(), ); } else { logger::warn!("Outgoing webhook not sent because of missing event type status mapping"); } } Ok(()) } #[cfg(all(feature = "payouts", feature = "v2"))] pub async fn trigger_payouts_webhook( state: &SessionState, merchant_context: &domain::MerchantContext, payout_response: &api_models::payouts::PayoutCreateResponse, ) -> RouterResult<()> { todo!() }
{ "crate": "router", "file": "crates/router/src/utils.rs", "file_size": 54956, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-9146544046283768386
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/routes/payment_methods.rs // File size: 54766 bytes use ::payment_methods::{ controller::PaymentMethodsController, core::{migration, migration::payment_methods::migrate_payment_method}, }; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; use hyperswitch_domain_models::{ bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore, payment_methods::PaymentMethodCustomerMigrate, transformers::ForeignTryFrom, }; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] use crate::core::{customers, payment_methods::tokenize}; use crate::{ core::{ api_locking, errors::{self, utils::StorageErrorExt}, payment_methods::{self as payment_methods_routes, cards, migration as update_migration}, }, services::{self, api, authentication as auth, authorization::permissions::Permission}, types::{ api::payment_methods::{self, PaymentMethodId}, domain, storage::payment_method::PaymentTokenData, }, }; #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(cards::get_client_secret_or_add_payment_method( &state, req, &merchant_context, )) .await }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, req_state| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payment_methods_routes::create_payment_method( &state, &req_state, req, &merchant_context, &auth.profile, )) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))] pub async fn create_payment_method_intent_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsCreate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(payment_methods_routes::payment_method_intent_create( &state, req, &merchant_context, )) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } /// This struct is used internally only #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, pub request: payment_methods::PaymentMethodIntentConfirm, } #[cfg(feature = "v2")] impl From<PaymentMethodIntentConfirmInternal> for payment_methods::PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { item.request } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: Some(self.request.payment_method_type), payment_method_subtype: Some(self.request.payment_method_subtype), }) } } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::update_payment_method( state, merchant_context, auth.profile, req, &payment_method_id, ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] pub async fn payment_method_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsRetrieve; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::retrieve_payment_method(state, pm, merchant_context) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] pub async fn payment_method_delete_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsDelete; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::delete_payment_method(state, pm, merchant_context, auth.profile) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodMigrate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsMigrate; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); Box::pin(migrate_payment_method( &(&state).into(), req, &merchant_id, &merchant_context, &cards::PmCards { state: &state, merchant_context: &merchant_context, }, )) .await }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } async fn get_merchant_account( state: &SessionState, merchant_id: &id_type::MerchantId, ) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let merchant_account = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; Ok((key_store, merchant_account)) } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_methods( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<migration::PaymentMethodsMigrateForm>, ) -> HttpResponse { let flow = Flow::PaymentMethodsMigrate; let (merchant_id, records, merchant_connector_ids) = match form.validate_and_get_payment_method_records() { Ok((merchant_id, records, merchant_connector_ids)) => { (merchant_id, records, merchant_connector_ids) } Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); let merchant_connector_ids = merchant_connector_ids.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; // Create customers if they are not already present let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store.clone()), )); let mut mca_cache = std::collections::HashMap::new(); let customers = Vec::<PaymentMethodCustomerMigrate>::foreign_try_from(( &req, merchant_id.clone(), )) .map_err(|e| errors::ApiErrorResponse::InvalidRequestData { message: e.to_string(), })?; for record in &customers { if let Some(connector_customer_details) = &record.connector_customer_details { for connector_customer in connector_customer_details { if !mca_cache.contains_key(&connector_customer.merchant_connector_id) { let mca = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &(&state).into(), &merchant_id, &connector_customer.merchant_connector_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_customer.merchant_connector_id.get_string_repr().to_string(), }, )?; mca_cache .insert(connector_customer.merchant_connector_id.clone(), mca); } } } } customers::migrate_customers(state.clone(), customers, merchant_context.clone()) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; let controller = cards::PmCards { state: &state, merchant_context: &merchant_context, }; Box::pin(migration::migrate_payment_methods( &(&state).into(), req, &merchant_id, &merchant_context, merchant_connector_ids, &controller, )) .await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsBatchUpdate))] pub async fn update_payment_methods( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<update_migration::PaymentMethodsUpdateForm>, ) -> HttpResponse { let flow = Flow::PaymentMethodsBatchUpdate; let (merchant_id, records) = match form.validate_and_get_payment_method_records() { Ok((merchant_id, records)) => (merchant_id, records), Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account.clone(), key_store.clone()), )); Box::pin(update_migration::update_payment_methods( &state, req, &merchant_id, &merchant_context, )) .await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))] pub async fn save_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCreate>, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodSave; let payload = json_payload.into_inner(); let pm_id = path.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); Box::pin(cards::add_payment_method_data( state, req, merchant_context, pm_id.clone(), )) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] pub async fn list_payment_method_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodsList; let payload = json_payload.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { // TODO (#7195): Fill platform_merchant_account in the client secret auth and pass it here. let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::list_payment_methods(state, merchant_context, req) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<AppState>, customer_id: web::Path<(id_type::CustomerId,)>, req: HttpRequest, query_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner().0; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::do_list_customer_pm_fetch_customer_if_not_passed( state, merchant_context, Some(req), Some(&customer_id), None, ) }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api_client( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let api_key = auth::get_api_key(req.headers()).ok(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _, is_ephemeral_auth) = match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth) .await { Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::do_list_customer_pm_fetch_customer_if_not_passed( state, merchant_context, Some(req), None, is_ephemeral_auth.then_some(api_key).flatten(), ) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } /// Generate a form link for collecting payment methods for a customer #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))] pub async fn initiate_pm_collect_link_flow( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::PaymentMethodCollectLinkRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodCollectLink; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::initiate_pm_collect_link(state, merchant_context, req) }, &auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<AppState>, customer_id: web::Path<id_type::GlobalCustomerId>, req: HttpRequest, query_payload: web::Query<api_models::payment_methods::ListMethodsForPaymentMethodsRequest>, ) -> HttpResponse { let flow = Flow::CustomerPaymentMethodsList; let payload = query_payload.into_inner(); let customer_id = customer_id.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::list_saved_payment_methods_for_customer( state, merchant_context, customer_id.clone(), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::GetPaymentMethodTokenData))] pub async fn get_payment_method_token_data( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, json_payload: web::Json<api_models::payment_methods::GetTokenDataRequest>, ) -> HttpResponse { let flow = Flow::GetPaymentMethodTokenData; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { payment_methods_routes::get_token_data_for_payment_method( state, auth.merchant_account, auth.key_store, auth.profile, req, payment_method_id.clone(), ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v2", feature = "olap"))] #[instrument(skip_all, fields(flow = ?Flow::TotalPaymentMethodCount))] pub async fn get_total_payment_method_count( state: web::Data<AppState>, req: HttpRequest, ) -> HttpResponse { let flow = Flow::TotalPaymentMethodCount; Box::pin(api::server_wrap( flow, state, &req, (), |state, auth: auth::AuthenticationData, _, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::get_total_saved_payment_methods_for_merchant( state, merchant_context, ) }, auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::MerchantCustomerRead, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] /// Generate a form link for collecting payment methods for a customer #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodCollectLink))] pub async fn render_pm_collect_link( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(id_type::MerchantId, String)>, ) -> HttpResponse { let flow = Flow::PaymentMethodCollectLink; let (merchant_id, pm_collect_link_id) = path.into_inner(); let payload = payment_methods::PaymentMethodCollectLinkRenderRequest { merchant_id: merchant_id.clone(), pm_collect_link_id, }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::render_pm_collect_link(state, merchant_context, req) }, &auth::MerchantIdAuth(merchant_id), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] pub async fn payment_method_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let flow = Flow::PaymentMethodsRetrieve; let payload = web::Json(PaymentMethodId { payment_method_id: path.into_inner(), }) .into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, pm, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::PmCards { state: &state, merchant_context: &merchant_context, } .retrieve_payment_method(pm) .await }, &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<payment_methods::PaymentMethodUpdate>, ) -> HttpResponse { let flow = Flow::PaymentMethodsUpdate; let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); let api_auth = auth::ApiKeyAuth::default(); let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) { Ok((auth, _auth_flow)) => (auth, _auth_flow), Err(e) => return api::log_and_return_error_response(e), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::update_customer_payment_method(state, merchant_context, req, &payment_method_id) }, &*auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] pub async fn payment_method_delete_api( state: web::Data<AppState>, req: HttpRequest, payment_method_id: web::Path<(String,)>, ) -> HttpResponse { let flow = Flow::PaymentMethodsDelete; let pm = PaymentMethodId { payment_method_id: payment_method_id.into_inner().0, }; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, pm, |state, auth: auth::AuthenticationData, req, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); cards::PmCards { state: &state, merchant_context: &merchant_context, } .delete_payment_method(req) .await }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] pub async fn list_countries_currencies_for_connector_payment_method( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, ) -> HttpResponse { let flow = Flow::ListCountriesCurrencies; let payload = query_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method( state, req, auth.profile_id, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }), &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileConnectorWrite, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ListCountriesCurrencies))] pub async fn list_countries_currencies_for_connector_payment_method( state: web::Data<AppState>, req: HttpRequest, query_payload: web::Query<payment_methods::ListCountriesCurrenciesRequest>, ) -> HttpResponse { let flow = Flow::ListCountriesCurrencies; let payload = query_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::list_countries_currencies_for_connector_payment_method( state, req, Some(auth.profile.get_id().clone()), ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileConnectorRead, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileConnectorRead, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::DefaultPaymentMethodsSet))] pub async fn default_payment_method_set_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<payment_methods::DefaultPaymentMethod>, ) -> HttpResponse { let flow = Flow::DefaultPaymentMethodsSet; let payload = path.into_inner(); let pc = payload.clone(); let customer_id = &pc.customer_id; let api_auth = auth::ApiKeyAuth::default(); let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, default_payment_method, _| async move { let merchant_id = auth.merchant_account.get_id(); cards::PmCards { state: &state, merchant_context: &domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account.clone(), auth.key_store), )), } .set_default_payment_method( merchant_id, customer_id, default_payment_method.payment_method_id, ) .await }, &*ephemeral_auth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use api_models::payment_methods::PaymentMethodListRequest; use super::*; // #[test] // fn test_custom_list_deserialization() { // let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true"; // let de_query: web::Query<PaymentMethodListRequest> = // web::Query::from_query(dummy_data).unwrap(); // let de_struct = de_query.into_inner(); // assert_eq!(de_struct.installment_payment_enabled, Some(true)) // } #[test] fn test_custom_list_deserialization_multi_amount() { let dummy_data = "amount=120&recurring_enabled=true&amount=1000"; let de_query: Result<web::Query<PaymentMethodListRequest>, _> = web::Query::from_query(dummy_data); assert!(de_query.is_err()) } } #[derive(Clone)] pub struct ParentPaymentMethodToken { key_for_token: String, } impl ParentPaymentMethodToken { pub fn create_key_for_token( (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod), ) -> Self { Self { key_for_token: format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch"), } } #[cfg(feature = "v2")] pub fn return_key_for_token( (parent_pm_token, payment_method): (&String, api_models::enums::PaymentMethod), ) -> String { format!("pm_token_{parent_pm_token}_{payment_method}_hyperswitch") } pub async fn insert( &self, fulfillment_time: i64, token: PaymentTokenData, state: &SessionState, ) -> CustomResult<(), errors::ApiErrorResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn .serialize_and_set_key_with_expiry( &self.key_for_token.as_str().into(), token, fulfillment_time, ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add token in redis")?; Ok(()) } pub fn should_delete_payment_method_token(&self, status: IntentStatus) -> bool { // RequiresMerchantAction: When the payment goes for merchant review incase of potential fraud allow payment_method_token to be stored until resolved ![ IntentStatus::RequiresCustomerAction, IntentStatus::RequiresMerchantAction, ] .contains(&status) } pub async fn delete(&self, state: &SessionState) -> CustomResult<(), errors::ApiErrorResponse> { let redis_conn = state .store .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; match redis_conn .delete_key(&self.key_for_token.as_str().into()) .await { Ok(_) => Ok(()), Err(err) => { { logger::info!("Error while deleting redis key: {:?}", err) }; Ok(()) } } } } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCard))] pub async fn tokenize_card_api( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, ) -> HttpResponse { let flow = Flow::TokenizeCard; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(cards::tokenize_card_flow( &state, CardNetworkTokenizeRequest::foreign_from(req), &merchant_context, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCardUsingPaymentMethodId))] pub async fn tokenize_card_using_pm_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, ) -> HttpResponse { let flow = Flow::TokenizeCardUsingPaymentMethodId; let pm_id = path.into_inner(); let mut payload = json_payload.into_inner(); if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) = payload.data { pm_data.payment_method_id = pm_id; } else { return api::log_and_return_error_response(error_stack::report!( errors::ApiErrorResponse::InvalidDataValue { field_name: "card" } )); } Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| async move { let merchant_id = req.merchant_id.clone(); let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); let res = Box::pin(cards::tokenize_card_flow( &state, CardNetworkTokenizeRequest::foreign_from(req), &merchant_context, )) .await?; Ok(services::ApplicationResponse::Json(res)) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(feature = "v1", any(feature = "olap", feature = "oltp")))] #[instrument(skip_all, fields(flow = ?Flow::TokenizeCardBatch))] pub async fn tokenize_card_batch_api( state: web::Data<AppState>, req: HttpRequest, MultipartForm(form): MultipartForm<tokenize::CardNetworkTokenizeForm>, ) -> HttpResponse { let flow = Flow::TokenizeCardBatch; let (merchant_id, records) = match tokenize::get_tokenize_card_form_records(form) { Ok(res) => res, Err(e) => return api::log_and_return_error_response(e.into()), }; Box::pin(api::server_wrap( flow, state, &req, records, |state, _, req, _| { let merchant_id = merchant_id.clone(); async move { let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(merchant_account, key_store), )); Box::pin(tokenize::tokenize_cards(&state, req, &merchant_context)).await } }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))] pub async fn payment_methods_session_create( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionCreate; let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, request, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_create(state, merchant_context, request) .await }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdate))] pub async fn payment_methods_session_update( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json<api_models::payment_methods::PaymentMethodsSessionUpdateRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionUpdate; let payment_method_session_id = path.into_inner(); let payload = json_payload.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payload, |state, auth: auth::AuthenticationData, req, _| { let value = payment_method_session_id.clone(); async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_update( state, merchant_context, value.clone(), req, ) .await } }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionRetrieve))] pub async fn payment_methods_session_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionRetrieve; let payment_method_session_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_session_id.clone(), |state, auth: auth::AuthenticationData, payment_method_session_id, _| async move { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_retrieve( state, merchant_context, payment_method_session_id, ) .await }, auth::api_or_client_auth( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), req.headers(), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))] pub async fn payment_method_session_list_payment_methods( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, ) -> HttpResponse { let flow = Flow::PaymentMethodsList; let payment_method_session_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_session_id.clone(), |state, auth: auth::AuthenticationData, payment_method_session_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::list_payment_methods_for_session( state, merchant_context, auth.profile, payment_method_session_id, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize)] struct PaymentMethodsSessionGenericRequest<T: serde::Serialize> { payment_method_session_id: id_type::GlobalPaymentMethodSessionId, #[serde(flatten)] request: T, } #[cfg(feature = "v2")] impl<T: serde::Serialize> common_utils::events::ApiEventMetric for PaymentMethodsSessionGenericRequest<T> { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::PaymentMethodSession { payment_method_session_id: self.payment_method_session_id.clone(), }) } } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionConfirm))] pub async fn payment_method_session_confirm( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json<api_models::payment_methods::PaymentMethodSessionConfirmRequest>, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionConfirm; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, req_state| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_confirm( state, req_state, merchant_context, auth.profile, request.payment_method_session_id, request.request, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] pub async fn payment_method_session_update_saved_payment_method( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json< api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod, >, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionUpdateSavedPaymentMethod; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_update_payment_method( state, merchant_context, auth.profile, request.payment_method_session_id, request.request, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionUpdateSavedPaymentMethod))] pub async fn payment_method_session_delete_saved_payment_method( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodSessionId>, json_payload: web::Json< api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod, >, ) -> HttpResponse { let flow = Flow::PaymentMethodSessionDeleteSavedPaymentMethod; let payload = json_payload.into_inner(); let payment_method_session_id = path.into_inner(); let request = PaymentMethodsSessionGenericRequest { payment_method_session_id: payment_method_session_id.clone(), request: payload, }; Box::pin(api::server_wrap( flow, state, &req, request, |state, auth: auth::AuthenticationData, request, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::payment_methods_session_delete_payment_method( state, merchant_context, auth.profile, request.request.payment_method_id, request.payment_method_session_id, ) }, &auth::V2ClientAuth( common_utils::types::authentication::ResourceId::PaymentMethodSession( payment_method_session_id, ), ), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::NetworkTokenStatusCheck))] pub async fn network_token_status_check_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<id_type::GlobalPaymentMethodId>, ) -> HttpResponse { let flow = Flow::NetworkTokenStatusCheck; let payment_method_id = path.into_inner(); Box::pin(api::server_wrap( flow, state, &req, payment_method_id, |state, auth: auth::AuthenticationData, payment_method_id, _| { let merchant_context = domain::MerchantContext::NormalMerchant(Box::new( domain::Context(auth.merchant_account, auth.key_store), )); payment_methods_routes::check_network_token_status( state, merchant_context, payment_method_id, ) }, &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, api_locking::LockAction::NotApplicable, )) .await }
{ "crate": "router", "file": "crates/router/src/routes/payment_methods.rs", "file_size": 54766, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_-572386502009961840
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/core/refunds_v2.rs // File size: 52978 bytes use std::{fmt::Debug, str::FromStr}; use api_models::{enums::Connector, refunds::RefundErrorDetails}; use common_utils::{id_type, types as common_utils_types}; use diesel_models::refund as diesel_refund; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ refunds::RefundListConstraints, router_data::{ErrorResponse, RouterData}, router_data_v2::RefundFlowData, }; use hyperswitch_interfaces::{ api::{Connector as ConnectorTrait, ConnectorIntegration}, connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2}, integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject}, }; use router_env::{instrument, tracing}; use crate::{ consts, core::{ errors::{self, ConnectorErrorExt, StorageErrorExt}, payments::{self, access_token, helpers}, utils::{self as core_utils, refunds_validator}, }, db, logger, routes::{metrics, SessionState}, services, types::{ self, api::{self, refunds}, domain, storage::{self, enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils, }; #[instrument(skip_all)] pub async fn refund_create_core( state: SessionState, merchant_context: domain::MerchantContext, req: refunds::RefundsCreateRequest, global_refund_id: id_type::GlobalRefundId, ) -> errors::RouterResponse<refunds::RefundResponse> { let db = &*state.store; let (payment_intent, payment_attempt, amount); payment_intent = db .find_payment_intent_by_id( &(&state).into(), &req.payment_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; utils::when( !(payment_intent.status == enums::IntentStatus::Succeeded || payment_intent.status == enums::IntentStatus::PartiallyCaptured), || { Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState { current_flow: "refund".into(), field_name: "status".into(), current_value: payment_intent.status.to_string(), states: "succeeded, partially_captured".to_string() }) .attach_printable("unable to refund for a unsuccessful payment intent")) }, )?; let captured_amount = payment_intent .amount_captured .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("amount captured is none in a successful payment")?; // Amount is not passed in request refer from payment intent. amount = req.amount.unwrap_or(captured_amount); utils::when(amount <= common_utils_types::MinorUnit::new(0), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "amount".to_string(), expected_format: "positive integer".to_string() }) .attach_printable("amount less than or equal to zero")) })?; payment_attempt = db .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id( &(&state).into(), merchant_context.get_merchant_key_store(), &req.payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?; tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr()); let merchant_connector_details = req.merchant_connector_details.clone(); Box::pin(validate_and_create_refund( &state, &merchant_context, &payment_attempt, &payment_intent, amount, req, global_refund_id, merchant_connector_details, )) .await .map(services::ApplicationResponse::Json) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let mca = db .find_merchant_connector_account_by_id( &state.into(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account")?; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())), ); let connector_enum = mca.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, Some(mca_id.clone()), )?; refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca)); let mut router_data = core_utils::construct_refund_router_data( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; logger::debug!(refund_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await; let refund_update = get_refund_update_object( state, &connector, &storage_scheme, merchant_context, &connector_response, ) .await; let response = match refund_update { Some(refund_update) => state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.id.get_string_repr() ) })?, None => refund.to_owned(), }; // Implement outgoing webhooks here connector_response.to_refund_failed_response()?; Ok(response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn internal_trigger_refund_to_gateway( state: &SessionState, refund: &diesel_refund::Refund, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails, ) -> errors::RouterResult<diesel_refund::Refund> { let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let routed_through = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve connector from payment attempt")?; metrics::REFUND_COUNT.add( 1, router_env::metric_attributes!(("connector", routed_through.clone())), ); let connector_enum = merchant_connector_details.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, None, )?; refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); let mut router_data = core_utils::construct_refund_router_data( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await; let refund_update = get_refund_update_object( state, &connector, &storage_scheme, merchant_context, &connector_response, ) .await; let response = match refund_update { Some(refund_update) => state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Failed while updating refund: refund_id: {}", refund.id.get_string_repr() ) })?, None => refund.to_owned(), }; // Implement outgoing webhooks here connector_response.to_refund_failed_response()?; Ok(response) } async fn call_connector_service<F>( state: &SessionState, connector: &api::ConnectorData, add_access_token_result: types::AddAccessTokenResult, router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> Result< RouterData<F, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, > where F: Debug + Clone + 'static, dyn ConnectorTrait + Sync: ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>, dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>, { if !(add_access_token_result.connector_supports_access_token && router_data.access_token.is_none()) { let connector_integration: services::BoxedRefundConnectorIntegrationInterface< F, types::RefundsData, types::RefundsResponseData, > = connector.connector.get_connector_integration(); services::execute_connector_processing_step( state, connector_integration, &router_data, payments::CallConnectorAction::Trigger, None, None, ) .await } else { Ok(router_data) } } async fn get_refund_update_object( state: &SessionState, connector: &api::ConnectorData, storage_scheme: &enums::MerchantStorageScheme, merchant_context: &domain::MerchantContext, router_data_response: &Result< RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, error_stack::Report<errors::ConnectorError>, >, ) -> Option<diesel_refund::RefundUpdate> { match router_data_response { // This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself. Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme), Ok(response) => { let response = perform_integrity_check(response.clone()); match response.response.clone() { Err(err) => Some( get_connector_error_refund_update(state, err, connector, storage_scheme).await, ), Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data( response, connector, refund_response_data, storage_scheme, merchant_context, )), } } } } fn get_connector_implementation_error_refund_update( error: &error_stack::Report<errors::ConnectorError>, storage_scheme: enums::MerchantStorageScheme, ) -> Option<diesel_refund::RefundUpdate> { Option::<diesel_refund::RefundUpdate>::foreign_from((error.current_context(), storage_scheme)) } async fn get_connector_error_refund_update( state: &SessionState, err: ErrorResponse, connector: &api::ConnectorData, storage_scheme: &enums::MerchantStorageScheme, ) -> diesel_refund::RefundUpdate { let unified_error_object = get_unified_error_and_message(state, &err, connector).await; diesel_refund::RefundUpdate::build_error_update_for_unified_error_and_message( unified_error_object, err.reason.or(Some(err.message)), Some(err.code), storage_scheme, ) } async fn get_unified_error_and_message( state: &SessionState, err: &ErrorResponse, connector: &api::ConnectorData, ) -> (String, String) { let option_gsm = helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::REFUND_FLOW_STR.to_string(), ) .await; // Note: Some connectors do not have a separate list of refund errors // In such cases, the error codes and messages are stored under "Authorize" flow in GSM table // So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow" let option_gsm = if option_gsm.is_none() { helpers::get_gsm_record( state, Some(err.code.clone()), Some(err.message.clone()), connector.connector_name.to_string(), consts::AUTHORIZE_FLOW_STR.to_string(), ) .await } else { option_gsm }; let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()); let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message); match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) { Some((code, message)) => (code.to_owned(), message.to_owned()), None => ( consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(), consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(), ), } } pub fn get_refund_update_for_refund_response_data( router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>, connector: &api::ConnectorData, refund_response_data: types::RefundsResponseData, storage_scheme: &enums::MerchantStorageScheme, merchant_context: &domain::MerchantContext, ) -> diesel_refund::RefundUpdate { // match on connector integrity checks match router_data.integrity_check.clone() { Err(err) => { let connector_refund_id = err .connector_transaction_id .map(common_utils_types::ConnectorTransactionId::from); metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ( "merchant_id", merchant_context.get_merchant_account().get_id().clone() ), ), ); diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure( err.field_names, connector_refund_id, storage_scheme, ) } Ok(()) => { if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success { metrics::SUCCESSFUL_REFUND.add( 1, router_env::metric_attributes!(( "connector", connector.connector_name.to_string(), )), ) } let connector_refund_id = common_utils_types::ConnectorTransactionId::from( refund_response_data.connector_refund_id, ); diesel_refund::RefundUpdate::build_refund_update( connector_refund_id, refund_response_data.refund_status, storage_scheme, ) } } } pub fn perform_integrity_check<F>( mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>, ) -> RouterData<F, types::RefundsData, types::RefundsResponseData> where F: Debug + Clone + 'static, { // Initiating Integrity check let integrity_result = check_refund_integrity(&router_data.request, &router_data.response); router_data.integrity_check = integrity_result; router_data } impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)> for Option<diesel_refund::RefundUpdate> { fn foreign_from( (from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme), ) -> Self { match from { errors::ConnectorError::NotImplemented(message) => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some( errors::ConnectorError::NotImplemented(message.to_owned()).to_string(), ), refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, }) } errors::ConnectorError::NotSupported { message, connector } => { Some(diesel_refund::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::Failure), refund_error_message: Some(format!( "{message} is not supported by {connector}" )), refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, processor_refund_data: None, unified_code: None, unified_message: None, }) } _ => None, } } } pub fn check_refund_integrity<T, Request>( request: &Request, refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>, ) -> Result<(), common_utils::errors::IntegrityCheckError> where T: FlowIntegrity, Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>, { let connector_refund_id = refund_response_data .as_ref() .map(|resp_data| resp_data.connector_refund_id.clone()) .ok(); request.check_integrity(request, connector_refund_id.to_owned()) } // ********************************************** REFUND UPDATE ********************************************** pub async fn refund_metadata_update_core( state: SessionState, merchant_account: domain::MerchantAccount, req: refunds::RefundMetadataUpdateRequest, global_refund_id: id_type::GlobalRefundId, ) -> errors::RouterResponse<refunds::RefundResponse> { let db = state.store.as_ref(); let refund = db .find_refund_by_id(&global_refund_id, merchant_account.storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = db .update_refund( refund, diesel_refund::RefundUpdate::MetadataAndReasonUpdate { metadata: req.metadata, reason: req.reason, updated_by: merchant_account.storage_scheme.to_string(), }, merchant_account.storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", global_refund_id.get_string_repr() ) })?; refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) } // ********************************************** REFUND SYNC ********************************************** #[instrument(skip_all)] pub async fn refund_retrieve_core_with_refund_id( state: SessionState, merchant_context: domain::MerchantContext, profile: domain::Profile, request: refunds::RefundsRetrieveRequest, ) -> errors::RouterResponse<refunds::RefundResponse> { let refund_id = request.refund_id.clone(); let db = &*state.store; let profile_id = profile.get_id().to_owned(); let refund = db .find_refund_by_id( &refund_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let response = Box::pin(refund_retrieve_core( state.clone(), merchant_context, Some(profile_id), request, refund, )) .await?; api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json) } #[instrument(skip_all)] pub async fn refund_retrieve_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<id_type::ProfileId>, request: refunds::RefundsRetrieveRequest, refund: diesel_refund::Refund, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let key_manager_state = &(&state).into(); core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?; let payment_id = &refund.payment_id; let payment_intent = db .find_payment_intent_by_id( key_manager_state, payment_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let active_attempt_id = payment_intent .active_attempt_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Active attempt id not found")?; let payment_attempt = db .find_payment_attempt_by_id( key_manager_state, merchant_context.get_merchant_key_store(), &active_attempt_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; let unified_translated_message = if let (Some(unified_code), Some(unified_message)) = (refund.unified_code.clone(), refund.unified_message.clone()) { helpers::get_unified_translation( &state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)) } else { refund.unified_message }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) { if state.conf.merchant_id_auth.merchant_id_auth_enabled { let merchant_connector_details = match request.merchant_connector_details { Some(details) => details, None => { return Err(report!(errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_details" })); } }; Box::pin(internal_sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, merchant_connector_details, )) .await } else { Box::pin(sync_refund_with_gateway( &state, &merchant_context, &payment_attempt, &payment_intent, &refund, )) .await } } else { Ok(refund) }?; Ok(response) } fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool { // This implies, we cannot perform a refund sync & `the connector_refund_id` // doesn't exist let predicate1 = refund.connector_refund_id.is_some(); // This allows refund sync at connector level if force_sync is enabled, or // checks if the refund has failed let predicate2 = force_sync || !matches!( refund.refund_status, diesel_models::enums::RefundStatus::Failure | diesel_models::enums::RefundStatus::Success ); predicate1 && predicate2 } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let connector_id = refund.connector.to_string(); let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_id, api::GetToken::Connector, payment_attempt.merchant_connector_id.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get the connector")?; let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?; let mca = db .find_merchant_connector_account_by_id( &state.into(), &mca_id, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch merchant connector account")?; let connector_enum = mca.connector_name; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca)); let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; logger::debug!(refund_retrieve_router_data=?router_data); access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await .to_refund_failed_response()?; let connector_response = perform_integrity_check(connector_response); let refund_update = build_refund_update_for_rsync(&connector, merchant_context, connector_response); let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.id.get_string_repr() ) })?; // Implement outgoing webhook here Ok(response) } #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] pub async fn internal_sync_refund_with_gateway( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund: &diesel_refund::Refund, merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails, ) -> errors::RouterResult<diesel_refund::Refund> { let connector_enum = merchant_connector_details.connector_name; let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &connector_enum.to_string(), api::GetToken::Connector, None, )?; let merchant_connector_account = domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails( merchant_connector_details, ); let mut router_data = core_utils::construct_refund_router_data::<api::RSync>( state, connector_enum, merchant_context, payment_intent, payment_attempt, refund, &merchant_connector_account, ) .await?; let add_access_token_result = Box::pin(access_token::add_access_token( state, &connector, merchant_context, &router_data, None, )) .await?; access_token::update_router_data_with_access_token_result( &add_access_token_result, &mut router_data, &payments::CallConnectorAction::Trigger, ); let connector_response = Box::pin(call_connector_service( state, &connector, add_access_token_result, router_data, )) .await .to_refund_failed_response()?; let connector_response = perform_integrity_check(connector_response); let refund_update = build_refund_update_for_rsync(&connector, merchant_context, connector_response); let response = state .store .update_refund( refund.to_owned(), refund_update, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound) .attach_printable_lazy(|| { format!( "Unable to update refund with refund_id: {}", refund.id.get_string_repr() ) })?; // Implement outgoing webhook here Ok(response) } pub fn build_refund_update_for_rsync( connector: &api::ConnectorData, merchant_context: &domain::MerchantContext, router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, ) -> diesel_refund::RefundUpdate { let merchant_account = merchant_context.get_merchant_account(); let storage_scheme = &merchant_context.get_merchant_account().storage_scheme; match router_data_response.response { Err(error_message) => { let refund_status = match error_message.status_code { // marking failure for 2xx because this is genuine refund failure 200..=299 => Some(enums::RefundStatus::Failure), _ => None, }; let refund_error_message = error_message.reason.or(Some(error_message.message)); let refund_error_code = Some(error_message.code); diesel_refund::RefundUpdate::build_error_update_for_refund_failure( refund_status, refund_error_message, refund_error_code, storage_scheme, ) } Ok(response) => match router_data_response.integrity_check.clone() { Err(err) => { metrics::INTEGRITY_CHECK_FAILED.add( 1, router_env::metric_attributes!( ("connector", connector.connector_name.to_string()), ("merchant_id", merchant_account.get_id().clone()), ), ); let connector_refund_id = err .connector_transaction_id .map(common_utils_types::ConnectorTransactionId::from); diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure( err.field_names, connector_refund_id, storage_scheme, ) } Ok(()) => { let connector_refund_id = common_utils_types::ConnectorTransactionId::from(response.connector_refund_id); diesel_refund::RefundUpdate::build_refund_update( connector_refund_id, response.refund_status, storage_scheme, ) } }, } } // ********************************************** Refund list ********************************************** /// If payment_id is provided, lists all the refunds associated with that particular payment_id /// If payment_id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( state: SessionState, merchant_account: domain::MerchantAccount, profile: domain::Profile, req: refunds::RefundListRequest, ) -> errors::RouterResponse<refunds::RefundListResponse> { let db = state.store; let limit = refunds_validator::validate_refund_list(req.limit)?; let offset = req.offset.unwrap_or_default(); let refund_list = db .filter_refund_by_constraints( merchant_account.get_id(), RefundListConstraints::from((req.clone(), profile.clone())), merchant_account.storage_scheme, limit, offset, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let data: Vec<refunds::RefundResponse> = refund_list .into_iter() .map(refunds::RefundResponse::foreign_try_from) .collect::<Result<_, _>>()?; let total_count = db .get_total_count_of_refunds( merchant_account.get_id(), RefundListConstraints::from((req, profile)), merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?; Ok(services::ApplicationResponse::Json( api_models::refunds::RefundListResponse { count: data.len(), total_count, data, }, )) } // ********************************************** VALIDATIONS ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn validate_and_create_refund( state: &SessionState, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, refund_amount: common_utils_types::MinorUnit, req: refunds::RefundsCreateRequest, global_refund_id: id_type::GlobalRefundId, merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, ) -> errors::RouterResult<refunds::RefundResponse> { let db = &*state.store; let refund_type = req.refund_type.unwrap_or_default(); let merchant_reference_id = req.merchant_reference_id; let predicate = req .merchant_id .as_ref() .map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id()); utils::when(predicate.unwrap_or(false), || { Err(report!(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string() }) .attach_printable("invalid merchant_id in request")) })?; let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; let all_refunds = db .find_refund_by_merchant_id_connector_transaction_id( merchant_context.get_merchant_account().get_id(), &connector_payment_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?; let currency = payment_intent.amount_details.currency; refunds_validator::validate_payment_order_age( &payment_intent.created_at, state.conf.refund.max_age, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "created_at".to_string(), expected_format: format!( "created_at not older than {} days", state.conf.refund.max_age, ), })?; let total_amount_captured = payment_intent .amount_captured .unwrap_or(payment_attempt.get_total_amount()); refunds_validator::validate_refund_amount( total_amount_captured.get_amount_as_i64(), &all_refunds, refund_amount.get_amount_as_i64(), ) .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?; refunds_validator::validate_maximum_refund_against_payment_attempt( &all_refunds, state.conf.refund.max_attempts, ) .change_context(errors::ApiErrorResponse::MaximumRefundCount)?; let connector = payment_attempt .connector .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; let (connector_transaction_id, processor_transaction_data) = common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id); let refund_create_req = diesel_refund::RefundNew { id: global_refund_id, merchant_reference_id: merchant_reference_id.clone(), external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()), payment_id: req.payment_id, merchant_id: merchant_context.get_merchant_account().get_id().clone(), connector_transaction_id, connector, refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()), total_amount: payment_attempt.get_total_amount(), refund_amount, currency, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), refund_status: enums::RefundStatus::Pending, metadata: req.metadata, description: req.reason.clone(), attempt_id: payment_attempt.id.clone(), refund_reason: req.reason, profile_id: Some(payment_intent.profile_id.clone()), connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: None, connector_refund_id: None, sent_to_gateway: Default::default(), refund_arn: None, updated_by: Default::default(), organization_id: merchant_context .get_merchant_account() .organization_id .clone(), processor_transaction_data, processor_refund_data: None, }; let refund = match db .insert_refund( refund_create_req, merchant_context.get_merchant_account().storage_scheme, ) .await { Ok(refund) => { Box::pin(schedule_refund_execution( state, refund.clone(), refund_type, merchant_context, payment_attempt, payment_intent, merchant_connector_details, )) .await? } Err(err) => { if err.current_context().is_db_unique_violation() { Err(errors::ApiErrorResponse::DuplicateRefundRequest)? } else { Err(err) .change_context(errors::ApiErrorResponse::RefundFailed { data: None }) .attach_printable("Failed to insert refund")? } } }; let unified_translated_message = match (refund.unified_code.clone(), refund.unified_message.clone()) { (Some(unified_code), Some(unified_message)) => helpers::get_unified_translation( state, unified_code, unified_message.clone(), state.locale.to_string(), ) .await .or(Some(unified_message)), _ => refund.unified_message, }; let refund = diesel_refund::Refund { unified_message: unified_translated_message, ..refund }; api::RefundResponse::foreign_try_from(refund) } impl ForeignTryFrom<diesel_refund::Refund> for api::RefundResponse { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(refund: diesel_refund::Refund) -> Result<Self, Self::Error> { let refund = refund; let profile_id = refund .profile_id .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("Profile id not found")?; let connector_name = refund.connector; let connector = Connector::from_str(&connector_name) .change_context(errors::ConnectorError::InvalidConnectorName) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "connector", }) .attach_printable_lazy(|| { format!("unable to parse connector name {connector_name:?}") })?; Ok(Self { payment_id: refund.payment_id, id: refund.id.clone(), amount: refund.refund_amount, currency: refund.currency, reason: refund.refund_reason, status: refunds::RefundStatus::foreign_from(refund.refund_status), profile_id, metadata: refund.metadata, created_at: refund.created_at, updated_at: refund.modified_at, connector, merchant_connector_id: refund.connector_id, merchant_reference_id: Some(refund.merchant_reference_id), error_details: Some(RefundErrorDetails { code: refund.refund_error_code.unwrap_or_default(), message: refund.refund_error_message.unwrap_or_default(), }), connector_refund_reference_id: None, }) } } // ********************************************** PROCESS TRACKER ********************************************** #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn schedule_refund_execution( state: &SessionState, refund: diesel_refund::Refund, refund_type: api_models::refunds::RefundType, merchant_context: &domain::MerchantContext, payment_attempt: &storage::PaymentAttempt, payment_intent: &storage::PaymentIntent, merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>, ) -> errors::RouterResult<diesel_refund::Refund> { let db = &*state.store; let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter; let task = "EXECUTE_REFUND"; let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let refund_process = db .find_process_by_id(&task_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find the process id")?; let result = match refund.refund_status { enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => { match (refund.sent_to_gateway, refund_process) { (false, None) => { // Execute the refund task based on refund_type match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_execute_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?; Ok(refund) } api_models::refunds::RefundType::Instant => { let update_refund = if state.conf.merchant_id_auth.merchant_id_auth_enabled { let merchant_connector_details = match merchant_connector_details { Some(details) => details, None => { return Err(report!( errors::ApiErrorResponse::MissingRequiredField { field_name: "merchant_connector_details" } )); } }; Box::pin(internal_trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, merchant_connector_details, )) .await } else { Box::pin(trigger_refund_to_gateway( state, &refund, merchant_context, payment_attempt, payment_intent, )) .await }; match update_refund { Ok(updated_refund_data) => { add_refund_sync_task(db, &updated_refund_data, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!( "Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr() ))?; Ok(updated_refund_data) } Err(err) => Err(err), } } } } _ => { // Sync the refund for status check //[#300]: return refund status response match refund_type { api_models::refunds::RefundType::Scheduled => { add_refund_sync_task(db, &refund, runner) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?; Ok(refund) } api_models::refunds::RefundType::Instant => { // [#255]: This is not possible in schedule_refund_execution as it will always be scheduled // sync_refund_with_gateway(data, &refund).await Ok(refund) } } } } } // [#255]: This is not allowed to be otherwise or all _ => Ok(refund), }?; Ok(result) } #[instrument] pub fn refund_to_refund_core_workflow_model( refund: &diesel_refund::Refund, ) -> diesel_refund::RefundCoreWorkflow { diesel_refund::RefundCoreWorkflow { refund_id: refund.id.clone(), connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), processor_transaction_data: refund.processor_transaction_data.clone(), } } #[instrument(skip_all)] pub async fn add_refund_execute_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> errors::RouterResult<storage::ProcessTracker> { let task = "EXECUTE_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let tag = ["REFUND"]; let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund execute process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.id.get_string_repr() ) })?; Ok(response) } #[instrument(skip_all)] pub async fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> errors::RouterResult<storage::ProcessTracker> { let task = "SYNC_REFUND"; let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr()); let schedule_time = common_utils::date_time::now(); let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund); let tag = ["REFUND"]; let process_tracker_entry = storage::ProcessTrackerNew::new( process_tracker_id, task, runner, tag, refund_workflow_tracking_data, None, schedule_time, common_types::consts::API_VERSION, ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to construct refund sync process tracker task")?; let response = db .insert_process(process_tracker_entry) .await .to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest) .attach_printable_lazy(|| { format!( "Failed while inserting task in process_tracker: refund_id: {}", refund.id.get_string_repr() ) })?; metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund"))); Ok(response) }
{ "crate": "router", "file": "crates/router/src/core/refunds_v2.rs", "file_size": 52978, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
large_file_router_4902444177950513220
clm
file
// Repository: hyperswitch // Crate: router // File: crates/router/src/configs/settings.rs // File size: 51017 bytes use std::{ collections::{HashMap, HashSet}, path::PathBuf, sync::Arc, }; #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::enums; use common_utils::{ ext_traits::ConfigExt, id_type, types::{user::EmailThemeConfig, Url}, }; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ crm::CrmManagerConfig, file_storage::FileStorageConfig, grpc_client::GrpcClientSettings, managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, }, superposition::SuperpositionClientConfig, }; pub use hyperswitch_interfaces::{ configs::{ Connectors, GlobalTenant, InternalMerchantIdProfileIdAuthSettings, InternalServicesConfig, Tenant, TenantUserConfig, }, secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }, types::Proxy, }; use masking::Secret; pub use payment_methods::configs::settings::{ BankRedirectConfig, BanksVector, ConnectorBankNames, ConnectorFields, EligiblePaymentMethods, Mandates, PaymentMethodAuth, PaymentMethodType, RequiredFieldFinal, RequiredFields, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, }; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; use serde::Deserialize; use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] use crate::analytics::{AnalyticsConfig, AnalyticsProvider}; #[cfg(feature = "v2")] use crate::types::storage::revenue_recovery; use crate::{ configs, core::errors::{ApplicationError, ApplicationResult}, env::{self, Env}, events::EventsConfig, routes::app, AppState, }; pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml"; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] pub struct CmdLineConf { /// Config file. /// Application will look for "config/config.toml" if this option isn't specified. #[arg(short = 'f', long, value_name = "FILE")] pub config_path: Option<PathBuf>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, pub chat: SecretStateContainer<ChatSettings, S>, pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] pub replica_database: SecretStateContainer<Database, S>, pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, pub eph_key: EphemeralConfig, pub scheduler: Option<SchedulerSettings>, #[cfg(feature = "kv_store")] pub drainer: DrainerSettings, pub jwekey: SecretStateContainer<Jwekey, S>, pub webhooks: WebhooksSettings, pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, pub api_keys: SecretStateContainer<ApiKeys, S>, pub file_storage: FileStorageConfig, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, pub user: UserSettings, pub crm: CrmManagerConfig, pub cors: CorsSettings, pub mandates: Mandates, pub zero_mandates: ZeroMandates, pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors, pub list_dispute_supported_connectors: ListDiputeSupportedConnectors, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall, pub billing_connectors_invoice_sync: BillingConnectorInvoiceSyncCall, pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, pub l2_l3_data_config: L2L3DataConfig, pub debit_routing_config: DebitRoutingConfig, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, pub temp_locker_enable_config: TempLockerEnableConfig, pub generic_link: GenericLink, pub payment_link: PaymentLink, #[cfg(feature = "olap")] pub analytics: SecretStateContainer<AnalyticsConfig, S>, #[cfg(feature = "kv_store")] pub kv_config: KvConfig, #[cfg(feature = "frm")] pub frm: Frm, #[cfg(feature = "olap")] pub report_download_config: ReportConfig, #[cfg(feature = "olap")] pub opensearch: OpenSearchConfig, pub events: EventsConfig, #[cfg(feature = "olap")] pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, pub unmasked_headers: UnmaskedHeaders, pub multitenancy: Multitenancy, pub saved_payment_methods: EligiblePaymentMethods, pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>, pub decision: Option<DecisionConfig>, pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, pub grpc_client: GrpcClientSettings, #[cfg(feature = "v2")] pub cell_information: CellInformation, pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, pub platform: Platform, pub authentication_providers: AuthenticationProviders, pub open_router: OpenRouter, #[cfg(feature = "v2")] pub revenue_recovery: revenue_recovery::RevenueRecoverySettings, pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>, pub merchant_id_auth: MerchantIdAuthSettings, pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings, #[serde(default)] pub infra_values: Option<HashMap<String, String>>, #[serde(default)] pub enhancement: Option<HashMap<String, String>>, pub superposition: SecretStateContainer<SuperpositionClientConfig, S>, pub proxy_status_mapping: ProxyStatusMapping, pub internal_services: InternalServicesConfig, pub comparison_service: Option<ComparisonServiceConfig>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DebitRoutingConfig { #[serde(deserialize_with = "deserialize_hashmap")] pub connector_supported_debit_networks: HashMap<enums::Connector, HashSet<enums::CardNetwork>>, #[serde(deserialize_with = "deserialize_hashset")] pub supported_currencies: HashSet<enums::Currency>, #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct OpenRouter { pub dynamic_routing_enabled: bool, pub static_routing_enabled: bool, pub url: String, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CloneConnectorAllowlistConfig { #[serde(deserialize_with = "deserialize_merchant_ids")] pub merchant_ids: HashSet<id_type::MerchantId>, #[serde(deserialize_with = "deserialize_hashset")] pub connector_names: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone)] pub struct ComparisonServiceConfig { pub url: Url, pub enabled: bool, pub timeout_secs: Option<u64>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, pub allow_connected_merchants: bool, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ChatSettings { pub enabled: bool, pub hyperswitch_ai_host: String, pub encryption_key: Secret<String>, } #[derive(Debug, Clone, Default, Deserialize)] pub struct Multitenancy { pub tenants: TenantConfig, pub enabled: bool, pub global_tenant: GlobalTenant, } impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Deserialize, Clone, Default)] pub struct DecisionConfig { pub base_url: String, } #[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl TenantConfig { /// # Panics /// /// Panics if Failed to create event handler pub async fn get_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::StorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } /// # Panics /// /// Panics if Failed to create event handler pub async fn get_accounts_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::AccountsStorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_accounts_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } #[cfg(feature = "olap")] pub async fn get_pools_map( &self, analytics_config: &AnalyticsConfig, ) -> HashMap<id_type::TenantId, AnalyticsProvider> { futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { ( tenant_name.clone(), AnalyticsProvider::from_conf(analytics_config, tenant).await, ) })) .await .into_iter() .collect() } } #[derive(Debug, Deserialize, Clone, Default)] pub struct L2L3DataConfig { pub enabled: bool, } #[derive(Debug, Deserialize, Clone, Default)] pub struct UnmaskedHeaders { #[serde(deserialize_with = "deserialize_hashset")] pub keys: HashSet<String>, } #[cfg(feature = "frm")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Frm { pub enabled: bool, } #[derive(Debug, Deserialize, Clone)] pub struct KvConfig { pub ttl: u32, pub soft_kill: Option<bool>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct KeyManagerConfig { pub enabled: bool, pub url: String, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct GenericLink { pub payment_method_collect: GenericLinkEnvConfig, pub payout_link: GenericLinkEnvConfig, } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvConfig { pub sdk_url: url::Url, pub expiry: u32, pub ui_config: GenericLinkEnvUiConfig, #[serde(deserialize_with = "deserialize_hashmap")] pub enabled_payment_methods: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, } impl Default for GenericLinkEnvConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js") .expect("Failed to parse default SDK URL"), expiry: 900, ui_config: GenericLinkEnvUiConfig::default(), enabled_payment_methods: HashMap::default(), } } } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvUiConfig { pub logo: url::Url, pub merchant_name: Secret<String>, pub theme: String, } #[allow(clippy::panic)] impl Default for GenericLinkEnvUiConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] logo: url::Url::parse("https://hyperswitch.io/favicon.ico") .expect("Failed to parse default logo URL"), merchant_name: Secret::new("HyperSwitch".to_string()), theme: "#4285F4".to_string(), } } } #[derive(Debug, Deserialize, Clone)] pub struct PaymentLink { pub sdk_url: url::Url, } impl Default for PaymentLink { fn default() -> Self { Self { #[allow(clippy::expect_used)] sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js") .expect("Failed to parse default SDK URL"), } } } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ForexApi { pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, pub data_expiration_delay_in_seconds: u32, pub redis_lock_timeout_in_seconds: u32, pub redis_ttl_in_seconds: u32, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DefaultExchangeRates { pub base_currency: String, pub conversion: HashMap<String, Conversion>, pub timestamp: i64, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Conversion { #[serde(with = "rust_decimal::serde::str")] pub to_factor: Decimal, #[serde(with = "rust_decimal::serde::str")] pub from_factor: Decimal, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ApplepayMerchantConfigs { pub merchant_cert: Secret<String>, pub merchant_cert_key: Secret<String>, pub common_merchant_identifier: Secret<String>, pub applepay_endpoint: String, } #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMethodFilter>); #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { #[cfg(feature = "payouts")] #[serde(deserialize_with = "deserialize_hashset")] pub payout_connector_list: HashSet<enums::PayoutConnectors>, } #[cfg(feature = "dummy_connector")] #[derive(Debug, Deserialize, Clone, Default)] pub struct DummyConnector { pub enabled: bool, pub payment_ttl: i64, pub payment_duration: u64, pub payment_tolerance: u64, pub payment_retrieve_duration: u64, pub payment_retrieve_tolerance: u64, pub payment_complete_duration: i64, pub payment_complete_tolerance: i64, pub refund_ttl: i64, pub refund_duration: u64, pub refund_tolerance: u64, pub refund_retrieve_duration: u64, pub refund_retrieve_tolerance: u64, pub authorize_ttl: i64, pub assets_base_url: String, pub default_return_url: String, pub slack_invite_url: String, pub discord_invite_url: String, } #[derive(Debug, Deserialize, Clone)] pub struct CorsSettings { #[serde(default, deserialize_with = "deserialize_hashset")] pub origins: HashSet<String>, #[serde(default)] pub wildcard_origin: bool, pub max_age: usize, #[serde(deserialize_with = "deserialize_hashset")] pub allowed_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct AuthenticationProviders { #[serde(deserialize_with = "deserialize_connector_list")] pub click_to_pay: HashSet<enums::Connector>, } fn deserialize_connector_list<'a, D>(deserializer: D) -> Result<HashSet<enums::Connector>, D::Error> where D: serde::Deserializer<'a>, { use serde::de::Error; #[derive(Deserialize)] struct Wrapper { connector_list: String, } let wrapper = Wrapper::deserialize(deserializer)?; wrapper .connector_list .split(',') .map(|s| s.trim().parse().map_err(D::Error::custom)) .collect() } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTransactionIdSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } /// Connectors that support only dispute list API for syncing disputes with Hyperswitch #[derive(Debug, Deserialize, Clone, Default)] pub struct ListDiputeSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedCardNetworks { #[serde(deserialize_with = "deserialize_hashset")] pub card_networks: HashSet<enums::CardNetwork>, } #[derive(Debug, Deserialize, Clone)] pub struct NetworkTokenizationService { pub generate_token_url: url::Url, pub fetch_token_url: url::Url, pub token_service_api_key: Secret<String>, pub public_key: Secret<String>, pub private_key: Secret<String>, pub key_id: String, pub delete_token_url: url::Url, pub check_token_status_url: url::Url, pub webhook_source_verification_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>, pub google_pay_pre_decrypt_flow: Option<GooglePayPreDecryptFlow>, pub flow: Option<PaymentFlow>, } #[derive(Debug, Deserialize, Clone, PartialEq)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum PaymentFlow { Mandates, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum ApplePayPreDecryptFlow { #[default] ConnectorTokenization, NetworkTokenization, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum GooglePayPreDecryptFlow { #[default] ConnectorTokenization, NetworkTokenization, } #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum PaymentMethodTypeTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[serde(deserialize_with = "deserialize_hashset")] DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[default] AllAccepted, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { PaymentMethodType(enums::PaymentMethodType), CardNetwork(enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { #[serde(deserialize_with = "deserialize_optional_hashset")] pub currency: Option<HashSet<enums::Currency>>, #[serde(deserialize_with = "deserialize_optional_hashset")] pub country: Option<HashSet<enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<enums::CaptureMethod>, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payout_required_fields.toml pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { pub jwt_secret: Secret<String>, pub admin_api_key: Secret<String>, pub master_enc_key: Secret<String>, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct FallbackMerchantIds { #[serde(deserialize_with = "deserialize_merchant_ids")] pub merchant_ids: HashSet<id_type::MerchantId>, } #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, pub two_factor_auth_expiry_in_secs: i64, pub totp_issuer_name: String, pub base_url: String, pub force_two_factor_auth: bool, pub force_cookies: bool, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Locker { pub host: String, pub host_rs: String, pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, pub locker_enabled: bool, pub ttl_for_storage_in_secs: i64, pub decryption_scheme: DecryptionScheme, } #[derive(Debug, Deserialize, Clone, Default)] pub enum DecryptionScheme { #[default] #[serde(rename = "RSA-OAEP")] RsaOaep, #[serde(rename = "RSA-OAEP-256")] RsaOaep256, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Refund { pub max_attempts: usize, pub max_age: i64, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct EphemeralConfig { pub validity: i64, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Jwekey { pub vault_encryption_key: Secret<String>, pub rust_locker_encryption_key: Secret<String>, pub vault_private_key: Secret<String>, pub tunnel_private_key: Secret<String>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, pub request_body_limit: usize, pub shutdown_timeout: u64, #[cfg(feature = "tls")] pub tls: Option<ServerTls>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { username: val.username, password: val.password, host: val.host, port: val.port, dbname: val.dbname, pool_size: val.pool_size, connection_timeout: val.connection_timeout, queue_strategy: val.queue_strategy, min_idle: val.min_idle, max_lifetime: val.max_lifetime, } } } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct SupportedConnectors { pub wallets: Vec<String>, } #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct MerchantIdAuthSettings { pub merchant_id_auth_enabled: bool, } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct ProxyStatusMapping { pub proxy_connector_http_status_code: bool, } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct WebhooksSettings { pub outgoing_enabled: bool, pub ignore_error: WebhookIgnoreErrorSettings, pub redis_lock_expiry_seconds: u32, } #[derive(Debug, Clone, Deserialize, Default)] #[serde(default)] pub struct WebhookIgnoreErrorSettings { pub event_type: Option<bool>, pub payment_not_found: Option<bool>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct ApiKeys { /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys pub hash_key: Secret<String>, // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] pub expiry_reminder_days: Vec<u8>, #[cfg(feature = "partial-auth")] pub checksum_auth_context: Secret<String>, #[cfg(feature = "partial-auth")] pub checksum_auth_key: Secret<String>, #[cfg(feature = "partial-auth")] pub enable_partial_auth: bool, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_delayed_session_response: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BillingConnectorPaymentsSyncCall { #[serde(deserialize_with = "deserialize_hashset")] pub billing_connectors_which_require_payment_sync: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BillingConnectorInvoiceSyncCall { #[serde(deserialize_with = "deserialize_hashset")] pub billing_connectors_which_requires_invoice_sync_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ApplePayDecryptConfig { pub apple_pay_ppc: Secret<String>, pub apple_pay_ppc_key: Secret<String>, pub apple_pay_merchant_cert: Secret<String>, pub apple_pay_merchant_cert_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PazeDecryptConfig { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, } #[derive(Debug, Deserialize, Clone)] pub struct GooglePayDecryptConfig { pub google_pay_root_signing_keys: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LockerBasedRecipientConnectorList { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct UserAuthMethodSettings { pub encryption_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> { // Configuration values are picked up in the following priority order (1 being least // priority): // 1. Defaults from the implementation of the `Default` trait. // 2. Values from config file. The config file accessed depends on the environment // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of // `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`, // `/config/development.toml` file is read. // 3. Environment variables prefixed with `ROUTER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); let config = router_env::Config::builder(&environment.to_string()) .change_context(ApplicationError::ConfigurationError)? .add_source(File::from(config_path).required(false)); #[cfg(feature = "v2")] let config = { let required_fields_config_file = router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE); config.add_source(File::from(required_fields_config_file).required(false)) }; let config = config .add_source( Environment::with_prefix("ROUTER") .try_parsing(true) .separator("__") .list_separator(",") .with_list_parse_key("log.telemetry.route_to_trace") .with_list_parse_key("redis.cluster_urls") .with_list_parse_key("events.kafka.brokers") .with_list_parse_key("connectors.supported.wallets") .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), ) .build() .change_context(ApplicationError::ConfigurationError)?; let mut settings: Self = serde_path_to_error::deserialize(config) .attach_printable("Unable to deserialize application configuration") .change_context(ApplicationError::ConfigurationError)?; #[cfg(feature = "v1")] { settings.required_fields = RequiredFields::new(&settings.bank_config); } Ok(settings) } pub fn validate(&self) -> ApplicationResult<()> { self.server.validate()?; self.master_database.get_inner().validate()?; #[cfg(feature = "olap")] self.replica_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) })?; if self.log.file.enabled { if self.log.file.file_name.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log file name must not be empty".into(), ), )); } if self.log.file.path.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log directory path must not be empty".into(), ), )); } } self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; self.chat.get_inner().validate()?; self.cors.validate()?; self.scheduler .as_ref() .map(|scheduler_settings| scheduler_settings.validate()) .transpose()?; #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.get_inner().validate()?; self.file_storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.crm .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.lock_settings.validate()?; self.events.validate()?; #[cfg(feature = "olap")] self.opensearch.validate()?; self.encryption_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.secrets_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.generic_link.payment_method_collect.validate()?; self.generic_link.payout_link.validate()?; #[cfg(feature = "v2")] self.cell_information.validate()?; self.network_tokenization_service .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.paze_decrypt_keys .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.google_pay_decrypt_keys .as_ref() .map(|x| x.validate()) .transpose()?; self.key_manager.get_inner().validate()?; #[cfg(feature = "email")] self.email .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.theme .storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.platform.validate()?; self.open_router.validate()?; // Validate gRPC client settings #[cfg(feature = "revenue_recovery")] self.grpc_client .recovery_decider_client .as_ref() .map(|config| config.validate()) .transpose() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.superposition .get_inner() .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; Ok(()) } } impl Settings<RawSecret> { #[cfg(feature = "kv_store")] pub fn is_kv_soft_kill_mode(&self) -> bool { self.kv_config.soft_kill.unwrap_or(false) } #[cfg(not(feature = "kv_store"))] pub fn is_kv_soft_kill_mode(&self) -> bool { false } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { pub payout_eligibility: bool, #[serde(default)] pub required_fields: PayoutRequiredFields, } #[derive(Debug, Clone, Default)] pub struct LockSettings { pub redis_lock_expiry_seconds: u32, pub delay_between_retries_in_milliseconds: u32, pub lock_retries: u32, } impl<'de> Deserialize<'de> for LockSettings { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { redis_lock_expiry_seconds: u32, delay_between_retries_in_milliseconds: u32, } let Inner { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, } = Inner::deserialize(deserializer)?; let redis_lock_expiry_milliseconds = redis_lock_expiry_seconds * 1000; Ok(Self { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, lock_retries: redis_lock_expiry_milliseconds / delay_between_retries_in_milliseconds, }) } } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorOnboarding { pub paypal: PayPalOnboarding, } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct PayPalOnboarding { pub client_id: Secret<String>, pub client_secret: Secret<String>, pub partner_id: Secret<String>, pub enabled: bool, } #[cfg(feature = "tls")] #[derive(Debug, Deserialize, Clone)] pub struct ServerTls { /// Port to host the TLS secure server on pub port: u16, /// Use a different host (optional) (defaults to the host provided in [`Server`] config) pub host: Option<String>, /// private key file path associated with TLS (path to the private key file (`pem` format)) pub private_key: PathBuf, /// certificate file associated with TLS (path to the certificate file (`pem` format)) pub certificate: PathBuf, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct CellInformation { pub id: id_type::CellId, } #[cfg(feature = "v2")] impl Default for CellInformation { fn default() -> Self { // We provide a static default cell id for constructing application settings. // This will only panic at application startup if we're unable to construct the default, // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] let cell_id = id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } } #[derive(Debug, Deserialize, Clone, Default)] pub struct ThemeSettings { pub storage: FileStorageConfig, pub email_config: EmailThemeConfig, } fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> where K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .into_iter() .map( |(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) { (Err(error), _) => Err(format!( "Unable to deserialize `{}` as `{}`: {error}", k, std::any::type_name::<K>() )), (_, Err(error)) => Err(error), (Ok(key), Ok(value)) => Ok((key, value)), }, ) .fold( (HashMap::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok((key, value)) => { values.insert(key, value); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error> where D: serde::Deserializer<'a>, K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?) .map_err(D::Error::custom) } fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) } fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; <Option<String>>::deserialize(deserializer).map(|value| { value.map_or(Ok(None), |inner: String| { let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?; match list.len() { 0 => Ok(None), _ => Ok(Some(list)), } }) })? } fn deserialize_merchant_ids_inner( value: impl AsRef<str>, ) -> Result<HashSet<id_type::MerchantId>, String> { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { let trimmed = s.trim(); id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { format!("Unable to deserialize `{trimmed}` as `MerchantId`: {error}") }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_merchant_ids<'de, D>( deserializer: D, ) -> Result<HashSet<id_type::MerchantId>, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) } impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, user: TenantUserConfig, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, user: value.user, }, ) }) .collect(), )) } } #[cfg(test)] mod hashmap_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::{HashMap, HashSet}; use serde::de::{ value::{Error as ValueError, MapDeserializer}, IntoDeserializer, }; use super::deserialize_hashmap; #[test] fn test_payment_method_and_payment_method_types() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("bank_transfer".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,venmo".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([PaymentMethodType::Paypal, PaymentMethodType::Venmo]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_and_payment_method_types_with_spaces() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ (" bank_transfer ".to_string(), " ach , bacs ".to_string()), ("wallet ".to_string(), " paypal , pix , venmo ".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([ PaymentMethodType::Paypal, PaymentMethodType::Pix, PaymentMethodType::Venmo, ]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_deserializer_error() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("unknown".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,unknown".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); assert!(result.is_err()); } } #[cfg(test)] mod hashset_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::HashSet; use serde::de::{ value::{Error as ValueError, StrDeserializer}, IntoDeserializer, }; use super::deserialize_hashset; #[test] fn test_payment_method_hashset_deserializer() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_with_spaces() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, bank_debit".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([ PaymentMethod::Wallet, PaymentMethod::Card, PaymentMethod::BankDebit, ]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_error() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, unknown".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); assert!(payment_methods.is_err()); } }
{ "crate": "router", "file": "crates/router/src/configs/settings.rs", "file_size": 51017, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
repo_structure
clm
repository
# Hyperswitch Repository Structure analytics/ Purpose: Event logging with Kafka and ClickHouse Dependencies: api_models, common_enums, common_utils, diesel_models, hyperswitch_interfaces, masking, storage_impl api_models/ Purpose: External API request/response types (what clients see) Dependencies: common_enums, common_utils, masking cards/ Dependencies: common_utils, masking common_enums/ Purpose: Shared enumerations across request/response and database types Dependencies: masking common_types/ Dependencies: common_enums, common_utils, masking common_utils/ Purpose: Utility functions shared across crates Dependencies: common_enums, masking config_importer/ connector_configs/ Dependencies: api_models, common_utils currency_conversion/ Dependencies: common_enums diesel_models/ Purpose: Database schema types directly mapping to PostgreSQL tables Dependencies: common_enums, common_utils, masking drainer/ Purpose: Redis stream processing and database writing Dependencies: common_utils, diesel_models, hyperswitch_interfaces, masking, redis_interface euclid/ Dependencies: common_enums, common_utils, hyperswitch_constraint_graph euclid_macros/ euclid_wasm/ Dependencies: api_models, common_enums, hyperswitch_constraint_graph events/ Dependencies: masking external_services/ Dependencies: common_utils, common_enums, hyperswitch_interfaces, masking, api_models hsdev/ hyperswitch_connectors/ Purpose: Payment provider integrations (Stripe, PayPal, etc.) Dependencies: api_models, common_enums, common_utils, hyperswitch_domain_models, hyperswitch_interfaces, masking hyperswitch_constraint_graph/ hyperswitch_domain_models/ Purpose: Business logic data models bridging API and database layers Dependencies: api_models, common_enums, common_utils, diesel_models, masking hyperswitch_interfaces/ Purpose: Trait definitions for connectors and services Dependencies: hyperswitch_domain_models, masking, api_models, common_enums, common_utils injector/ Dependencies: common_utils, masking kgraph_utils/ Dependencies: api_models, common_enums, common_utils, hyperswitch_constraint_graph, masking masking/ Purpose: PII protection and data masking openapi/ Dependencies: api_models, common_utils payment_methods/ Dependencies: masking, api_models, common_enums, common_utils, hyperswitch_domain_models, scheduler, storage_impl, hyperswitch_interfaces pm_auth/ Dependencies: api_models, common_enums, common_utils, masking redis_interface/ Purpose: User-friendly Redis interface Dependencies: common_utils router/ Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration Dependencies: analytics, api_models, common_enums, common_utils, diesel_models, hyperswitch_connectors, hyperswitch_constraint_graph, hyperswitch_domain_models, hyperswitch_interfaces, masking, redis_interface, scheduler, storage_impl router_derive/ Dependencies: common_utils router_env/ scheduler/ Purpose: Background task scheduling and execution Dependencies: common_utils, diesel_models, hyperswitch_domain_models, redis_interface, storage_impl smithy/ smithy-core/ smithy-generator/ Dependencies: api_models, common_enums, common_utils storage_impl/ Purpose: Storage backend implementations for database operations Dependencies: api_models, common_enums, common_utils, diesel_models, hyperswitch_domain_models, masking, redis_interface subscriptions/ Dependencies: masking, api_models, common_enums, common_utils, hyperswitch_domain_models, scheduler, storage_impl, hyperswitch_interfaces test_utils/ Dependencies: masking, common_enums
{ "crate": null, "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": 38 }
crate_storage_impl
clm
crate
// CRATE: storage_impl // PURPOSE: Storage backend implementations for database operations // DEPENDENCIES: api_models, common_enums, common_utils, diesel_models, hyperswitch_domain_models, masking, redis_interface
{ "crate": "storage_impl", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_common_utils
clm
crate
// CRATE: common_utils // PURPOSE: Utility functions shared across crates // DEPENDENCIES: common_enums, masking
{ "crate": "common_utils", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_hyperswitch_domain_models
clm
crate
// CRATE: hyperswitch_domain_models // PURPOSE: Business logic data models bridging API and database layers // DEPENDENCIES: api_models, common_enums, common_utils, diesel_models, masking
{ "crate": "hyperswitch_domain_models", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_hyperswitch_connectors
clm
crate
// CRATE: hyperswitch_connectors // PURPOSE: Payment provider integrations (Stripe, PayPal, etc.) // DEPENDENCIES: api_models, common_enums, common_utils, hyperswitch_domain_models, hyperswitch_interfaces, masking
{ "crate": "hyperswitch_connectors", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_smithy
clm
crate
// CRATE: smithy
{ "crate": "smithy", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_common_enums
clm
crate
// CRATE: common_enums // PURPOSE: Shared enumerations across request/response and database types // DEPENDENCIES: masking
{ "crate": "common_enums", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_hyperswitch_constraint_graph
clm
crate
// CRATE: hyperswitch_constraint_graph
{ "crate": "hyperswitch_constraint_graph", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_connector_configs
clm
crate
// CRATE: connector_configs // DEPENDENCIES: api_models, common_utils
{ "crate": "connector_configs", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_test_utils
clm
crate
// CRATE: test_utils // DEPENDENCIES: masking, common_enums
{ "crate": "test_utils", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_euclid_wasm
clm
crate
// CRATE: euclid_wasm // DEPENDENCIES: api_models, common_enums, hyperswitch_constraint_graph
{ "crate": "euclid_wasm", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_common_types
clm
crate
// CRATE: common_types // DEPENDENCIES: common_enums, common_utils, masking
{ "crate": "common_types", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_smithy-core
clm
crate
// CRATE: smithy-core
{ "crate": "smithy-core", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_config_importer
clm
crate
// CRATE: config_importer
{ "crate": "config_importer", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_cards
clm
crate
// CRATE: cards // DEPENDENCIES: common_utils, masking
{ "crate": "cards", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_currency_conversion
clm
crate
// CRATE: currency_conversion // DEPENDENCIES: common_enums
{ "crate": "currency_conversion", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_diesel_models
clm
crate
// CRATE: diesel_models // PURPOSE: Database schema types directly mapping to PostgreSQL tables // DEPENDENCIES: common_enums, common_utils, masking
{ "crate": "diesel_models", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_scheduler
clm
crate
// CRATE: scheduler // PURPOSE: Background task scheduling and execution // DEPENDENCIES: common_utils, diesel_models, hyperswitch_domain_models, redis_interface, storage_impl
{ "crate": "scheduler", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_smithy-generator
clm
crate
// CRATE: smithy-generator // DEPENDENCIES: api_models, common_enums, common_utils
{ "crate": "smithy-generator", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }
crate_openapi
clm
crate
// CRATE: openapi // DEPENDENCIES: api_models, common_utils
{ "crate": "openapi", "file": null, "file_size": null, "is_async": null, "is_pub": null, "num_enums": null, "num_structs": null, "num_tables": null, "score": null, "total_crates": null }