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

feat(platform): implement platform payment list (#12483)

Ankit Kumar Guptaa7a4dd603b37
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 8eb3220b49..e4e156697f 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -44,6 +44,7 @@ use crate::{
PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest,
PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest,
PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse,
+ PlatformPaymentListConstraints, PlatformPaymentListFilters, PlatformPaymentListResponse,
},
};
@@ -528,6 +529,27 @@ impl ApiEventMetric for PaymentListFilterConstraints {
}
}
+#[cfg(feature = "v1")]
+impl ApiEventMetric for PlatformPaymentListConstraints {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for PlatformPaymentListResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for PlatformPaymentListFilters {
+ 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)
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5caa4b3693..26f15fc680 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -38,6 +38,7 @@ pub use self::recipient::{
RecipientBankAccount, RecipientDetails,
};
use crate::customers::CustomerDocumentDetails;
+
#[cfg(any(feature = "v1", feature = "v2"))]
pub(crate) fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>
where
@@ -9308,6 +9309,273 @@ pub struct PaymentListResponse {
pub data: Vec<PaymentsListResponseItem>,
}
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct PlatformPaymentListConstraints {
+ /// The identifier for payment
+ pub payment_id: Option<id_type::PaymentId>,
+
+ /// The identifier for business profile
+ pub profile_id: Option<id_type::ProfileId>,
+
+ /// The connected (processor) merchant id to filter the list by.
+ /// When omitted, payments across all connected merchants under the platform are returned.
+ pub processor_merchant_id: Option<id_type::MerchantId>,
+
+ /// The identifier for customer
+ pub customer_id: Option<id_type::CustomerId>,
+
+ /// limit on the number of objects to return
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
+
+ /// The starting point within a list of objects
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
+
+ /// The created-at time range (`start_time` / `end_time`) to filter payments by.
+ #[serde(flatten)]
+ pub time_range: Option<TimeRange>,
+
+ /// The start amount (inclusive) to filter payments by.
+ pub start_amount: Option<i64>,
+
+ /// The end amount (inclusive) to filter payments by.
+ pub end_amount: Option<i64>,
+
+ /// The comma separated list of connectors to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub connector: Option<Vec<api_enums::Connector>>,
+
+ /// The comma separated list of currencies to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub currency: Option<Vec<enums::Currency>>,
+
+ /// The comma separated list of payment status to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub status: Option<Vec<enums::IntentStatus>>,
+
+ /// The comma separated list of payment methods to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub payment_method: Option<Vec<enums::PaymentMethod>>,
+
+ /// The comma separated list of payment method types to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub payment_method_type: Option<Vec<enums::PaymentMethodType>>,
+
+ /// The comma separated list of authentication types to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub authentication_type: Option<Vec<enums::AuthenticationType>>,
+
+ /// The comma separated list of merchant connector ids to filter payments list for selected label
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+
+ /// The comma separated list of card networks to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub card_network: Option<Vec<enums::CardNetwork>>,
+
+ /// The comma separated list of card discovery methods to filter payments list
+ #[serde(deserialize_with = "parse_comma_separated", default)]
+ pub card_discovery: Option<Vec<enums::CardDiscovery>>,
+
+ /// The identifier for merchant order reference id
+ pub merchant_order_reference_id: Option<String>,
+
+ /// The field (`on`) and direction (`by`) on which the payments list should be sorted.
+ #[serde(flatten)]
+ pub order: Option<Order>,
+}
+
+/// A single item in the platform payments list.
+///
+/// Built directly from raw diesel rows with no decryption, since a platform listing spans many
+/// connected merchants each with their own key store. Encrypted/PII fields (customer, billing,
+/// shipping, payment method data) and `connector_response_metadata` (derived on the domain
+/// `PaymentAttempt`) are therefore omitted. Use the single-payment retrieve (scoped to the
+/// connected merchant) when full PII is required.
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PlatformPaymentListItem {
+ /// Unique identifier for the payment.
+ pub payment_id: id_type::PaymentId,
+
+ /// Identifier of the platform merchant. Equals the caller's merchant id.
+ pub merchant_id: id_type::MerchantId,
+
+ /// Identifier of the connected merchant that owns this payment.
+ pub processor_merchant_id: Option<id_type::MerchantId>,
+
+ pub status: api_enums::IntentStatus,
+
+ /// Amount in lowest denomination of the currency.
+ pub amount: MinorUnit,
+
+ /// Net amount of the active attempt.
+ pub net_amount: Option<MinorUnit>,
+
+ /// Amount still capturable on the active attempt.
+ pub amount_capturable: MinorUnit,
+
+ /// The current state metadata of the payment intent.
+ pub state_metadata: Option<common_types::payments::PaymentIntentStateMetadata>,
+
+ /// A secret token unique to this payment intent.
+ pub client_secret: Option<Secret<String>>,
+
+ #[serde(with = "common_utils::custom_serde::iso8601::option", default)]
+ pub created: Option<PrimitiveDateTime>,
+
+ #[serde(with = "common_utils::custom_serde::iso8601::option", default)]
+ pub modified_at: Option<PrimitiveDateTime>,
+
+ pub currency: Option<api_enums::Currency>,
+
+ /// Reference id of the customer (PII fields are intentionally excluded for platform listings).
+ pub customer_id: Option<id_type::CustomerId>,
+
+ /// Description of the payment.
+ pub description: Option<String>,
+
+ /// Order details associated with the payment.
+ pub order_details: Option<Vec<pii::SecretSerdeValue>>,
+
+ /// Connector used on the active attempt.
+ pub connector: Option<String>,
+
+ /// Payment method of the active attempt.
+ pub payment_method: Option<api_enums::PaymentMethod>,
+
+ /// Payment method type of the active attempt.
+ pub payment_method_type: Option<api_enums::PaymentMethodType>,
+
+ /// The business label of the profile under which this payment was processed.
+ pub business_label: Option<String>,
+
+ /// The business country of the profile under which this payment was processed.
+ pub business_country: Option<api_enums::CountryAlpha2>,
+
+ /// An optional sub-label for the business unit on the active attempt.
+ pub business_sub_label: Option<String>,
+
+ pub setup_future_usage: Option<api_enums::FutureUsage>,
+
+ pub capture_method: Option<api_enums::CaptureMethod>,
+
+ pub authentication_type: Option<api_enums::AuthenticationType>,
+
+ /// Connector's transaction id for the active attempt.
+ pub connector_transaction_id: Option<String>,
+
+ /// Total number of payment attempts associated with this payment.
+ pub attempt_count: i16,
+
+ /// Identifier of the business profile under which this payment was created.
+ pub profile_id: Option<id_type::ProfileId>,
+
+ /// The merchant connector account id used on the active attempt.
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
+
+ /// Merchant-supplied order reference id.
+ pub merchant_order_reference_id: Option<String>,
+
+ /// Merchant-supplied metadata.
+ pub metadata: Option<serde_json::Value>,
+
+ /// A human-readable error message from the active attempt, if the payment failed.
+ pub error_message: Option<String>,
+
+ /// Date time at which the payment was last updated.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub updated: Option<PrimitiveDateTime>,
+
+ /// Whether extended authorization is applied on this payment.
+ pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
+
+ /// Date time at which extended authorization was last applied.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub extended_authorization_last_applied_at: Option<PrimitiveDateTime>,
+
+ /// Date time after which this payment cannot be captured.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub capture_before: Option<PrimitiveDateTime>,
+
+ /// Method through which the card was discovered.
+ pub card_discovery: Option<enums::CardDiscovery>,
+
+ /// The category of a Merchant Initiated Transaction (MIT).
+ pub mit_category: Option<api_enums::MitCategory>,
+
+ /// The tokenization preference for the payment method.
+ pub tokenization: Option<enums::Tokenization>,
+
+ /// Whether 3ds challenge is forced.
+ pub force_3ds_challenge: Option<bool>,
+
+ /// Whether 3ds challenge is triggered.
+ pub force_3ds_challenge_trigger: Option<bool>,
+
+ /// Error code received from the issuer in case of failed payments.
+ pub issuer_error_code: Option<String>,
+
+ /// Error message received from the issuer in case of failed payments.
+ pub issuer_error_message: Option<String>,
+
+ /// Whether the redirection has to open in the iframe.
+ pub is_iframe_redirection_enabled: Option<bool>,
+
+ /// Indicates how the payment was initiated.
+ pub payment_channel: Option<common_enums::PaymentChannel>,
+
+ /// Whether partial authorization is allowed for this payment.
+ pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
+
+ /// Whether overcapture must be requested for this payment.
+ pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>,
+
+ /// Whether overcapture is effectively enabled for this payment.
+ pub is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
+
+ /// Card network response details (e.g. Visa/Mastercard advice codes).
+ pub network_details: Option<NetworkDetails>,
+
+ /// Whether this payment method is stored and previously used.
+ pub is_stored_credential: Option<bool>,
+
+ /// Whether extended authorization was requested for this payment.
+ pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
+
+ /// Billing descriptor information for the payment.
+ pub billing_descriptor: Option<common_types::payments::BillingDescriptor>,
+
+ /// Information identifying partner and merchant details.
+ pub partner_merchant_identifier_details:
+ Option<common_types::payments::PartnerMerchantIdentifierDetails>,
+
+ /// Installment selection confirmed by the customer for this payment.
+ pub installment_data: Option<common_types::payments::InstallmentData>,
+
+ /// A connector-specific identifier representing the stored payment instrument.
+ pub sender_payment_instrument_id: Option<String>,
+
+ /// Surcharge and tax-on-surcharge applied on the active attempt.
+ pub surcharge_details: Option<RequestSurchargeDetails>,
+
+ /// Installment options available/selected for this payment.
+ pub installment_options: Option<Vec<common_types::payments::InstallmentOption>>,
+}
+
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PlatformPaymentListResponse {
+ /// The number of payments included in the current response.
+ pub count: usize,
+ /// The total number of payments matching the given constraints (ignores limit/offset).
+ pub total_count: i64,
+ /// The list of payment summaries across the platform's connected merchants.
+ pub data: Vec<PlatformPaymentListItem>,
+}
+
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, ToSchema)]
pub struct RecoveryPaymentListResponse {
@@ -9478,6 +9746,27 @@ pub struct PaymentListFiltersV2 {
pub card_discovery: Vec<enums::CardDiscovery>,
}
+/// Available filter values for a platform payments list, aggregated across all of the
+/// platform's connected merchants.
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PlatformPaymentListFilters {
+ /// The available connector filters, keyed by connector name
+ pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,
+ /// The list of available currency filters
+ pub currency: Vec<enums::Currency>,
+ /// The list of available payment status filters
+ pub status: Vec<enums::IntentStatus>,
+ /// The available payment methods and their corresponding payment method types
+ pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
+ /// The list of available authentication types
+ pub authentication_type: Vec<enums::AuthenticationType>,
+ /// The list of available card networks
+ pub card_network: Vec<enums::CardNetwork>,
+ /// The list of available card discovery methods
+ pub card_discovery: Vec<enums::CardDiscovery>,
+}
+
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsAggregateResponse {
/// The list of intent status with their count
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 45c430a6b9..4972e192ca 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -93,6 +93,26 @@ pub trait PaymentIntentInterface {
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>;
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_filtered_payment_intents_attempt_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<
+ Vec<(
+ DieselPaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>,
+ Self::Error,
+ >;
+
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_payment_intents_attempt_count_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<i64, Self::Error>;
+
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
@@ -1836,6 +1856,7 @@ pub struct PaymentIntentListParams {
pub card_discovery: Option<Vec<common_enums::CardDiscovery>>,
pub merchant_order_reference_id: Option<String>,
pub customer_email: Option<Email>,
+ pub processor_merchant_id: Option<Vec<id_type::MerchantId>>,
}
#[cfg(feature = "v2")]
@@ -1898,6 +1919,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
card_discovery: None,
merchant_order_reference_id: None,
customer_email: None,
+ processor_merchant_id: None,
}))
}
}
@@ -1990,6 +2012,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
card_discovery: None,
merchant_order_reference_id: None,
customer_email: None,
+ processor_merchant_id: None,
}))
}
}
@@ -2053,6 +2076,69 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
card_discovery,
merchant_order_reference_id,
customer_email,
+ processor_merchant_id: None,
+ }))
+ }
+ }
+}
+
+#[cfg(feature = "v1")]
+impl From<api_models::payments::PlatformPaymentListConstraints> for PaymentIntentFetchConstraints {
+ fn from(value: api_models::payments::PlatformPaymentListConstraints) -> Self {
+ let api_models::payments::PlatformPaymentListConstraints {
+ payment_id,
+ profile_id,
+ processor_merchant_id,
+ customer_id,
+ limit,
+ offset,
+ time_range,
+ start_amount,
+ end_amount,
+ connector,
+ currency,
+ status,
+ payment_method,
+ payment_method_type,
+ authentication_type,
+ merchant_connector_id,
+ card_network,
+ card_discovery,
+ merchant_order_reference_id,
+ order,
+ } = value;
+ if let Some(payment_intent_id) = payment_id {
+ Self::Single { payment_intent_id }
+ } else {
+ Self::List(Box::new(PaymentIntentListParams {
+ offset,
+ starting_at: time_range.map(|time_range| time_range.start_time),
+ ending_at: time_range.and_then(|time_range| time_range.end_time),
+ amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some(
+ api_models::payments::AmountFilter {
+ start_amount,
+ end_amount,
+ },
+ ),
+ connector,
+ currency,
+ status,
+ payment_method,
+ payment_method_type,
+ authentication_type,
+ merchant_connector_id,
+ profile_id: profile_id.map(|profile_id| vec![profile_id]),
+ customer_id,
+ starting_after_id: None,
+ ending_before_id: None,
+ limit,
+ order: order.unwrap_or_default(),
+ card_network,
+ card_discovery,
+ merchant_order_reference_id,
+ customer_email: None,
+ processor_merchant_id: processor_merchant_id
+ .map(|processor_merchant_id| vec![processor_merchant_id]),
}))
}
}
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index c197962cba..1a9d64e6cd 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -641,7 +641,7 @@ pub async fn payment_intent_list(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::list_payments(state, auth.platform, None, req)
+ payments::list::list_payments(state, auth.platform, None, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
allow_connected_scope_operation: true,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 3113a0295a..927e02821c 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2,9 +2,13 @@ use hyperswitch_domain_models::mandates;
pub mod access_token;
pub mod conditional_configs;
pub mod customers;
+#[cfg(feature = "olap")]
+pub mod filters;
pub mod flows;
pub mod gateway;
pub mod helpers;
+#[cfg(feature = "olap")]
+pub mod list;
pub mod operations;
pub mod session_token;
@@ -34,8 +38,6 @@ pub mod payment_methods;
#[cfg(feature = "v2")]
use std::future;
-#[cfg(feature = "olap")]
-use api_models::admin::MerchantConnectorInfo;
#[cfg(feature = "v2")]
use api_models::payments::RevenueRecoveryGetIntentResponse;
use api_models::{
@@ -88,8 +90,6 @@ use rustc_hash::FxHashMap;
use scheduler::utils as pt_utils;
#[cfg(feature = "v2")]
pub use session_operation::payments_session_core;
-#[cfg(feature = "olap")]
-use strum::IntoEnumIterator;
#[cfg(feature = "v1")]
pub use self::operations::{
@@ -11010,529 +11010,6 @@ pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool {
matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
}
-#[cfg(all(feature = "olap", feature = "v1"))]
-pub async fn list_payments(
- state: SessionState,
- platform: domain::Platform,
- profile_id_list: Option<Vec<id_type::ProfileId>>,
- constraints: api::PaymentListConstraints,
-) -> RouterResponse<api::PaymentListResponse> {
- let processor_merchant_id = platform.get_processor().get_account().get_id();
- let db = state.store.as_ref();
- let payment_intents = helpers::filter_by_constraints(
- &state,
- &(constraints, profile_id_list).try_into()?,
- processor_merchant_id,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
- let collected_futures = payment_intents.into_iter().map(|pi| {
- async {
- match db
- .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(
- &pi.payment_id,
- processor_merchant_id,
- &pi.active_attempt.get_id(),
- // since OLAP doesn't have KV. Force to get the data from PSQL.
- storage_enums::MerchantStorageScheme::PostgresOnly,
- platform.get_processor().get_key_store(),
- )
- .await
- {
- Ok(pa) => Some(Ok((pi, pa))),
- Err(error) => {
- if matches!(
- error.current_context(),
- errors::StorageError::ValueNotFound(_)
- ) {
- logger::warn!(
- ?error,
- "payment_attempts missing for payment_id : {:?}",
- pi.payment_id,
- );
- return None;
- }
- Some(Err(error))
- }
- }
- }
- });
-
- //If any of the response are Err, we will get Result<Err(_)>
- let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> =
- join_all(collected_futures)
- .await
- .into_iter()
- .flatten() //Will ignore `None`, will only flatten 1 level
- .collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>();
- //Will collect responses in same order async, leading to sorted responses
-
- //Converting Intent-Attempt array to Response if no error
- let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .into_iter()
- .map(ForeignFrom::foreign_from)
- .collect();
-
- Ok(services::ApplicationResponse::Json(
- api::PaymentListResponse {
- size: data.len(),
- data,
- },
- ))
-}
-
-#[cfg(all(feature = "v2", feature = "olap"))]
-pub async fn list_payments(
- state: SessionState,
- platform: domain::Platform,
- constraints: api::PaymentListConstraints,
-) -> RouterResponse<payments_api::PaymentListResponse> {
- common_utils::metrics::utils::record_operation_time(
- async {
- let db: &dyn StorageInterface = state.store.as_ref();
- let fetch_constraints = constraints.clone().into();
- let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
- .get_filtered_payment_intents_attempt(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let data: Vec<api_models::payments::PaymentsListResponseItem> =
- list.into_iter().map(ForeignFrom::foreign_from).collect();
-
- let active_attempt_ids = db
- .get_filtered_active_attempt_ids_for_total_count(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while retrieving active_attempt_ids for merchant")?;
-
- let total_count = if constraints.has_no_attempt_filters() {
- i64::try_from(active_attempt_ids.len())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while converting from usize to i64")
- } else {
- let active_attempt_ids = active_attempt_ids
- .into_iter()
- .flatten()
- .collect::<Vec<String>>();
-
- db.get_total_count_of_filtered_payment_attempts(
- platform.get_processor().get_account().get_id(),
- &active_attempt_ids,
- constraints.connector,
- constraints.payment_method_type,
- constraints.payment_method_subtype,
- constraints.authentication_type,
- constraints.merchant_connector_id,
- constraints.card_network,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while retrieving total count of payment attempts")
- }?;
-
- Ok(services::ApplicationResponse::Json(
- api_models::payments::PaymentListResponse {
- count: data.len(),
- total_count,
- data,
- },
- ))
- },
- &metrics::PAYMENT_LIST_LATENCY,
- router_env::metric_attributes!((
- "merchant_id",
- platform.get_processor().get_account().get_id().clone()
- )),
- )
- .await
-}
-
-#[cfg(all(feature = "v2", feature = "olap"))]
-pub async fn revenue_recovery_list_payments(
- state: SessionState,
- platform: domain::Platform,
- constraints: api::PaymentListConstraints,
-) -> RouterResponse<payments_api::RecoveryPaymentListResponse> {
- common_utils::metrics::utils::record_operation_time(
- async {
- // `limit` is a `PageSize`, already validated at deserialize; no extra check needed.
- let db: &dyn StorageInterface = state.store.as_ref();
- let fetch_constraints = constraints.clone().into();
- let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
- .get_filtered_payment_intents_attempt(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
- // Get all billing connector account IDs
- let billing_connector_ids: Vec<_> = list
- .iter()
- .map(|(payment_intent, _)| {
- payment_intent.get_billing_merchant_connector_account_id()
- })
- .collect();
-
- // Create futures for workflow lookups
- let workflow_futures: Vec<_> = list
- .iter()
- .map(|(payment_intent, _)| get_workflow_entries(&state, &payment_intent.id))
- .collect();
-
- let billing_connector_futures: Vec<_> = billing_connector_ids
- .into_iter()
- .map(|billing_mca_id| {
- let platform_clone = platform.clone(); // Clone for each future
- async move {
- if let Some(billing_mca_id) = billing_mca_id {
- db.find_merchant_connector_account_by_id(
- &billing_mca_id,
- platform_clone.get_processor().get_key_store(),
- )
- .await
- .ok()
- } else {
- None
- }
- }
- })
- .collect();
-
- let workflow_results = join_all(workflow_futures).await;
- let billing_connector_results = join_all(billing_connector_futures).await;
-
- let data: Vec<api_models::payments::RecoveryPaymentsListResponseItem> = list
- .into_iter()
- .zip(workflow_results)
- .zip(billing_connector_results)
- .map(
- |(
- ((payment_intent, payment_attempt), workflow_result),
- billing_connector_account,
- )| {
- let (calculate_workflow, execute_workflow) =
- workflow_result.unwrap_or((None, None));
-
- // Get retry threshold from billing connector account
- let max_retry_threshold = billing_connector_account
- .as_ref()
- .and_then(|mca| mca.get_retry_threshold())
- .unwrap_or(0); // Default fallback
-
- // Use custom mapping function
- map_to_recovery_payment_item(
- payment_intent,
- payment_attempt,
- calculate_workflow,
- execute_workflow,
- max_retry_threshold.try_into().unwrap_or(0),
- )
- },
- )
- .collect();
-
- let active_attempt_ids = db
- .get_filtered_active_attempt_ids_for_total_count(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while retrieving active_attempt_ids for merchant")?;
-
- let total_count = if constraints.has_no_attempt_filters() {
- i64::try_from(active_attempt_ids.len())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while converting from usize to i64")
- } else {
- let active_attempt_ids = active_attempt_ids
- .into_iter()
- .flatten()
- .collect::<Vec<String>>();
-
- db.get_total_count_of_filtered_payment_attempts(
- platform.get_processor().get_account().get_id(),
- &active_attempt_ids,
- constraints.connector,
- constraints.payment_method_type,
- constraints.payment_method_subtype,
- constraints.authentication_type,
- constraints.merchant_connector_id,
- constraints.card_network,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while retrieving total count of payment attempts")
- }?;
-
- Ok(services::ApplicationResponse::Json(
- api_models::payments::RecoveryPaymentListResponse {
- count: data.len(),
- total_count,
- data,
- },
- ))
- },
- &metrics::PAYMENT_LIST_LATENCY,
- router_env::metric_attributes!((
- "merchant_id",
- platform.get_processor().get_account().get_id().clone()
- )),
- )
- .await
-}
-
-#[cfg(all(feature = "olap", feature = "v1"))]
-pub async fn apply_filters_on_payments(
- state: SessionState,
- platform: domain::Platform,
- _profile_id_list: Option<Vec<id_type::ProfileId>>,
- constraints: api::PaymentListFilterConstraints,
-) -> RouterResponse<api::PaymentListResponseV2> {
- common_utils::metrics::utils::record_operation_time(
- async {
- let db: &dyn StorageInterface = state.store.as_ref();
- let fetch_constraints = constraints.clone().into();
- let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
- .get_filtered_payment_intents_attempt(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let data: Vec<api::PaymentsResponse> =
- list.into_iter().map(ForeignFrom::foreign_from).collect();
-
- let active_attempt_ids = db
- .get_filtered_active_attempt_ids_for_total_count(
- platform.get_processor().get_account().get_id(),
- &fetch_constraints,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
-
- let total_count = if constraints.has_no_attempt_filters() {
- i64::try_from(active_attempt_ids.len())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while converting from usize to i64")
- } else {
- db.get_total_count_of_filtered_payment_attempts(
- platform.get_processor().get_account().get_id(),
- &active_attempt_ids,
- constraints.connector,
- constraints.payment_method,
- constraints.payment_method_type,
- constraints.authentication_type,
- constraints.merchant_connector_id,
- constraints.card_network,
- constraints.card_discovery,
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- }?;
-
- Ok(services::ApplicationResponse::Json(
- api::PaymentListResponseV2 {
- count: data.len(),
- total_count,
- data,
- },
- ))
- },
- &metrics::PAYMENT_LIST_LATENCY,
- router_env::metric_attributes!((
- "merchant_id",
- platform.get_processor().get_account().get_id().clone()
- )),
- )
- .await
-}
-
-#[cfg(all(feature = "olap", feature = "v1"))]
-pub async fn get_filters_for_payments(
- state: SessionState,
- platform: domain::Platform,
- time_range: common_utils::types::TimeRange,
-) -> RouterResponse<api::PaymentListFilters> {
- let db = state.store.as_ref();
- let pi = db
- .filter_payment_intents_by_time_range_constraints(
- platform.get_processor().get_account().get_id(),
- &time_range,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
- let filters = db
- .get_filters_for_payments(
- pi.as_slice(),
- platform.get_processor().get_account().get_id(),
- // since OLAP doesn't have KV. Force to get the data from PSQL.
- storage_enums::MerchantStorageScheme::PostgresOnly,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
- Ok(services::ApplicationResponse::Json(
- api::PaymentListFilters {
- connector: filters.connector,
- currency: filters.currency,
- status: filters.status,
- payment_method: filters.payment_method,
- payment_method_type: filters.payment_method_type,
- authentication_type: filters.authentication_type,
- },
- ))
-}
-
-#[cfg(feature = "olap")]
-pub async fn get_payment_filters(
- state: SessionState,
- platform: domain::Platform,
- profile_id_list: Option<Vec<id_type::ProfileId>>,
-) -> RouterResponse<api::PaymentListFiltersV2> {
- let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
- super::admin::list_payment_connectors(
- state,
- platform.get_processor().clone(),
- profile_id_list,
- )
- .await?
- {
- data
- } else {
- return Err(errors::ApiErrorResponse::InternalServerError.into());
- };
-
- let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();
- let mut payment_method_types_map: HashMap<
- enums::PaymentMethod,
- HashSet<enums::PaymentMethodType>,
- > = HashMap::new();
-
- // populate connector map
- merchant_connector_accounts
- .iter()
- .filter_map(|merchant_connector_account| {
- merchant_connector_account
- .connector_label
- .as_ref()
- .map(|label| {
- let info = merchant_connector_account.to_merchant_connector_info(label);
- (merchant_connector_account.get_connector_name(), info)
- })
- })
- .for_each(|(connector_name, info)| {
- connector_map
- .entry(connector_name.to_string())
- .or_default()
- .push(info);
- });
-
- // populate payment method type map
- merchant_connector_accounts
- .iter()
- .flat_map(|merchant_connector_account| {
- merchant_connector_account.payment_methods_enabled.as_ref()
- })
- .map(|payment_methods_enabled| {
- payment_methods_enabled
- .iter()
- .filter_map(|payment_method_enabled| {
- payment_method_enabled
- .get_payment_method_type()
- .map(|types_vec| {
- (
- payment_method_enabled.get_payment_method(),
- types_vec.clone(),
- )
- })
- })
- })
- .for_each(|payment_methods_enabled| {
- payment_methods_enabled.for_each(
- |(payment_method_option, payment_method_types_vec)| {
- if let Some(payment_method) = payment_method_option {
- payment_method_types_map
- .entry(payment_method)
- .or_default()
- .extend(payment_method_types_vec.iter().filter_map(
- |req_payment_method_types| {
- req_payment_method_types.get_payment_method_type()
- },
- ));
- }
- },
- );
- });
-
- Ok(services::ApplicationResponse::Json(
- api::PaymentListFiltersV2 {
- connector: connector_map,
- currency: enums::Currency::iter().collect(),
- status: enums::IntentStatus::iter().collect(),
- payment_method: payment_method_types_map,
- authentication_type: enums::AuthenticationType::iter().collect(),
- card_network: enums::CardNetwork::iter().collect(),
- card_discovery: enums::CardDiscovery::iter().collect(),
- },
- ))
-}
-
-#[cfg(feature = "olap")]
-pub async fn get_aggregates_for_payments(
- state: SessionState,
- platform: domain::Platform,
- profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: common_utils::types::TimeRange,
-) -> RouterResponse<api::PaymentsAggregateResponse> {
- let db = state.store.as_ref();
- let intent_status_with_count = db
- .get_intent_status_with_count(
- platform.get_processor().get_account().get_id(),
- profile_id_list,
- &time_range,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
-
- let mut status_map: HashMap<enums::IntentStatus, i64> =
- intent_status_with_count.into_iter().collect();
- for status in enums::IntentStatus::iter() {
- status_map.entry(status).or_default();
- }
-
- Ok(services::ApplicationResponse::Json(
- api::PaymentsAggregateResponse {
- status_with_count: status_map,
- },
- ))
-}
-
#[cfg(feature = "v1")]
pub async fn add_process_sync_task(
db: &dyn StorageInterface,
diff --git a/crates/router/src/core/payments/filters.rs b/crates/router/src/core/payments/filters.rs
new file mode 100644
index 0000000000..6ea9c00367
--- /dev/null
+++ b/crates/router/src/core/payments/filters.rs
@@ -0,0 +1,319 @@
+use std::collections::{HashMap, HashSet};
+
+use api_models::{admin::MerchantConnectorInfo, enums};
+use common_utils::id_type;
+#[cfg(feature = "v1")]
+use error_stack::{report, ResultExt};
+use strum::IntoEnumIterator;
+
+#[cfg(feature = "v1")]
+use crate::types::storage::enums as storage_enums;
+use crate::{
+ core::{
+ admin,
+ errors::{self, RouterResponse, StorageErrorExt},
+ },
+ routes::SessionState,
+ services,
+ types::{api, domain},
+};
+
+/// Available filter values for a platform, aggregated across all of its connected merchants.
+///
+/// Connectors and payment methods are derived from the *configured* merchant connector
+/// accounts of every connected merchant under the platform's organization (not from payment
+/// data), mirroring [`get_payment_filters`]. The remaining filters (currency, status,
+/// authentication type, card network, card discovery) are the full set of supported values.
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn get_platform_payment_filters(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+) -> RouterResponse<api::PlatformPaymentListFilters> {
+ // This endpoint is exclusively for platform merchants - not connected, not standard.
+ common_utils::fp_utils::when(
+ !platform.get_provider().get_account().is_platform_account(),
+ || {
+ Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
+ "Platform payment filters are only accessible to platform merchants",
+ )
+ },
+ )?;
+
+ let db = state.store.as_ref();
+
+ // Every connected merchant lives under the platform's organization.
+ let merchant_accounts = db
+ .list_merchant_accounts_by_organization_id(
+ platform.get_provider().get_account().get_org_id(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();
+ let mut payment_method_types_map: HashMap<
+ enums::PaymentMethod,
+ HashSet<enums::PaymentMethodType>,
+ > = HashMap::new();
+
+ for connected_account in merchant_accounts.into_iter().filter(|account| {
+ account.merchant_account_type == common_enums::MerchantAccountType::Connected
+ }) {
+ let merchant_id = connected_account.get_id().clone();
+ let key_store = db
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &db.get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
+
+ // `list_payment_connectors` operates on a processor identity; build one for this
+ // connected merchant (provider == processor since we are not acting on its behalf).
+ let processor = domain::Platform::new(
+ connected_account.clone(),
+ key_store.clone(),
+ connected_account,
+ key_store,
+ None,
+ )
+ .get_processor()
+ .clone();
+
+ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
+ admin::list_payment_connectors(state.clone(), processor, profile_id_list.clone())
+ .await?
+ {
+ data
+ } else {
+ return Err(errors::ApiErrorResponse::InternalServerError.into());
+ };
+
+ // populate connector map
+ merchant_connector_accounts
+ .iter()
+ .filter_map(|merchant_connector_account| {
+ merchant_connector_account
+ .connector_label
+ .as_ref()
+ .map(|label| {
+ let info = merchant_connector_account.to_merchant_connector_info(label);
+ (merchant_connector_account.get_connector_name(), info)
+ })
+ })
+ .for_each(|(connector_name, info)| {
+ connector_map
+ .entry(connector_name.to_string())
+ .or_default()
+ .push(info);
+ });
+
+ // populate payment method type map
+ merchant_connector_accounts
+ .iter()
+ .flat_map(|merchant_connector_account| {
+ merchant_connector_account.payment_methods_enabled.as_ref()
+ })
+ .map(|payment_methods_enabled| {
+ payment_methods_enabled
+ .iter()
+ .filter_map(|payment_method_enabled| {
+ payment_method_enabled
+ .get_payment_method_type()
+ .map(|types_vec| {
+ (
+ payment_method_enabled.get_payment_method(),
+ types_vec.clone(),
+ )
+ })
+ })
+ })
+ .for_each(|payment_methods_enabled| {
+ payment_methods_enabled.for_each(
+ |(payment_method_option, payment_method_types_vec)| {
+ if let Some(payment_method) = payment_method_option {
+ payment_method_types_map
+ .entry(payment_method)
+ .or_default()
+ .extend(payment_method_types_vec.iter().filter_map(
+ |req_payment_method_types| {
+ req_payment_method_types.get_payment_method_type()
+ },
+ ));
+ }
+ },
+ );
+ });
+ }
+
+ Ok(services::ApplicationResponse::Json(
+ api::PlatformPaymentListFilters {
+ connector: connector_map,
+ currency: enums::Currency::iter().collect(),
+ status: enums::IntentStatus::iter().collect(),
+ payment_method: payment_method_types_map,
+ authentication_type: enums::AuthenticationType::iter().collect(),
+ card_network: enums::CardNetwork::iter().collect(),
+ card_discovery: enums::CardDiscovery::iter().collect(),
+ },
+ ))
+}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn get_filters_for_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ time_range: common_utils::types::TimeRange,
+) -> RouterResponse<api::PaymentListFilters> {
+ let db = state.store.as_ref();
+ let pi = db
+ .filter_payment_intents_by_time_range_constraints(
+ platform.get_processor().get_account().get_id(),
+ &time_range,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let filters = db
+ .get_filters_for_payments(
+ pi.as_slice(),
+ platform.get_processor().get_account().get_id(),
+ // since OLAP doesn't have KV. Force to get the data from PSQL.
+ storage_enums::MerchantStorageScheme::PostgresOnly,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListFilters {
+ connector: filters.connector,
+ currency: filters.currency,
+ status: filters.status,
+ payment_method: filters.payment_method,
+ payment_method_type: filters.payment_method_type,
+ authentication_type: filters.authentication_type,
+ },
+ ))
+}
+
+#[cfg(feature = "olap")]
+pub async fn get_payment_filters(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+) -> RouterResponse<api::PaymentListFiltersV2> {
+ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
+ admin::list_payment_connectors(state, platform.get_processor().clone(), profile_id_list)
+ .await?
+ {
+ data
+ } else {
+ return Err(errors::ApiErrorResponse::InternalServerError.into());
+ };
+
+ let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();
+ let mut payment_method_types_map: HashMap<
+ enums::PaymentMethod,
+ HashSet<enums::PaymentMethodType>,
+ > = HashMap::new();
+
+ // populate connector map
+ merchant_connector_accounts
+ .iter()
+ .filter_map(|merchant_connector_account| {
+ merchant_connector_account
+ .connector_label
+ .as_ref()
+ .map(|label| {
+ let info = merchant_connector_account.to_merchant_connector_info(label);
+ (merchant_connector_account.get_connector_name(), info)
+ })
+ })
+ .for_each(|(connector_name, info)| {
+ connector_map
+ .entry(connector_name.to_string())
+ .or_default()
+ .push(info);
+ });
+
+ // populate payment method type map
+ merchant_connector_accounts
+ .iter()
+ .flat_map(|merchant_connector_account| {
+ merchant_connector_account.payment_methods_enabled.as_ref()
+ })
+ .map(|payment_methods_enabled| {
+ payment_methods_enabled
+ .iter()
+ .filter_map(|payment_method_enabled| {
+ payment_method_enabled
+ .get_payment_method_type()
+ .map(|types_vec| {
+ (
+ payment_method_enabled.get_payment_method(),
+ types_vec.clone(),
+ )
+ })
+ })
+ })
+ .for_each(|payment_methods_enabled| {
+ payment_methods_enabled.for_each(
+ |(payment_method_option, payment_method_types_vec)| {
+ if let Some(payment_method) = payment_method_option {
+ payment_method_types_map
+ .entry(payment_method)
+ .or_default()
+ .extend(payment_method_types_vec.iter().filter_map(
+ |req_payment_method_types| {
+ req_payment_method_types.get_payment_method_type()
+ },
+ ));
+ }
+ },
+ );
+ });
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListFiltersV2 {
+ connector: connector_map,
+ currency: enums::Currency::iter().collect(),
+ status: enums::IntentStatus::iter().collect(),
+ payment_method: payment_method_types_map,
+ authentication_type: enums::AuthenticationType::iter().collect(),
+ card_network: enums::CardNetwork::iter().collect(),
+ card_discovery: enums::CardDiscovery::iter().collect(),
+ },
+ ))
+}
+
+#[cfg(feature = "olap")]
+pub async fn get_aggregates_for_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ time_range: common_utils::types::TimeRange,
+) -> RouterResponse<api::PaymentsAggregateResponse> {
+ let db = state.store.as_ref();
+ let intent_status_with_count = db
+ .get_intent_status_with_count(
+ platform.get_processor().get_account().get_id(),
+ profile_id_list,
+ &time_range,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let mut status_map: HashMap<enums::IntentStatus, i64> =
+ intent_status_with_count.into_iter().collect();
+ for status in enums::IntentStatus::iter() {
+ status_map.entry(status).or_default();
+ }
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentsAggregateResponse {
+ status_with_count: status_map,
+ },
+ ))
+}
diff --git a/crates/router/src/core/payments/list.rs b/crates/router/src/core/payments/list.rs
new file mode 100644
index 0000000000..dcc1aff4d5
--- /dev/null
+++ b/crates/router/src/core/payments/list.rs
@@ -0,0 +1,447 @@
+#[cfg(feature = "v2")]
+use api_models::payments as payments_api;
+#[cfg(feature = "v1")]
+use common_utils::id_type;
+#[cfg(feature = "v1")]
+use error_stack::report;
+use error_stack::ResultExt;
+use futures::future::join_all;
+
+#[cfg(feature = "v2")]
+use crate::core::revenue_recovery::{get_workflow_entries, map_to_recovery_payment_item};
+use crate::{
+ core::errors::{self, RouterResponse, StorageErrorExt},
+ db::StorageInterface,
+ routes::{metrics, SessionState},
+ services,
+ types::{api, domain, storage, transformers::ForeignFrom},
+};
+#[cfg(feature = "v1")]
+use crate::{core::payments::helpers, logger, types::storage::enums as storage_enums};
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn list_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ constraints: api::PaymentListConstraints,
+) -> RouterResponse<api::PaymentListResponse> {
+ let processor_merchant_id = platform.get_processor().get_account().get_id();
+ let db = state.store.as_ref();
+ let payment_intents = helpers::filter_by_constraints(
+ &state,
+ &(constraints, profile_id_list).try_into()?,
+ processor_merchant_id,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let collected_futures = payment_intents.into_iter().map(|pi| {
+ async {
+ match db
+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(
+ &pi.payment_id,
+ processor_merchant_id,
+ &pi.active_attempt.get_id(),
+ // since OLAP doesn't have KV. Force to get the data from PSQL.
+ storage_enums::MerchantStorageScheme::PostgresOnly,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ {
+ Ok(pa) => Some(Ok((pi, pa))),
+ Err(error) => {
+ if matches!(
+ error.current_context(),
+ errors::StorageError::ValueNotFound(_)
+ ) {
+ logger::warn!(
+ ?error,
+ "payment_attempts missing for payment_id : {:?}",
+ pi.payment_id,
+ );
+ return None;
+ }
+ Some(Err(error))
+ }
+ }
+ }
+ });
+
+ //If any of the response are Err, we will get Result<Err(_)>
+ let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> =
+ join_all(collected_futures)
+ .await
+ .into_iter()
+ .flatten() //Will ignore `None`, will only flatten 1 level
+ .collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>();
+ //Will collect responses in same order async, leading to sorted responses
+
+ //Converting Intent-Attempt array to Response if no error
+ let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .into_iter()
+ .map(ForeignFrom::foreign_from)
+ .collect();
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListResponse {
+ size: data.len(),
+ data,
+ },
+ ))
+}
+
+/// Lists payments across all connected merchants under a platform merchant.
+///
+/// Returns a slim, non-PII summary built from raw diesel rows, so no per-merchant key store
+/// is fetched. Use the single-payment retrieve for full PII.
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn list_payments_for_platform(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ constraints: api::PlatformPaymentListConstraints,
+) -> RouterResponse<api::PlatformPaymentListResponse> {
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ // This endpoint is exclusively for platform merchants - not connected, not standard.
+ common_utils::fp_utils::when(
+ !platform.get_provider().get_account().is_platform_account(),
+ || {
+ Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
+ "Platform payments list is only accessible to platform merchants",
+ )
+ },
+ )?;
+
+ // `limit` is a `PageSize`, already validated at deserialize; no extra check needed.
+ let platform_merchant_id = platform.get_provider().get_account().get_id();
+ let db: &dyn StorageInterface = state.store.as_ref();
+
+ let pi_fetch_constraints = (constraints, profile_id_list).try_into()?;
+
+ let raw_rows = db
+ .get_filtered_payment_intents_attempt_for_platform(
+ platform_merchant_id,
+ &pi_fetch_constraints,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let total_count = db
+ .get_payment_intents_attempt_count_for_platform(
+ platform_merchant_id,
+ &pi_fetch_constraints,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let data: Vec<api::PlatformPaymentListItem> = raw_rows
+ .into_iter()
+ .map(ForeignFrom::foreign_from)
+ .collect();
+
+ Ok(services::ApplicationResponse::Json(
+ api::PlatformPaymentListResponse {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+ },
+ &metrics::PAYMENT_LIST_LATENCY,
+ router_env::metric_attributes!((
+ "merchant_id",
+ platform.get_provider().get_account().get_id().clone()
+ )),
+ )
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "olap"))]
+pub async fn list_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ constraints: api::PaymentListConstraints,
+) -> RouterResponse<payments_api::PaymentListResponse> {
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let fetch_constraints = constraints.clone().into();
+ let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
+ .get_filtered_payment_intents_attempt(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let data: Vec<api_models::payments::PaymentsListResponseItem> =
+ list.into_iter().map(ForeignFrom::foreign_from).collect();
+
+ let active_attempt_ids = db
+ .get_filtered_active_attempt_ids_for_total_count(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving active_attempt_ids for merchant")?;
+
+ let total_count = if constraints.has_no_attempt_filters() {
+ i64::try_from(active_attempt_ids.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i64")
+ } else {
+ let active_attempt_ids = active_attempt_ids
+ .into_iter()
+ .flatten()
+ .collect::<Vec<String>>();
+
+ db.get_total_count_of_filtered_payment_attempts(
+ platform.get_processor().get_account().get_id(),
+ &active_attempt_ids,
+ constraints.connector,
+ constraints.payment_method_type,
+ constraints.payment_method_subtype,
+ constraints.authentication_type,
+ constraints.merchant_connector_id,
+ constraints.card_network,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving total count of payment attempts")
+ }?;
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::payments::PaymentListResponse {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+ },
+ &metrics::PAYMENT_LIST_LATENCY,
+ router_env::metric_attributes!((
+ "merchant_id",
+ platform.get_processor().get_account().get_id().clone()
+ )),
+ )
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "olap"))]
+pub async fn revenue_recovery_list_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ constraints: api::PaymentListConstraints,
+) -> RouterResponse<payments_api::RecoveryPaymentListResponse> {
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ // `limit` is a `PageSize`, already validated at deserialize; no extra check needed.
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let fetch_constraints = constraints.clone().into();
+ let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
+ .get_filtered_payment_intents_attempt(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ // Get all billing connector account IDs
+ let billing_connector_ids: Vec<_> = list
+ .iter()
+ .map(|(payment_intent, _)| {
+ payment_intent.get_billing_merchant_connector_account_id()
+ })
+ .collect();
+
+ // Create futures for workflow lookups
+ let workflow_futures: Vec<_> = list
+ .iter()
+ .map(|(payment_intent, _)| get_workflow_entries(&state, &payment_intent.id))
+ .collect();
+
+ let billing_connector_futures: Vec<_> = billing_connector_ids
+ .into_iter()
+ .map(|billing_mca_id| {
+ let platform_clone = platform.clone(); // Clone for each future
+ async move {
+ if let Some(billing_mca_id) = billing_mca_id {
+ db.find_merchant_connector_account_by_id(
+ &billing_mca_id,
+ platform_clone.get_processor().get_key_store(),
+ )
+ .await
+ .ok()
+ } else {
+ None
+ }
+ }
+ })
+ .collect();
+
+ let workflow_results = join_all(workflow_futures).await;
+ let billing_connector_results = join_all(billing_connector_futures).await;
+
+ let data: Vec<api_models::payments::RecoveryPaymentsListResponseItem> = list
+ .into_iter()
+ .zip(workflow_results)
+ .zip(billing_connector_results)
+ .map(
+ |(
+ ((payment_intent, payment_attempt), workflow_result),
+ billing_connector_account,
+ )| {
+ let (calculate_workflow, execute_workflow) =
+ workflow_result.unwrap_or((None, None));
+
+ // Get retry threshold from billing connector account
+ let max_retry_threshold = billing_connector_account
+ .as_ref()
+ .and_then(|mca| mca.get_retry_threshold())
+ .unwrap_or(0); // Default fallback
+
+ // Use custom mapping function
+ map_to_recovery_payment_item(
+ payment_intent,
+ payment_attempt,
+ calculate_workflow,
+ execute_workflow,
+ max_retry_threshold.try_into().unwrap_or(0),
+ )
+ },
+ )
+ .collect();
+
+ let active_attempt_ids = db
+ .get_filtered_active_attempt_ids_for_total_count(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving active_attempt_ids for merchant")?;
+
+ let total_count = if constraints.has_no_attempt_filters() {
+ i64::try_from(active_attempt_ids.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i64")
+ } else {
+ let active_attempt_ids = active_attempt_ids
+ .into_iter()
+ .flatten()
+ .collect::<Vec<String>>();
+
+ db.get_total_count_of_filtered_payment_attempts(
+ platform.get_processor().get_account().get_id(),
+ &active_attempt_ids,
+ constraints.connector,
+ constraints.payment_method_type,
+ constraints.payment_method_subtype,
+ constraints.authentication_type,
+ constraints.merchant_connector_id,
+ constraints.card_network,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving total count of payment attempts")
+ }?;
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::payments::RecoveryPaymentListResponse {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+ },
+ &metrics::PAYMENT_LIST_LATENCY,
+ router_env::metric_attributes!((
+ "merchant_id",
+ platform.get_processor().get_account().get_id().clone()
+ )),
+ )
+ .await
+}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn apply_filters_on_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ _profile_id_list: Option<Vec<id_type::ProfileId>>,
+ constraints: api::PaymentListFilterConstraints,
+) -> RouterResponse<api::PaymentListResponseV2> {
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let fetch_constraints = constraints.clone().into();
+ let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
+ .get_filtered_payment_intents_attempt(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let data: Vec<api::PaymentsResponse> =
+ list.into_iter().map(ForeignFrom::foreign_from).collect();
+
+ let active_attempt_ids = db
+ .get_filtered_active_attempt_ids_for_total_count(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let total_count = if constraints.has_no_attempt_filters() {
+ i64::try_from(active_attempt_ids.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i64")
+ } else {
+ db.get_total_count_of_filtered_payment_attempts(
+ platform.get_processor().get_account().get_id(),
+ &active_attempt_ids,
+ constraints.connector,
+ constraints.payment_method,
+ constraints.payment_method_type,
+ constraints.authentication_type,
+ constraints.merchant_connector_id,
+ constraints.card_network,
+ constraints.card_discovery,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ }?;
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListResponseV2 {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+ },
+ &metrics::PAYMENT_LIST_LATENCY,
+ router_env::metric_attributes!((
+ "merchant_id",
+ platform.get_processor().get_account().get_id().clone()
+ )),
+ )
+ .await
+}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index e6c0d04f2b..5d90dadfdc 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -36,6 +36,10 @@ use diesel_models::{
NetworkDetails as DieselNetworkDetails,
},
};
+#[cfg(all(feature = "v1", feature = "olap"))]
+use diesel_models::{
+ payment_attempt::PaymentAttempt as DieselPaymentAttempt, PaymentIntent as DieselPaymentIntent,
+};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
mandates,
@@ -4701,6 +4705,84 @@ pub fn construct_connector_invoke_hidden_frame(
Ok(api_models::payments::NextActionData::InvokeHiddenIframe { iframe_data })
}
+#[cfg(all(feature = "v1", feature = "olap"))]
+impl ForeignFrom<(DieselPaymentIntent, DieselPaymentAttempt)> for api::PlatformPaymentListItem {
+ fn foreign_from((pi, pa): (DieselPaymentIntent, DieselPaymentAttempt)) -> Self {
+ let connector_transaction_id =
+ common_utils::types::ConnectorTransactionIdTrait::get_optional_connector_transaction_id(
+ &pa,
+ )
+ .map(ToString::to_string);
+ Self {
+ payment_id: pi.payment_id,
+ merchant_id: pi.merchant_id,
+ processor_merchant_id: pi.processor_merchant_id,
+ status: pi.status,
+ amount: pi.amount,
+ net_amount: pa.net_amount,
+ amount_capturable: pa.amount_capturable,
+ state_metadata: pi.state_metadata,
+ client_secret: pi.client_secret.map(Secret::new),
+ created: Some(pi.created_at),
+ modified_at: Some(pi.modified_at),
+ currency: pi.currency,
+ customer_id: pi.customer_id,
+ description: pi.description,
+ order_details: pi.order_details,
+ connector: pa.connector,
+ payment_method: pa.payment_method,
+ payment_method_type: pa.payment_method_type,
+ business_label: pi.business_label,
+ business_country: pi.business_country,
+ business_sub_label: pa.business_sub_label,
+ setup_future_usage: pa.setup_future_usage_applied.or(pi.setup_future_usage),
+ capture_method: pa.capture_method,
+ authentication_type: pa.authentication_type,
+ connector_transaction_id,
+ attempt_count: pi.attempt_count,
+ profile_id: pi.profile_id,
+ merchant_connector_id: pa.merchant_connector_id,
+ merchant_order_reference_id: pi.merchant_order_reference_id,
+ metadata: pi.metadata,
+ error_message: pa.error_message,
+ updated: Some(pi.modified_at),
+ extended_authorization_applied: pa.extended_authorization_applied,
+ extended_authorization_last_applied_at: pa.extended_authorization_last_applied_at,
+ capture_before: pa.capture_before,
+ card_discovery: pa.card_discovery,
+ mit_category: pi.mit_category,
+ tokenization: pi.tokenization,
+ force_3ds_challenge: pi.force_3ds_challenge,
+ force_3ds_challenge_trigger: pi.force_3ds_challenge_trigger,
+ issuer_error_code: pa.issuer_error_code,
+ issuer_error_message: pa.issuer_error_message,
+ is_iframe_redirection_enabled: pi.is_iframe_redirection_enabled,
+ payment_channel: pi.payment_channel,
+ enable_partial_authorization: pi.enable_partial_authorization,
+ enable_overcapture: pi.enable_overcapture,
+ is_overcapture_enabled: pa.is_overcapture_enabled,
+ network_details: pa.network_details.map(NetworkDetails::foreign_from),
+ is_stored_credential: pa.is_stored_credential,
+ request_extended_authorization: pa.request_extended_authorization,
+ billing_descriptor: pi.billing_descriptor,
+ partner_merchant_identifier_details: pi.partner_merchant_identifier_details,
+ installment_data: pa.installment_data,
+ sender_payment_instrument_id: pa.sender_payment_instrument_id,
+ surcharge_details: pa.surcharge_amount.map(|surcharge_amount| {
+ RequestSurchargeDetails {
+ surcharge_amount,
+ tax_amount: pa.tax_amount,
+ surcharge_percentage: pa
+ .external_surcharge_details
+ .as_ref()
+ .and_then(|details| details.surcharge_percentage_as_f64()),
+ }
+ }),
+ installment_options: pi.installment_options.map(|options| options.0),
+ }
+ }
+}
+
#[cfg(feature = "v1")]
fn applied_offer_response(
details: Option<common_types::payments::AppliedOfferDetails>,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index d7aedd5c35..054e765d0c 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2232,6 +2232,34 @@ impl PaymentIntentInterface for KafkaStore {
.await
}
+ #[cfg(all(feature = "olap", feature = "v1"))]
+ async fn get_filtered_payment_intents_attempt_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ ) -> CustomResult<
+ Vec<(
+ diesel_models::PaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>,
+ errors::StorageError,
+ > {
+ self.diesel_store
+ .get_filtered_payment_intents_attempt_for_platform(platform_merchant_id, filters)
+ .await
+ }
+
+ #[cfg(all(feature = "olap", feature = "v1"))]
+ async fn get_payment_intents_attempt_count_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.diesel_store
+ .get_payment_intents_attempt_count_for_platform(platform_merchant_id, filters)
+ .await
+ }
+
#[cfg(all(feature = "olap", feature = "v1"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 60d788772d..a483badd0f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -983,6 +983,14 @@ impl Payments {
.route(web::get().to(payments::payments_list))
.route(web::post().to(payments::payments_list_by_filter)),
)
+ .service(
+ web::resource("/platform/list")
+ .route(web::get().to(payments::payments_list_for_platform)),
+ )
+ .service(
+ web::resource("/platform/filter")
+ .route(web::get().to(payments::payments_list_for_platform_filters)),
+ )
.service(
web::resource("/profile/list")
.route(web::get().to(payments::profile_payments_list))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 7300903b7a..82c8b38aa0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -180,6 +180,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsSessionToken
| Flow::PaymentsStart
| Flow::PaymentsList
+ | Flow::PlatformPaymentsList
+ | Flow::PlatformPaymentsFilters
| Flow::PaymentsFilters
| Flow::PaymentsAggregate
| Flow::PaymentsRedirect
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 32d1f6f3b0..1289c1fa6f 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -2284,7 +2284,7 @@ pub async fn payments_list(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::list_payments(state, auth.platform, None, req)
+ payments::list::list_payments(state, auth.platform, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
@@ -2303,6 +2303,58 @@ pub async fn payments_list(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PlatformPaymentsList))]
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn payments_list_for_platform(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Query<payment_types::PlatformPaymentListConstraints>,
+) -> impl Responder {
+ let flow = Flow::PlatformPaymentsList;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ payments::list::list_payments_for_platform(state, auth.platform, None, req)
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantPaymentRead,
+ allow_connected: false,
+ allow_platform: true,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::PlatformPaymentsFilters))]
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn payments_list_for_platform_filters(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+) -> impl Responder {
+ let flow = Flow::PlatformPaymentsFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ payments::filters::get_platform_payment_filters(state, auth.platform, None)
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantPaymentRead,
+ allow_connected: false,
+ allow_platform: true,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn revenue_recovery_invoices_list(
@@ -2318,7 +2370,7 @@ pub async fn revenue_recovery_invoices_list(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::revenue_recovery_list_payments(state, auth.platform, req)
+ payments::list::revenue_recovery_list_payments(state, auth.platform, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
@@ -2351,7 +2403,7 @@ pub async fn payments_list(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::list_payments(state, auth.platform, req)
+ payments::list::list_payments(state, auth.platform, req)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
@@ -2385,7 +2437,7 @@ pub async fn profile_payments_list(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::list_payments(
+ payments::list::list_payments(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
@@ -2424,7 +2476,7 @@ pub async fn payments_list_by_filter(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::apply_filters_on_payments(state, auth.platform, None, req)
+ payments::list::apply_filters_on_payments(state, auth.platform, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
@@ -2451,7 +2503,7 @@ pub async fn profile_payments_list_by_filter(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::apply_filters_on_payments(
+ payments::list::apply_filters_on_payments(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
@@ -2483,7 +2535,7 @@ pub async fn get_filters_for_payments(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::get_filters_for_payments(state, auth.platform, req)
+ payments::filters::get_filters_for_payments(state, auth.platform, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
@@ -2508,7 +2560,7 @@ pub async fn get_payment_filters(
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
- payments::get_payment_filters(state, auth.platform, None)
+ payments::filters::get_payment_filters(state, auth.platform, None)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
@@ -2533,7 +2585,7 @@ pub async fn get_payment_filters_profile(
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
- payments::get_payment_filters(
+ payments::filters::get_payment_filters(
state,
auth.platform,
Some(vec![auth.profile.get_id().clone()]),
@@ -2562,7 +2614,7 @@ pub async fn get_payment_filters_profile(
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
- payments::get_payment_filters(
+ payments::filters::get_payment_filters(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
@@ -2593,7 +2645,7 @@ pub async fn get_payments_aggregates(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::get_aggregates_for_payments(state, auth.platform, None, req)
+ payments::filters::get_aggregates_for_payments(state, auth.platform, None, req)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
@@ -3939,7 +3991,7 @@ pub async fn get_payments_aggregates_profile(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::get_aggregates_for_payments(
+ payments::filters::get_aggregates_for_payments(
state,
auth.platform,
auth.profile.map(|profile| vec![profile.get_id().clone()]),
@@ -3970,7 +4022,7 @@ pub async fn get_payments_aggregates_profile(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::get_aggregates_for_payments(
+ payments::filters::get_aggregates_for_payments(
state,
auth.platform,
Some(vec![auth.profile.get_id().clone()]),
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 5dd37fe510..7fca4056a0 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -8,7 +8,8 @@ pub use api_models::payments::{
pub use api_models::payments::{
PaymentListFilterConstraints, PaymentListResponse, PaymentListResponseV2, PaymentRetrieveBody,
PaymentRetrieveBodyWithCredentials, PaymentsEligibilityCheckRequest,
- PaymentsEligibilityRequest,
+ PaymentsEligibilityRequest, PlatformPaymentListConstraints, PlatformPaymentListFilters,
+ PlatformPaymentListItem, PlatformPaymentListResponse,
};
pub use api_models::{
feature_matrix::{
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index e128f7f6ec..76af3450a6 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -216,6 +216,10 @@ pub enum Flow {
PaymentsStart,
/// Payments list flow.
PaymentsList,
+ /// Aggregated payments list flow for a platform across its connected merchants.
+ PlatformPaymentsList,
+ /// Aggregated payments filter-values flow for a platform across its connected merchants.
+ PlatformPaymentsFilters,
/// Payments filters flow
PaymentsFilters,
/// Payments aggregates flow
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 9ce4ed4257..c46259674e 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -1,5 +1,7 @@
use common_utils::errors::CustomResult;
use diesel_models::enums as storage_enums;
+#[cfg(all(feature = "v1", feature = "olap"))]
+use diesel_models::PaymentIntent as DieselPaymentIntent;
#[cfg(feature = "v1")]
use error_stack::ResultExt;
#[cfg(feature = "v1")]
@@ -47,6 +49,32 @@ impl PaymentIntentInterface for MockDb {
Err(StorageError::MockDbError)?
}
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_filtered_payment_intents_attempt_for_platform(
+ &self,
+ _platform_merchant_id: &common_utils::id_type::MerchantId,
+ _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ ) -> CustomResult<
+ Vec<(
+ DieselPaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>,
+ StorageError,
+ > {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_payment_intents_attempt_count_for_platform(
+ &self,
+ _platform_merchant_id: &common_utils::id_type::MerchantId,
+ _filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
+ ) -> CustomResult<i64, StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(StorageError::MockDbError)?
+ }
+
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index d8eb3b2a17..87e6a6a4cf 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -448,6 +448,34 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await
}
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_filtered_payment_intents_attempt_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<
+ Vec<(
+ DieselPaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>,
+ StorageError,
+ > {
+ self.router_store
+ .get_filtered_payment_intents_attempt_for_platform(platform_merchant_id, filters)
+ .await
+ }
+
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ async fn get_payment_intents_attempt_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<i64, StorageError> {
+ self.router_store
+ .get_payment_intents_attempt_count_for_platform(platform_merchant_id, filters)
+ .await
+ }
+
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
@@ -936,6 +964,284 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.await
}
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ #[instrument(skip_all)]
+ async fn get_filtered_payment_intents_attempt_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<
+ Vec<(
+ DieselPaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>,
+ StorageError,
+ > {
+ let conn = connection::pg_connection_read(self).await?;
+
+ let mut query = diesel_models::list::into_boxed_list(
+ <DieselPaymentIntent as HasTable>::table()
+ .inner_join(
+ payment_attempt_schema::table
+ .on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
+ )
+ .filter(pi_dsl::merchant_id.eq(platform_merchant_id.to_owned()))
+ .filter(pa_dsl::merchant_id.eq(platform_merchant_id.to_owned())),
+ );
+
+ query = match filters {
+ PaymentIntentFetchConstraints::Single { payment_intent_id } => {
+ query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
+ }
+ PaymentIntentFetchConstraints::List(params) => {
+ query = match params.order {
+ Order {
+ on: SortOn::Amount,
+ by: SortBy::Asc,
+ } => query.order(pi_dsl::amount.asc()),
+ Order {
+ on: SortOn::Amount,
+ by: SortBy::Desc,
+ } => query.order(pi_dsl::amount.desc()),
+ Order {
+ on: SortOn::Created,
+ by: SortBy::Asc,
+ } => query.order(pi_dsl::created_at.asc()),
+ Order {
+ on: SortOn::Created,
+ by: SortBy::Desc,
+ } => query.order(pi_dsl::created_at.desc()),
+ Order {
+ on: SortOn::Modified,
+ by: SortBy::Asc,
+ } => query.order(pi_dsl::modified_at.asc()),
+ Order {
+ on: SortOn::Modified,
+ by: SortBy::Desc,
+ } => query.order(pi_dsl::modified_at.desc()),
+ Order {
+ on: SortOn::AttemptCount,
+ by: SortBy::Asc,
+ } => query.order(pi_dsl::attempt_count.asc()),
+ Order {
+ on: SortOn::AttemptCount,
+ by: SortBy::Desc,
+ } => query.order(pi_dsl::attempt_count.desc()),
+ };
+
+ query = diesel_models::list::apply_pagination(query, params.limit, params.offset);
+
+ if let Some(processor_merchant_id) = &params.processor_merchant_id {
+ query = query.filter(
+ pi_dsl::processor_merchant_id.eq_any(processor_merchant_id.clone()),
+ );
+ }
+ if let Some(customer_id) = &params.customer_id {
+ query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
+ }
+ if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id {
+ query = query.filter(
+ pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
+ );
+ }
+ if let Some(profile_id) = &params.profile_id {
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
+ }
+ if let Some(starting_at) = params.starting_at {
+ query = query.filter(pi_dsl::created_at.ge(starting_at));
+ }
+ if let Some(ending_at) = params.ending_at {
+ query = query.filter(pi_dsl::created_at.le(ending_at));
+ }
+ query = match params.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => query.filter(pi_dsl::amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.le(end)),
+ _ => query,
+ };
+ if let Some(currency) = &params.currency {
+ query = query.filter(pi_dsl::currency.eq_any(currency.clone()));
+ }
+ if let Some(status) = &params.status {
+ query = query.filter(pi_dsl::status.eq_any(status.clone()));
+ }
+ if let Some(connector) = &params.connector {
+ let connectors = connector
+ .iter()
+ .map(|connector| connector.to_string())
+ .collect::<Vec<String>>();
+ query = query.filter(pa_dsl::connector.eq_any(connectors));
+ }
+ if let Some(payment_method) = &params.payment_method {
+ query = query.filter(pa_dsl::payment_method.eq_any(payment_method.clone()));
+ }
+ if let Some(payment_method_type) = &params.payment_method_type {
+ query = query
+ .filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone()));
+ }
+ if let Some(authentication_type) = &params.authentication_type {
+ query = query
+ .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone()));
+ }
+ if let Some(merchant_connector_id) = &params.merchant_connector_id {
+ query = query.filter(
+ pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
+ );
+ }
+ if let Some(card_network) = &params.card_network {
+ query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
+ }
+ if let Some(card_discovery) = &params.card_discovery {
+ query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone()));
+ }
+
+ query
+ }
+ };
+
+ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ db_metrics::DatabaseOperation::Filter,
+ query.get_results_async::<(
+ DieselPaymentIntent,
+ diesel_models::payment_attempt::PaymentAttempt,
+ )>(conn.raw_connection()),
+ )
+ .await
+ .map_err(|er| {
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error filtering platform payment records")
+ })
+ }
+
+ #[cfg(all(feature = "v1", feature = "olap"))]
+ #[instrument(skip_all)]
+ async fn get_payment_intents_attempt_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ filters: &PaymentIntentFetchConstraints,
+ ) -> error_stack::Result<i64, StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ let mut query = diesel_models::list::into_boxed_list(
+ <DieselPaymentIntent as HasTable>::table()
+ .inner_join(
+ payment_attempt_schema::table
+ .on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
+ )
+ .count()
+ .filter(pi_dsl::merchant_id.eq(platform_merchant_id.to_owned()))
+ .filter(pa_dsl::merchant_id.eq(platform_merchant_id.to_owned())),
+ );
+
+ query = match filters {
+ PaymentIntentFetchConstraints::Single { payment_intent_id } => {
+ query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
+ }
+ PaymentIntentFetchConstraints::List(params) => {
+ if let Some(processor_merchant_id) = &params.processor_merchant_id {
+ query = query.filter(
+ pi_dsl::processor_merchant_id.eq_any(processor_merchant_id.clone()),
+ );
+ }
+ if let Some(customer_id) = &params.customer_id {
+ query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
+ }
+ if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id {
+ query = query.filter(
+ pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
+ );
+ }
+ if let Some(profile_id) = &params.profile_id {
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
+ }
+ if let Some(starting_at) = params.starting_at {
+ query = query.filter(pi_dsl::created_at.ge(starting_at));
+ }
+ if let Some(ending_at) = params.ending_at {
+ query = query.filter(pi_dsl::created_at.le(ending_at));
+ }
+ query = match params.amount_filter {
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.between(start, end)),
+ Some(AmountFilter {
+ start_amount: Some(start),
+ end_amount: None,
+ }) => query.filter(pi_dsl::amount.ge(start)),
+ Some(AmountFilter {
+ start_amount: None,
+ end_amount: Some(end),
+ }) => query.filter(pi_dsl::amount.le(end)),
+ _ => query,
+ };
+ if let Some(currency) = &params.currency {
+ query = query.filter(pi_dsl::currency.eq_any(currency.clone()));
+ }
+ if let Some(status) = &params.status {
+ query = query.filter(pi_dsl::status.eq_any(status.clone()));
+ }
+ if let Some(connector) = &params.connector {
+ let connectors = connector
+ .iter()
+ .map(|connector| connector.to_string())
+ .collect::<Vec<String>>();
+ query = query.filter(pa_dsl::connector.eq_any(connectors));
+ }
+ if let Some(payment_method) = &params.payment_method {
+ query = query.filter(pa_dsl::payment_method.eq_any(payment_method.clone()));
+ }
+ if let Some(payment_method_type) = &params.payment_method_type {
+ query = query
+ .filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone()));
+ }
+ if let Some(authentication_type) = &params.authentication_type {
+ query = query
+ .filter(pa_dsl::authentication_type.eq_any(authentication_type.clone()));
+ }
+ if let Some(merchant_connector_id) = &params.merchant_connector_id {
+ query = query.filter(
+ pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
+ );
+ }
+ if let Some(card_network) = &params.card_network {
+ query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
+ }
+ if let Some(card_discovery) = &params.card_discovery {
+ query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone()));
+ }
+ query
+ }
+ };
+
+ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ db_metrics::DatabaseOperation::Count,
+ query.get_result_async::<i64>(conn.raw_connection()),
+ )
+ .await
+ .map_err(|er| {
+ error_stack::report!(StorageError::from(er))
+ .attach_printable("Error counting platform payment records")
+ })
+ }
+
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payment_intents_by_time_range_constraints(