Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

Refactor(core): reverts the payment method list filtering using constraint graph (#5044)

Prajjwal Kumare486641c97e0
diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs
index 8e65d23d5e..1aba6338d9 100644
--- a/crates/euclid/src/enums.rs
+++ b/crates/euclid/src/enums.rs
@@ -79,8 +79,6 @@ pub enum MandateAcceptanceType {
pub enum PaymentType {
SetupMandate,
NonMandate,
- NewMandate,
- UpdateMandate,
}
#[derive(
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 4bde9f42c8..f0aa0480d0 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1,7 +1,6 @@
pub mod cards;
pub mod surcharge_decision_configs;
pub mod transformers;
-pub mod utils;
pub mod vault;
pub use api_models::enums::Connector;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3e23b24294..fad3e6d918 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -5,7 +5,7 @@ use std::{
};
use api_models::{
- admin::PaymentMethodsEnabled,
+ admin::{self, PaymentMethodsEnabled},
enums::{self as api_enums},
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
@@ -19,22 +19,18 @@ use api_models::{
pm_auth::PaymentMethodAuthConfig,
surcharge_decision_configs as api_surcharge_decision_configs,
};
-use cgraph::ConstraintGraph;
use common_enums::enums::MerchantStorageScheme;
use common_utils::{
consts,
ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
generate_id, id_type,
};
-use diesel_models::{business_profile::BusinessProfile, encryption::Encryption, payment_method};
+use diesel_models::{
+ business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
+ payment_method,
+};
use domain::CustomerUpdate;
use error_stack::{report, ResultExt};
-use euclid::{
- dssa::graph::{AnalysisContext, CgraphExt},
- frontend::dir,
-};
-use hyperswitch_constraint_graph as cgraph;
-use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, metrics::add_attributes, tracing};
use strum::IntoEnumIterator;
@@ -49,11 +45,7 @@ use crate::{
configs::settings,
core::{
errors::{self, StorageErrorExt},
- payment_methods::{
- transformers as payment_methods,
- utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
- vault,
- },
+ payment_methods::{transformers as payment_methods, vault},
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
@@ -1885,94 +1877,31 @@ pub async fn list_payment_methods(
.await?;
// filter out connectors based on the business country
- let filtered_mcas =
- helpers::filter_mca_based_on_business_profile(all_mcas.clone(), profile_id.clone());
+ let filtered_mcas = helpers::filter_mca_based_on_business_profile(all_mcas, profile_id);
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
+ for mca in &filtered_mcas {
+ let payment_methods = match &mca.payment_methods_enabled {
+ Some(pm) => pm.clone(),
+ None => continue,
+ };
- // Key creation for storing PM_FILTER_CGRAPH
- #[cfg(feature = "business_profile_routing")]
- let key = {
- let profile_id = profile_id
- .clone()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::GenericNotFoundError {
- message: "Profile id not found".to_string(),
- })?;
- format!(
- "pm_filters_cgraph_{}_{}",
- &merchant_account.merchant_id, profile_id
+ filter_payment_methods(
+ payment_methods,
+ &mut req,
+ &mut response,
+ payment_intent.as_ref(),
+ payment_attempt.as_ref(),
+ billing_address.as_ref(),
+ mca.connector_name.clone(),
+ pm_config_mapping,
+ &state.conf.mandates.supported_payment_methods,
+ &state.conf.mandates.update_mandate_supported,
+ &state.conf.saved_payment_methods,
)
- };
-
- #[cfg(not(feature = "business_profile_routing"))]
- let key = { format!("pm_filters_cgraph_{}", &merchant_account.merchant_id) };
-
- if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await {
- // Derivation of PM_FILTER_CGRAPH from MokaCache successful
- for mca in &filtered_mcas {
- let payment_methods = match &mca.payment_methods_enabled {
- Some(pm) => pm,
- None => continue,
- };
- filter_payment_methods(
- &graph,
- payment_methods,
- &mut req,
- &mut response,
- payment_intent.as_ref(),
- payment_attempt.as_ref(),
- billing_address.as_ref(),
- mca.connector_name.clone(),
- &state.conf.saved_payment_methods,
- )
- .await?;
- }
- } else {
- // No PM_FILTER_CGRAPH Cache present in MokaCache
- let mut builder = cgraph::ConstraintGraphBuilder::<'static, _>::new();
- for mca in &filtered_mcas {
- let payment_methods = match &mca.payment_methods_enabled {
- Some(pm) => pm,
- None => continue,
- };
- if let Err(e) = make_pm_graph(
- &mut builder,
- payment_methods,
- mca.connector_name.clone(),
- pm_config_mapping,
- &state.conf.mandates.supported_payment_methods,
- &state.conf.mandates.update_mandate_supported,
- ) {
- logger::error!(
- "Failed to construct constraint graph for list payment methods {e:?}"
- );
- }
- }
-
- // Refreshing our CGraph cache
- let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await;
-
- for mca in &filtered_mcas {
- let payment_methods = match &mca.payment_methods_enabled {
- Some(pm) => pm,
- None => continue,
- };
- filter_payment_methods(
- &graph,
- payment_methods,
- &mut req,
- &mut response,
- payment_intent.as_ref(),
- payment_attempt.as_ref(),
- billing_address.as_ref(),
- mca.connector_name.clone(),
- &state.conf.saved_payment_methods,
- )
- .await?;
- }
+ .await?;
}
// Filter out wallet payment method from mca if customer has already saved it
@@ -2867,18 +2796,20 @@ pub async fn call_surcharge_decision_management_for_saved_card(
#[allow(clippy::too_many_arguments)]
pub async fn filter_payment_methods(
- graph: &ConstraintGraph<'_, dir::DirValue>,
- payment_methods: &[serde_json::Value],
+ payment_methods: Vec<serde_json::Value>,
req: &mut api::PaymentMethodListRequest,
resp: &mut Vec<ResponsePaymentMethodIntermediate>,
payment_intent: Option<&storage::PaymentIntent>,
payment_attempt: Option<&storage::PaymentAttempt>,
address: Option<&domain::Address>,
connector: String,
+ config: &settings::ConnectorFilters,
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
saved_payment_methods: &settings::EligiblePaymentMethods,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
- for payment_method in payment_methods.iter() {
- let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method.clone());
+ for payment_method in payment_methods.into_iter() {
+ let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method);
if let Ok(payment_methods_enabled) = parse_result {
let payment_method = payment_methods_enabled.payment_method;
@@ -2909,13 +2840,57 @@ pub async fn filter_payment_methods(
.map(|minor_amount| minor_amount.get_amount_as_i64()),
)
{
- let payment_method_object = payment_method_type_info.clone();
+ let mut payment_method_object = payment_method_type_info;
+
+ let filter;
+ (
+ payment_method_object.accepted_countries,
+ req.accepted_countries,
+ filter,
+ ) = filter_pm_country_based(
+ &payment_method_object.accepted_countries,
+ &req.accepted_countries,
+ );
+ let filter2;
+ (
+ payment_method_object.accepted_currencies,
+ req.accepted_currencies,
+ filter2,
+ ) = filter_pm_currencies_based(
+ &payment_method_object.accepted_currencies,
+ &req.accepted_currencies,
+ );
- let pm_dir_value: dir::DirValue =
- (payment_method_type_info.payment_method_type, payment_method)
- .into_dir_value()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("pm_value_node not created")?;
+ let filter4 = filter_pm_card_network_based(
+ payment_method_object.card_networks.as_ref(),
+ req.card_networks.as_ref(),
+ &payment_method_object.payment_method_type,
+ );
+
+ let filter3 = if let Some(payment_intent) = payment_intent {
+ filter_payment_country_based(&payment_method_object, address).await?
+ && filter_payment_currency_based(payment_intent, &payment_method_object)
+ && filter_payment_amount_based(payment_intent, &payment_method_object)
+ && filter_payment_mandate_based(payment_attempt, &payment_method_object)
+ .await?
+ } else {
+ true
+ };
+
+ let filter5 = filter_pm_based_on_config(
+ config,
+ &connector,
+ &payment_method_object.payment_method_type,
+ payment_attempt,
+ &mut payment_method_object.card_networks,
+ &address.and_then(|inner| inner.country),
+ payment_attempt.and_then(|value| value.currency),
+ );
+
+ let filter6 = filter_pm_based_on_allowed_types(
+ allowed_payment_method_types.as_ref(),
+ &payment_method_object.payment_method_type,
+ );
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
@@ -2925,85 +2900,35 @@ pub async fn filter_payment_methods(
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector:?}")
})?;
-
- let mut context_values: Vec<dir::DirValue> = Vec::new();
- context_values.push(pm_dir_value.clone());
-
- payment_intent.map(|intent| {
- intent.currency.map(|currency| {
- context_values.push(dir::DirValue::PaymentCurrency(currency))
- })
- });
- address.map(|address| {
- address.country.map(|country| {
- context_values.push(dir::DirValue::BillingCountry(
- common_enums::Country::from_alpha2(country),
- ))
- })
- });
-
- // Addition of Connector to context
- if let Ok(connector) = api_enums::RoutableConnectors::from_str(
- connector_variant.to_string().as_str(),
- ) {
- context_values.push(dir::DirValue::Connector(Box::new(
- api_models::routing::ast::ConnectorChoice {
- connector,
- #[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: None,
- },
- )));
- };
-
- let filter_pm_based_on_allowed_types = filter_pm_based_on_allowed_types(
- allowed_payment_method_types.as_ref(),
- &payment_method_object.payment_method_type,
- );
-
- if payment_attempt
+ let filter7 = payment_attempt
.and_then(|attempt| attempt.mandate_details.as_ref())
- .is_some()
- {
- context_values.push(dir::DirValue::PaymentType(
- euclid::enums::PaymentType::NewMandate,
- ));
- };
+ .map(|_mandate_details| {
+ filter_pm_based_on_supported_payments_for_mandate(
+ supported_payment_methods_for_mandate,
+ &payment_method,
+ &payment_method_object.payment_method_type,
+ connector_variant,
+ )
+ })
+ .unwrap_or(true);
- payment_attempt
+ let filter8 = payment_attempt
.and_then(|attempt| attempt.mandate_data.as_ref())
.map(|mandate_detail| {
if mandate_detail.update_mandate_id.is_some() {
- context_values.push(dir::DirValue::PaymentType(
- euclid::enums::PaymentType::UpdateMandate,
- ));
+ filter_pm_based_on_update_mandate_support_for_connector(
+ supported_payment_methods_for_update_mandate,
+ &payment_method,
+ &payment_method_object.payment_method_type,
+ connector_variant,
+ )
+ } else {
+ true
}
- });
-
- payment_attempt
- .map(|attempt| {
- attempt.mandate_data.is_none() && attempt.mandate_details.is_none()
})
- .and_then(|res| {
- res.then(|| {
- context_values.push(dir::DirValue::PaymentType(
- euclid::enums::PaymentType::NonMandate,
- ))
- })
- });
-
- payment_attempt
- .and_then(|inner| inner.capture_method)
- .map(|capture_method| {
- context_values.push(dir::DirValue::CaptureMethod(capture_method));
- });
-
- let filter_pm_card_network_based = filter_pm_card_network_based(
- payment_method_object.card_networks.as_ref(),
- req.card_networks.as_ref(),
- &payment_method_object.payment_method_type,
- );
+ .unwrap_or(true);
- let saved_payment_methods_filter = req
+ let filter9 = req
.client_secret
.as_ref()
.map(|cs| {
@@ -3017,28 +2942,25 @@ pub async fn filter_payment_methods(
})
.unwrap_or(true);
- let context = AnalysisContext::from_dir_values(context_values.clone());
+ let connector = connector.clone();
- let result = graph.key_value_analysis(
- pm_dir_value.clone(),
- &context,
- &mut cgraph::Memoization::new(),
- &mut cgraph::CycleCheck::new(),
- None,
+ let response_pm_type = ResponsePaymentMethodIntermediate::new(
+ payment_method_object,
+ connector,
+ payment_method,
);
- if filter_pm_based_on_allowed_types
- && filter_pm_card_network_based
- && saved_payment_methods_filter
- && matches!(result, Ok(()))
+
+ if filter
+ && filter2
+ && filter3
+ && filter4
+ && filter5
+ && filter6
+ && filter7
+ && filter8
+ && filter9
{
- let response_pm_type = ResponsePaymentMethodIntermediate::new(
- payment_method_object,
- connector.clone(),
- payment_method,
- );
resp.push(response_pm_type);
- } else {
- logger::error!("Filtering Payment Methods Failed");
}
}
}
@@ -3046,12 +2968,287 @@ pub async fn filter_payment_methods(
}
Ok(())
}
+pub fn filter_pm_based_on_update_mandate_support_for_connector(
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ payment_method: &api_enums::PaymentMethod,
+ payment_method_type: &api_enums::PaymentMethodType,
+ connector: api_enums::Connector,
+) -> bool {
+ if payment_method == &api_enums::PaymentMethod::Card {
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .map(|payment_method_type_hm| {
+ let pm_credit = payment_method_type_hm
+ .0
+ .get(&api_enums::PaymentMethodType::Credit)
+ .map(|conn| conn.connector_list.clone())
+ .unwrap_or_default();
+ let pm_debit = payment_method_type_hm
+ .0
+ .get(&api_enums::PaymentMethodType::Debit)
+ .map(|conn| conn.connector_list.clone())
+ .unwrap_or_default();
+ &pm_credit | &pm_debit
+ })
+ .map(|supported_connectors| supported_connectors.contains(&connector))
+ .unwrap_or(false)
+ } else {
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
+ .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
+ .unwrap_or(false)
+ }
+}
-fn filter_pm_based_on_allowed_types(
- allowed_types: Option<&Vec<api_enums::PaymentMethodType>>,
+fn filter_pm_based_on_supported_payments_for_mandate(
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ payment_method: &api_enums::PaymentMethod,
payment_method_type: &api_enums::PaymentMethodType,
+ connector: api_enums::Connector,
) -> bool {
- allowed_types.map_or(true, |pm| pm.contains(payment_method_type))
+ supported_payment_methods_for_mandate
+ .0
+ .get(payment_method)
+ .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
+ .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
+ .unwrap_or(false)
+}
+
+fn filter_pm_based_on_config<'a>(
+ config: &'a settings::ConnectorFilters,
+ connector: &'a str,
+ payment_method_type: &'a api_enums::PaymentMethodType,
+ payment_attempt: Option<&storage::PaymentAttempt>,
+ card_network: &mut Option<Vec<api_enums::CardNetwork>>,
+ country: &Option<api_enums::CountryAlpha2>,
+ currency: Option<api_enums::Currency>,
+) -> bool {
+ config
+ .0
+ .get(connector)
+ .or_else(|| config.0.get("default"))
+ .and_then(|inner| match payment_method_type {
+ api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
+ let country_currency_filter = inner
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ .map(|value| global_country_currency_filter(value, country, currency));
+
+ card_network_filter(country, currency, card_network, inner);
+
+ let capture_method_filter = payment_attempt
+ .and_then(|inner| inner.capture_method)
+ .and_then(|capture_method| {
+ (capture_method == storage_enums::CaptureMethod::Manual).then(|| {
+ filter_pm_based_on_capture_method_used(inner, payment_method_type)
+ })
+ });
+
+ Some(
+ country_currency_filter.unwrap_or(true)
+ && capture_method_filter.unwrap_or(true),
+ )
+ }
+ payment_method_type => inner
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ .map(|value| global_country_currency_filter(value, country, currency)),
+ })
+ .unwrap_or(true)
+}
+
+///Filters the payment method list on basis of Capture methods, checks whether the connector issues Manual payments using cards or not if not it won't be visible in payment methods list
+fn filter_pm_based_on_capture_method_used(
+ payment_method_filters: &settings::PaymentMethodFilters,
+ payment_method_type: &api_enums::PaymentMethodType,
+) -> bool {
+ payment_method_filters
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ .and_then(|v| v.not_available_flows)
+ .and_then(|v| v.capture_method)
+ .map(|v| !matches!(v, api_enums::CaptureMethod::Manual))
+ .unwrap_or(true)
+}
+
+fn card_network_filter(
+ country: &Option<api_enums::CountryAlpha2>,
+ currency: Option<api_enums::Currency>,
+ card_network: &mut Option<Vec<api_enums::CardNetwork>>,
+ payment_method_filters: &settings::PaymentMethodFilters,
+) {
+ if let Some(value) = card_network.as_mut() {
+ let filtered_card_networks = value
+ .iter()
+ .filter(|&element| {
+ let key = settings::PaymentMethodFilterKey::CardNetwork(element.clone());
+ payment_method_filters
+ .0
+ .get(&key)
+ .map(|value| global_country_currency_filter(value, country, currency))
+ .unwrap_or(true)
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ *value = filtered_card_networks;
+ }
+}
+
+fn global_country_currency_filter(
+ item: &settings::CurrencyCountryFlowFilter,
+ country: &Option<api_enums::CountryAlpha2>,
+ currency: Option<api_enums::Currency>,
+) -> bool {
+ let country_condition = item
+ .country
+ .as_ref()
+ .zip(country.as_ref())
+ .map(|(lhs, rhs)| lhs.contains(rhs));
+ let currency_condition = item
+ .currency
+ .as_ref()
+ .zip(currency)
+ .map(|(lhs, rhs)| lhs.contains(&rhs));
+ country_condition.unwrap_or(true) && currency_condition.unwrap_or(true)
+}
+
+fn filter_pm_card_network_based(
+ pm_card_networks: Option<&Vec<api_enums::CardNetwork>>,
+ request_card_networks: Option<&Vec<api_enums::CardNetwork>>,
+ pm_type: &api_enums::PaymentMethodType,
+) -> bool {
+ match pm_type {
+ api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
+ match (pm_card_networks, request_card_networks) {
+ (Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
+ .iter()
+ .all(|card_network| pm_card_networks.contains(card_network)),
+ (None, Some(_)) => false,
+ _ => true,
+ }
+ }
+ _ => true,
+ }
+}
+fn filter_pm_country_based(
+ accepted_countries: &Option<admin::AcceptedCountries>,
+ req_country_list: &Option<Vec<api_enums::CountryAlpha2>>,
+) -> (
+ Option<admin::AcceptedCountries>,
+ Option<Vec<api_enums::CountryAlpha2>>,
+ bool,
+) {
+ match (accepted_countries, req_country_list) {
+ (None, None) => (None, None, true),
+ (None, Some(ref r)) => (
+ Some(admin::AcceptedCountries::EnableOnly(r.to_vec())),
+ Some(r.to_vec()),
+ true,
+ ),
+ (Some(l), None) => (Some(l.to_owned()), None, true),
+ (Some(l), Some(ref r)) => {
+ let updated = match l {
+ admin::AcceptedCountries::EnableOnly(acc) => {
+ filter_accepted_enum_based(&Some(acc.clone()), &Some(r.to_owned()))
+ .map(admin::AcceptedCountries::EnableOnly)
+ }
+
+ admin::AcceptedCountries::DisableOnly(den) => {
+ filter_disabled_enum_based(&Some(den.clone()), &Some(r.to_owned()))
+ .map(admin::AcceptedCountries::DisableOnly)
+ }
+
+ admin::AcceptedCountries::AllAccepted => {
+ Some(admin::AcceptedCountries::AllAccepted)
+ }
+ };
+
+ (updated, Some(r.to_vec()), true)
+ }
+ }
+}
+
+fn filter_pm_currencies_based(
+ accepted_currency: &Option<admin::AcceptedCurrencies>,
+ req_currency_list: &Option<Vec<api_enums::Currency>>,
+) -> (
+ Option<admin::AcceptedCurrencies>,
+ Option<Vec<api_enums::Currency>>,
+ bool,
+) {
+ match (accepted_currency, req_currency_list) {
+ (None, None) => (None, None, true),
+ (None, Some(ref r)) => (
+ Some(admin::AcceptedCurrencies::EnableOnly(r.to_vec())),
+ Some(r.to_vec()),
+ true,
+ ),
+ (Some(l), None) => (Some(l.to_owned()), None, true),
+ (Some(l), Some(ref r)) => {
+ let updated = match l {
+ admin::AcceptedCurrencies::EnableOnly(acc) => {
+ filter_accepted_enum_based(&Some(acc.clone()), &Some(r.to_owned()))
+ .map(admin::AcceptedCurrencies::EnableOnly)
+ }
+
+ admin::AcceptedCurrencies::DisableOnly(den) => {
+ filter_disabled_enum_based(&Some(den.clone()), &Some(r.to_owned()))
+ .map(admin::AcceptedCurrencies::DisableOnly)
+ }
+
+ admin::AcceptedCurrencies::AllAccepted => {
+ Some(admin::AcceptedCurrencies::AllAccepted)
+ }
+ };
+
+ (updated, Some(r.to_vec()), true)
+ }
+ }
+}
+
+fn filter_accepted_enum_based<T: Eq + std::hash::Hash + Clone>(
+ left: &Option<Vec<T>>,
+ right: &Option<Vec<T>>,
+) -> Option<Vec<T>> {
+ match (left, right) {
+ (Some(ref l), Some(ref r)) => {
+ let a: HashSet<&T> = HashSet::from_iter(l.iter());
+ let b: HashSet<&T> = HashSet::from_iter(r.iter());
+
+ let y: Vec<T> = a.intersection(&b).map(|&i| i.to_owned()).collect();
+ Some(y)
+ }
+ (Some(ref l), None) => Some(l.to_vec()),
+ (_, _) => None,
+ }
+}
+
+fn filter_disabled_enum_based<T: Eq + std::hash::Hash + Clone>(
+ left: &Option<Vec<T>>,
+ right: &Option<Vec<T>>,
+) -> Option<Vec<T>> {
+ match (left, right) {
+ (Some(ref l), Some(ref r)) => {
+ let mut enabled = Vec::new();
+ for element in r {
+ if !l.contains(element) {
+ enabled.push(element.to_owned());
+ }
+ }
+ Some(enabled)
+ }
+ (None, Some(r)) => Some(r.to_vec()),
+ (_, _) => None,
+ }
}
fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Option<i64>) -> bool {
@@ -3069,9 +3266,24 @@ fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Optio
.map(|max_amt| amt <= max_amt.into())
})
.unwrap_or(true);
+ // let min_check = match (amount, payment_method.minimum_amount) {
+ // (Some(amt), Some(min_amt)) => amt >= min_amt,
+ // (_, _) => true,
+ // };
+ // let max_check = match (amount, payment_method.maximum_amount) {
+ // (Some(amt), Some(max_amt)) => amt <= max_amt,
+ // (_, _) => true,
+ // };
(min_check && max_check) || amount == Some(0)
}
+fn filter_pm_based_on_allowed_types(
+ allowed_types: Option<&Vec<api_enums::PaymentMethodType>>,
+ payment_method_type: &api_enums::PaymentMethodType,
+) -> bool {
+ allowed_types.map_or(true, |pm| pm.contains(payment_method_type))
+}
+
fn filter_recurring_based(
payment_method: &RequestPaymentMethodTypes,
recurring_enabled: Option<bool>,
@@ -3088,23 +3300,54 @@ fn filter_installment_based(
})
}
-fn filter_pm_card_network_based(
- pm_card_networks: Option<&Vec<api_enums::CardNetwork>>,
- request_card_networks: Option<&Vec<api_enums::CardNetwork>>,
- pm_type: &api_enums::PaymentMethodType,
+async fn filter_payment_country_based(
+ pm: &RequestPaymentMethodTypes,
+ address: Option<&domain::Address>,
+) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
+ Ok(address.map_or(true, |address| {
+ address.country.as_ref().map_or(true, |country| {
+ pm.accepted_countries.as_ref().map_or(true, |ac| match ac {
+ admin::AcceptedCountries::EnableOnly(acc) => acc.contains(country),
+ admin::AcceptedCountries::DisableOnly(den) => !den.contains(country),
+ admin::AcceptedCountries::AllAccepted => true,
+ })
+ })
+ }))
+}
+
+fn filter_payment_currency_based(
+ payment_intent: &storage::PaymentIntent,
+ pm: &RequestPaymentMethodTypes,
) -> bool {
- match pm_type {
- api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
- match (pm_card_networks, request_card_networks) {
- (Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
- .iter()
- .all(|card_network| pm_card_networks.contains(card_network)),
- (None, Some(_)) => false,
- _ => true,
- }
- }
- _ => true,
- }
+ payment_intent.currency.map_or(true, |currency| {
+ pm.accepted_currencies.as_ref().map_or(true, |ac| match ac {
+ admin::AcceptedCurrencies::EnableOnly(acc) => acc.contains(&currency),
+ admin::AcceptedCurrencies::DisableOnly(den) => !den.contains(&currency),
+ admin::AcceptedCurrencies::AllAccepted => true,
+ })
+ })
+}
+
+fn filter_payment_amount_based(
+ payment_intent: &storage::PaymentIntent,
+ pm: &RequestPaymentMethodTypes,
+) -> bool {
+ let amount = payment_intent.amount.get_amount_as_i64();
+ (pm.maximum_amount.map_or(true, |amt| amount <= amt.into())
+ && pm.minimum_amount.map_or(true, |amt| amount >= amt.into()))
+ || payment_intent.amount.get_amount_as_i64() == 0
+}
+
+async fn filter_payment_mandate_based(
+ payment_attempt: Option<&storage::PaymentAttempt>,
+ pm: &RequestPaymentMethodTypes,
+) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
+ let recurring_filter = if !pm.recurring_enabled {
+ payment_attempt.map_or(true, |pa| pa.mandate_id.is_none())
+ } else {
+ true
+ };
+ Ok(recurring_filter)
}
pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs
index 3a32d3a741..1b9897f9f0 100644
--- a/crates/router/src/core/payment_methods/utils.rs
+++ b/crates/router/src/core/payment_methods/utils.rs
@@ -1,5 +1,5 @@
use std::{str::FromStr, sync::Arc};
-
+:
use api_models::{
admin::{self, PaymentMethodsEnabled},
enums as api_enums,
@@ -571,7 +571,7 @@ fn compile_accepted_countries_for_mca(
agg_nodes.push((
pm_object_country_value_node,
cgraph::Relation::Positive,
- cgraph::Strength::Weak,
+ cgraph::Strength::Strong,
));
}
admin::AcceptedCountries::DisableOnly(countries) => {
@@ -592,7 +592,7 @@ fn compile_accepted_countries_for_mca(
agg_nodes.push((
pm_object_country_value_node,
cgraph::Relation::Positive,
- cgraph::Strength::Weak,
+ cgraph::Strength::Strong,
));
}
admin::AcceptedCountries::AllAccepted => return Ok(None),
@@ -628,7 +628,7 @@ fn compile_accepted_countries_for_mca(
agg_nodes.push((
config_country_agg_node,
cgraph::Relation::Positive,
- cgraph::Strength::Weak,
+ cgraph::Strength::Strong,
));
}
}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index a176db2654..ab66b52c32 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -538,9 +538,6 @@ impl MerchantConnectorAccountInterface for Store {
cache::CacheKind::CGraph(
format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
),
- cache::CacheKind::PmFiltersCGraph(
- format!("pm_filters_cgraph_{}_{_profile_id}", _merchant_id).into(),
- ),
],
update_call,
)
@@ -598,9 +595,6 @@ impl MerchantConnectorAccountInterface for Store {
cache::CacheKind::CGraph(
format!("cgraph_{}_{_profile_id}", mca.merchant_id).into(),
),
- cache::CacheKind::PmFiltersCGraph(
- format!("pm_filters_cgraph_{}_{_profile_id}", mca.merchant_id).into(),
- ),
],
delete_call,
)
diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs
index 52d7777f5a..681b523db1 100644
--- a/crates/router/src/routes/metrics/bg_metrics_collector.rs
+++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs
@@ -11,7 +11,6 @@ pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: &Option<u16>
&cache::ACCOUNTS_CACHE,
&cache::ROUTING_CACHE,
&cache::CGRAPH_CACHE,
- &cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
];
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 81e7e38b1b..46aa3f8aa9 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -41,9 +41,6 @@ const SURCHARGE_CACHE_PREFIX: &str = "surcharge";
/// Prefix for cgraph cache key
const CGRAPH_CACHE_PREFIX: &str = "cgraph";
-/// Prefix for PM Filter cgraph cache key
-const PM_FILTERS_CGRAPH_CACHE_PREFIX: &str = "pm_filters_cgraph";
-
/// Prefix for all kinds of cache key
const ALL_CACHE_PREFIX: &str = "all_cache_kind";
@@ -86,16 +83,6 @@ pub static SURCHARGE_CACHE: Lazy<Cache> =
pub static CGRAPH_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
-/// PM Filter CGraph Cache
-pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| {
- Cache::new(
- "PM_FILTERS_CGRAPH_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
-
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
@@ -108,7 +95,6 @@ pub enum CacheKind<'a> {
DecisionManager(Cow<'a, str>),
Surcharge(Cow<'a, str>),
CGraph(Cow<'a, str>),
- PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
@@ -121,7 +107,6 @@ impl<'a> From<CacheKind<'a>> for RedisValue {
CacheKind::DecisionManager(s) => format!("{DECISION_MANAGER_CACHE_PREFIX},{s}"),
CacheKind::Surcharge(s) => format!("{SURCHARGE_CACHE_PREFIX},{s}"),
CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"),
- CacheKind::PmFiltersCGraph(s) => format!("{PM_FILTERS_CGRAPH_CACHE_PREFIX},{s}"),
CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"),
};
Self::from_string(value)
@@ -145,10 +130,6 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> {
}
SURCHARGE_CACHE_PREFIX => Ok(Self::Surcharge(Cow::Owned(split.1.to_string()))),
CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))),
- PM_FILTERS_CGRAPH_CACHE_PREFIX => {
- Ok(Self::PmFiltersCGraph(Cow::Owned(split.1.to_string())))
- }
-
ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))),
_ => Err(validation_err.into()),
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 7c4bd93681..a50de0a4ed 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -4,7 +4,7 @@ use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, DECISION_MANAGER_CACHE,
- PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SURCHARGE_CACHE,
+ ROUTING_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
@@ -100,16 +100,6 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
.await;
key
}
- CacheKind::PmFiltersCGraph(key) => {
- PM_FILTERS_CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: self.key_prefix.clone(),
- })
- .await;
-
- key
- }
CacheKind::Routing(key) => {
ROUTING_CACHE
.remove(CacheKey {
@@ -156,12 +146,6 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
prefix: self.key_prefix.clone(),
})
.await;
- PM_FILTERS_CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: self.key_prefix.clone(),
- })
- .await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),