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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat: Implement OpenSearch-powered payment list API (#11270)
Venu Madhav Bandarupalli2ac9684914f7
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rsindex b938e82e65..2b98a0b7ca 100644--- a/crates/analytics/src/lib.rs+++ b/crates/analytics/src/lib.rs@@ -1159,6 +1159,7 @@ pub enum AnalyticsFlow {GetDisputeMetrics,GetSankey,GetRoutingEvents,+ GetPaymentListFromOpenSearch,}impl FlowMetric for AnalyticsFlow {}diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rsindex 47632e62b8..a499bd5df0 100644--- a/crates/analytics/src/opensearch.rs+++ b/crates/analytics/src/opensearch.rs@@ -1,8 +1,9 @@use std::collections::HashSet;use api_models::{- analytics::search::SearchIndex,+ analytics::search::{OpensearchRange, SearchIndex},errors::types::{ApiError, ApiErrorResponse},+ payments::{Order, SortBy, SortOn},};use aws_config::{self, meta::region::RegionProviderChain, Region};use common_utils::{@@ -487,12 +488,49 @@ pub struct OpenSearchQueryBuilder {pub count: Option<i64>,pub filters: Vec<(String, Vec<Value>)>,pub time_range: Option<OpensearchTimeRange>,+ pub amount_range: Option<OpensearchRange>,search_params: Vec<AuthInfo>,case_sensitive_fields: HashSet<&'static str>,+ pub order: Option<Order>,}+const ACTIVE_ATTEMPT_FILTER_SCRIPT: &str = r#"+ if (!params.containsKey('_source')) return false;++ def source = params._source;+ if (source == null) return false;++ def activeAttemptId = source.active_attempt_id;+ if (activeAttemptId == null) return false;++ def attemptsList = source.attempts_list;+ if (attemptsList == null) return false;++ for (def attemptObject : attemptsList) {+ if (attemptObject == null) continue;+ if (!(attemptObject instanceof Map)) continue;++ def attemptId = attemptObject.get("attempt_id");+ if (attemptId == null) continue;++ if (attemptId == activeAttemptId) {+ def fieldValueForActiveAttempt = attemptObject.get(params.field);+ if (fieldValueForActiveAttempt == null) return false;++ return params.values.contains(fieldValueForActiveAttempt);+ }+ }++ return false;+"#;+impl OpenSearchQueryBuilder {- pub fn new(query_type: OpenSearchQuery, query: String, search_params: Vec<AuthInfo>) -> Self {+ pub fn new(+ query_type: OpenSearchQuery,+ query: String,+ search_params: Vec<AuthInfo>,+ order: Option<Order>,+ ) -> Self {Self {query_type,query,@@ -501,6 +539,7 @@ impl OpenSearchQueryBuilder {count: Default::default(),filters: Default::default(),time_range: Default::default(),+ amount_range: Default::default(),case_sensitive_fields: HashSet::from(["customer_email.keyword","search_tags.keyword",@@ -508,7 +547,9 @@ impl OpenSearchQueryBuilder {"payment_id.keyword","amount","customer_id.keyword",+ "merchant_order_reference_id.keyword",]),+ order,}}@@ -523,6 +564,11 @@ impl OpenSearchQueryBuilder {Ok(())}+ pub fn set_amount_range(&mut self, amount_range: OpensearchRange) -> QueryResult<()> {+ self.amount_range = Some(amount_range);+ Ok(())+ }+pub fn add_filter_clause(&mut self, lhs: String, rhs: Vec<Value>) -> QueryResult<()> {self.filters.push((lhs, rhs));Ok(())@@ -544,6 +590,73 @@ impl OpenSearchQueryBuilder {}}+ fn make_active_attempt_script_filter(&self, field: &str, values: &Vec<Value>) -> Value {+ json!({+ "bool": {+ "should": [+ {+ "terms": {+ format!("{}.keyword", field): values+ }+ },+ {+ "bool": {+ "must": [+ {+ "term": {+ "attempt_count": 1+ }+ },+ {+ "terms": {+ format!("attempts_list.{}.keyword", field): values+ }+ }+ ]+ }+ },+ {+ "bool": {+ "must": [+ {+ "range": {+ "attempt_count": {+ "gt": 1+ }+ }+ },+ {+ "bool": {+ "must_not": [+ {+ "exists": {+ "field": field+ }+ }+ ]+ }+ },+ {+ "script": {+ "script": {+ "lang": "painless",+ "source": ACTIVE_ATTEMPT_FILTER_SCRIPT,+ "params": {+ "field": field,+ "values": values+ }+ }+ }+ }+ ]+ }+ }+ ],+ "minimum_should_match": 1+ }+ })+ }+pub fn build_filter_array(&self,case_sensitive_filters: Vec<&(String, Vec<Value>)>,@@ -583,6 +696,16 @@ impl OpenSearchQueryBuilder {}));}+ if let Some(ref amount_range) = self.amount_range {+ let range = json!(amount_range);+ let amount_field = self.get_amount_field(index);+ filter_array.push(json!({+ "range": {+ amount_field: range+ }+ }));+ }+filter_array}@@ -596,6 +719,9 @@ impl OpenSearchQueryBuilder {let mut must_array = case_insensitive_filters.iter().map(|(k, v)| {+ if *k == "card_discovery.keyword" {+ return self.make_active_attempt_script_filter("card_discovery", v);+ }let key = if *k == "status.keyword" {self.get_status_field(index).to_string()} else {@@ -748,22 +874,39 @@ impl OpenSearchQueryBuilder {query_obj.insert("bool".to_string(), Value::Object(bool_obj.clone()));- let mut sort_obj = Map::new();- sort_obj.insert(- "@timestamp".to_string(),- json!({- "order": "desc"- }),- );-Ok(indexes.iter().map(|index| {+ let mut sort_list = Vec::new();+ match &self.order {+ Some(order) => {+ let sort_on = match order.on {+ SortOn::Amount => self.get_amount_field(*index).to_string(),+ SortOn::Created => "@timestamp".to_string(),+ SortOn::Modified => "modified_at".to_string(),+ };+ let sort_by = match order.by {+ SortBy::Asc => "asc",+ SortBy::Desc => "desc",+ };+ sort_list.push(json!({+ sort_on: {+ "order": sort_by+ }+ }));+ }+ None => {+ sort_list.push(json!({+ "@timestamp": {+ "order": "desc"+ }+ }));+ }+ }let mut payload = json!({+ "track_total_hits": true,"query": query_obj.clone(),- "sort": [- Value::Object(sort_obj.clone())- ]+ "sort": sort_list.clone()});let filter_array = self.build_filter_array(case_sensitive_filters.clone(), *index);if !filter_array.is_empty() {diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rsindex 7fda015144..9495663e07 100644--- a/crates/analytics/src/search.rs+++ b/crates/analytics/src/search.rs@@ -16,6 +16,27 @@ pub fn convert_to_value<T: Into<Value>>(items: Vec<T>) -> Vec<Value> {items.into_iter().map(|item| item.into()).collect()}+macro_rules! append_filter {+ ($builder:ident, $filters:ident, $field:ident, $es_key:expr) => {+ if let Some(val) = &$filters.$field {+ if !val.is_empty() {+ $builder+ .add_filter_clause($es_key.to_string(), convert_to_value(val.clone()))+ .switch()?;+ }+ }+ };+ ($builder:ident, $filters:ident, $field:ident, $es_key:expr, $transform:expr) => {+ if let Some(val) = &$filters.$field {+ if !val.is_empty() {+ $builder+ .add_filter_clause($es_key.to_string(), convert_to_value($transform(val)))+ .switch()?;+ }+ }+ };+}+pub async fn msearch_results(client: &OpenSearchClient,req: GetGlobalSearchRequest,@@ -37,137 +58,62 @@ pub async fn msearch_results(OpenSearchQuery::Msearch(indexes.clone()),req.query,search_params,+ None,);if let Some(filters) = req.filters {- if let Some(currency) = filters.currency {- if !currency.is_empty() {- query_builder- .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency))- .switch()?;- }- };- if let Some(status) = filters.status {- if !status.is_empty() {- query_builder- .add_filter_clause("status.keyword".to_string(), convert_to_value(status))- .switch()?;- }- };- if let Some(payment_method) = filters.payment_method {- if !payment_method.is_empty() {- query_builder- .add_filter_clause(- "payment_method.keyword".to_string(),- convert_to_value(payment_method),- )- .switch()?;- }- };- if let Some(customer_email) = filters.customer_email {- if !customer_email.is_empty() {- query_builder- .add_filter_clause(- "customer_email.keyword".to_string(),- convert_to_value(- customer_email- .iter()- .filter_map(|email| {- // TODO: Add trait based inputs instead of converting this to strings- serde_json::to_value(email)- .ok()- .and_then(|a| a.as_str().map(|a| a.to_string()))- })- .collect(),- ),- )- .switch()?;- }- };- if let Some(search_tags) = filters.search_tags {- if !search_tags.is_empty() {- query_builder- .add_filter_clause(- "feature_metadata.search_tags.keyword".to_string(),- convert_to_value(- search_tags- .iter()- .filter_map(|search_tag| {- // TODO: Add trait based inputs instead of converting this to strings- serde_json::to_value(search_tag)- .ok()- .and_then(|a| a.as_str().map(|a| a.to_string()))- })- .collect(),- ),- )- .switch()?;- }- };- if let Some(connector) = filters.connector {- if !connector.is_empty() {- query_builder- .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector))- .switch()?;- }- };- if let Some(payment_method_type) = filters.payment_method_type {- if !payment_method_type.is_empty() {- query_builder- .add_filter_clause(- "payment_method_type.keyword".to_string(),- convert_to_value(payment_method_type),- )- .switch()?;- }- };- if let Some(card_network) = filters.card_network {- if !card_network.is_empty() {- query_builder- .add_filter_clause(- "card_network.keyword".to_string(),- convert_to_value(card_network),- )- .switch()?;- }- };- if let Some(card_last_4) = filters.card_last_4 {- if !card_last_4.is_empty() {- query_builder- .add_filter_clause(- "card_last_4.keyword".to_string(),- convert_to_value(card_last_4),- )- .switch()?;- }- };- if let Some(payment_id) = filters.payment_id {- if !payment_id.is_empty() {- query_builder- .add_filter_clause(- "payment_id.keyword".to_string(),- convert_to_value(payment_id),- )- .switch()?;- }- };- if let Some(amount) = filters.amount {- if !amount.is_empty() {- query_builder- .add_filter_clause("amount".to_string(), convert_to_value(amount))- .switch()?;+ append_filter!(query_builder, filters, currency, "currency.keyword");+ append_filter!(query_builder, filters, status, "status.keyword");+ append_filter!(+ query_builder,+ filters,+ payment_method,+ "payment_method.keyword"+ );+ append_filter!(+ query_builder,+ filters,+ customer_email,+ "customer_email.keyword",+ |emails: &Vec<_>| {+ emails+ .iter()+ .filter_map(|email| {+ serde_json::to_value(email)+ .ok()+ .and_then(|a| a.as_str().map(|a| a.to_string()))+ })+ .collect::<Vec<String>>()}- };- if let Some(customer_id) = filters.customer_id {- if !customer_id.is_empty() {- query_builder- .add_filter_clause(- "customer_id.keyword".to_string(),- convert_to_value(customer_id),- )- .switch()?;+ );+ append_filter!(+ query_builder,+ filters,+ search_tags,+ "feature_metadata.search_tags.keyword",+ |tags: &Vec<_>| {+ tags.iter()+ .filter_map(|tag| {+ serde_json::to_value(tag)+ .ok()+ .and_then(|a| a.as_str().map(|a| a.to_string()))+ })+ .collect::<Vec<String>>()}- };+ );++ append_filter!(query_builder, filters, connector, "connector.keyword");+ append_filter!(+ query_builder,+ filters,+ payment_method_type,+ "payment_method_type.keyword"+ );+ append_filter!(query_builder, filters, card_network, "card_network.keyword");+ append_filter!(query_builder, filters, card_last_4, "card_last_4.keyword");+ append_filter!(query_builder, filters, payment_id, "payment_id.keyword");+ append_filter!(query_builder, filters, amount, "amount");+ append_filter!(query_builder, filters, customer_id, "customer_id.keyword");};if let Some(time_range) = req.time_range {@@ -233,9 +179,10 @@ pub async fn search_results(.filters.as_ref().is_none_or(|filters| filters.is_all_none())+ && search_params.is_empty(){return Err(OpenSearchError::BadRequestError(- "Both query and filters are empty".to_string(),+ "Query, filters and search_params are all empty".to_string(),).into());}@@ -243,137 +190,83 @@ pub async fn search_results(OpenSearchQuery::Search(req.index),search_req.query,search_params,+ search_req.order,);if let Some(filters) = search_req.filters {- if let Some(currency) = filters.currency {- if !currency.is_empty() {- query_builder- .add_filter_clause("currency.keyword".to_string(), convert_to_value(currency))- .switch()?;- }- };- if let Some(status) = filters.status {- if !status.is_empty() {- query_builder- .add_filter_clause("status.keyword".to_string(), convert_to_value(status))- .switch()?;- }- };- if let Some(payment_method) = filters.payment_method {- if !payment_method.is_empty() {- query_builder- .add_filter_clause(- "payment_method.keyword".to_string(),- convert_to_value(payment_method),- )- .switch()?;- }- };- if let Some(customer_email) = filters.customer_email {- if !customer_email.is_empty() {- query_builder- .add_filter_clause(- "customer_email.keyword".to_string(),- convert_to_value(- customer_email- .iter()- .filter_map(|email| {- // TODO: Add trait based inputs instead of converting this to strings- serde_json::to_value(email)- .ok()- .and_then(|a| a.as_str().map(|a| a.to_string()))- })- .collect(),- ),- )- .switch()?;- }- };- if let Some(search_tags) = filters.search_tags {- if !search_tags.is_empty() {- query_builder- .add_filter_clause(- "feature_metadata.search_tags.keyword".to_string(),- convert_to_value(- search_tags- .iter()- .filter_map(|search_tag| {- // TODO: Add trait based inputs instead of converting this to strings- serde_json::to_value(search_tag)- .ok()- .and_then(|a| a.as_str().map(|a| a.to_string()))- })- .collect(),- ),- )- .switch()?;- }- };- if let Some(connector) = filters.connector {- if !connector.is_empty() {- query_builder- .add_filter_clause("connector.keyword".to_string(), convert_to_value(connector))- .switch()?;- }- };- if let Some(payment_method_type) = filters.payment_method_type {- if !payment_method_type.is_empty() {- query_builder- .add_filter_clause(- "payment_method_type.keyword".to_string(),- convert_to_value(payment_method_type),- )- .switch()?;- }- };- if let Some(card_network) = filters.card_network {- if !card_network.is_empty() {- query_builder- .add_filter_clause(- "card_network.keyword".to_string(),- convert_to_value(card_network),- )- .switch()?;- }- };- if let Some(card_last_4) = filters.card_last_4 {- if !card_last_4.is_empty() {- query_builder- .add_filter_clause(- "card_last_4.keyword".to_string(),- convert_to_value(card_last_4),- )- .switch()?;- }- };- if let Some(payment_id) = filters.payment_id {- if !payment_id.is_empty() {- query_builder- .add_filter_clause(- "payment_id.keyword".to_string(),- convert_to_value(payment_id),- )- .switch()?;- }- };- if let Some(amount) = filters.amount {- if !amount.is_empty() {- query_builder- .add_filter_clause("amount".to_string(), convert_to_value(amount))- .switch()?;+ append_filter!(query_builder, filters, currency, "currency.keyword");+ append_filter!(query_builder, filters, status, "status.keyword");+ append_filter!(+ query_builder,+ filters,+ payment_method,+ "payment_method.keyword"+ );+ append_filter!(+ query_builder,+ filters,+ customer_email,+ "customer_email.keyword",+ |emails: &Vec<_>| {+ emails+ .iter()+ .filter_map(|email| {+ serde_json::to_value(email)+ .ok()+ .and_then(|a| a.as_str().map(|a| a.to_string()))+ })+ .collect::<Vec<String>>()}- };- if let Some(customer_id) = filters.customer_id {- if !customer_id.is_empty() {- query_builder- .add_filter_clause(- "customer_id.keyword".to_string(),- convert_to_value(customer_id),- )- .switch()?;+ );+ append_filter!(+ query_builder,+ filters,+ search_tags,+ "feature_metadata.search_tags.keyword",+ |tags: &Vec<_>| {+ tags.iter()+ .filter_map(|tag| {+ serde_json::to_value(tag)+ .ok()+ .and_then(|a| a.as_str().map(|a| a.to_string()))+ })+ .collect::<Vec<String>>()}+ );++ if let Some(amount_filter) = filters.amount_filter {+ query_builder.set_amount_range(amount_filter).switch()?;};+ append_filter!(query_builder, filters, connector, "connector.keyword");+ append_filter!(+ query_builder,+ filters,+ payment_method_type,+ "payment_method_type.keyword"+ );+ append_filter!(query_builder, filters, card_network, "card_network.keyword");+ append_filter!(query_builder, filters, card_last_4, "card_last_4.keyword");+ append_filter!(query_builder, filters, payment_id, "payment_id.keyword");+ append_filter!(query_builder, filters, amount, "amount");+ append_filter!(query_builder, filters, customer_id, "customer_id.keyword");+ append_filter!(+ query_builder,+ filters,+ authentication_type,+ "authentication_type.keyword"+ );+ append_filter!(+ query_builder,+ filters,+ card_discovery,+ "card_discovery.keyword"+ );+ append_filter!(+ query_builder,+ filters,+ merchant_order_reference_id,+ "merchant_order_reference_id.keyword"+ );};if let Some(time_range) = search_req.time_range {diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rsindex ab22be377d..9ed344bdee 100644--- a/crates/api_models/src/analytics/search.rs+++ b/crates/api_models/src/analytics/search.rs@@ -1,7 +1,15 @@use common_utils::{hashing::HashedString, types::TimeRange};-use masking::WithType;+use masking::{ExposeInterface, WithType};use serde_json::Value;+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]+pub struct OpensearchRange {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub gte: Option<i64>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub lte: Option<i64>,+}+#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]pub struct SearchFilters {pub payment_method: Option<Vec<String>>,@@ -15,22 +23,95 @@ pub struct SearchFilters {pub card_last_4: Option<Vec<String>>,pub payment_id: Option<Vec<String>>,pub amount: Option<Vec<u64>>,+ pub amount_filter: Option<OpensearchRange>,pub customer_id: Option<Vec<String>>,+ pub authentication_type: Option<Vec<String>>,+ pub card_discovery: Option<Vec<String>>,+ pub merchant_order_reference_id: Option<Vec<String>>,}++#[cfg(feature = "v1")]+pub fn convert_to_strings<T: ToString>(items: &[T]) -> Vec<String> {+ items.iter().map(|item| item.to_string()).collect()+}++#[cfg(feature = "v1")]+impl From<&crate::payments::PaymentListFilterConstraints> for SearchFilters {+ fn from(constraints: &crate::payments::PaymentListFilterConstraints) -> Self {+ Self {+ payment_method: constraints+ .payment_method+ .as_deref()+ .map(convert_to_strings),+ currency: constraints.currency.as_deref().map(convert_to_strings),+ status: constraints.status.as_deref().map(convert_to_strings),+ payment_method_type: constraints+ .payment_method_type+ .as_deref()+ .map(convert_to_strings),+ authentication_type: constraints+ .authentication_type+ .as_deref()+ .map(convert_to_strings),+ card_network: constraints.card_network.as_deref().map(convert_to_strings),+ connector: constraints.connector.as_deref().map(convert_to_strings),+ card_discovery: constraints+ .card_discovery+ .as_deref()+ .map(convert_to_strings),+ customer_id: constraints+ .customer_id+ .as_ref()+ .map(|customer_id| vec![customer_id.get_string_repr().to_string()]),+ payment_id: constraints+ .payment_id+ .as_ref()+ .map(|payment_id| vec![payment_id.get_string_repr().to_string()]),+ merchant_order_reference_id: constraints+ .merchant_order_reference_id+ .as_ref()+ .map(|merchant_order_reference_id| vec![merchant_order_reference_id.clone()]),+ customer_email: constraints+ .customer_email+ .as_ref()+ .map(|customer_email| vec![HashedString::from(customer_email.clone().expose())]),+ search_tags: None,+ card_last_4: None,+ amount: None,+ amount_filter: constraints+ .amount_filter+ .as_ref()+ .map(|amount| OpensearchRange {+ gte: amount.start_amount,+ lte: amount.end_amount,+ }),+ }+ }+}+impl SearchFilters {pub fn is_all_none(&self) -> bool {- self.payment_method.is_none()- && self.currency.is_none()- && self.status.is_none()- && self.customer_email.is_none()- && self.search_tags.is_none()- && self.connector.is_none()- && self.payment_method_type.is_none()- && self.card_network.is_none()- && self.card_last_4.is_none()- && self.payment_id.is_none()- && self.amount.is_none()- && self.customer_id.is_none()+ matches!(+ self,+ Self {+ payment_method: None,+ currency: None,+ status: None,+ customer_email: None,+ search_tags: None,+ connector: None,+ payment_method_type: None,+ card_network: None,+ card_last_4: None,+ payment_id: None,+ amount: None,+ amount_filter: None,+ customer_id: None,+ authentication_type: None,+ card_discovery: None,+ merchant_order_reference_id: None,+ }+ )}}@@ -54,6 +135,8 @@ pub struct GetSearchRequest {pub filters: Option<SearchFilters>,#[serde(default)]pub time_range: Option<TimeRange>,+ #[serde(default)]+ pub order: Option<crate::payments::Order>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex d9c8758bb1..9b230213ef 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -9005,6 +9005,8 @@ pub struct PaymentListFilterConstraints {pub merchant_order_reference_id: Option<String>,/// Indicates the method by which a card is discovered during a paymentpub card_discovery: Option<Vec<enums::CardDiscovery>>,+ /// The customer email to filter payments list+ pub customer_email: Option<Email>,}#[cfg(feature = "v1")]diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex da186a3c23..9157f2dd6d 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -1660,6 +1660,7 @@ pub struct PaymentIntentListParams {pub card_network: Option<Vec<common_enums::CardNetwork>>,pub card_discovery: Option<Vec<common_enums::CardDiscovery>>,pub merchant_order_reference_id: Option<String>,+ pub customer_email: Option<Email>,}#[cfg(feature = "v2")]@@ -1721,6 +1722,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCocard_network: None,card_discovery: None,merchant_order_reference_id: None,+ customer_email: None,}))}}@@ -1812,6 +1814,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {card_network: None,card_discovery: None,merchant_order_reference_id: None,+ customer_email: None,}))}}@@ -1838,6 +1841,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFcard_network,card_discovery,merchant_order_reference_id,+ customer_email,} = value;if let Some(payment_intent_id) = payment_id {Self::Single { payment_intent_id }@@ -1863,6 +1867,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFcard_network,card_discovery,merchant_order_reference_id,+ customer_email,}))}}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 0c303c5155..64483ced06 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -33,7 +33,7 @@ payout_retry = ["payouts"]recon = ["email", "api_models/recon"]retry = []v2 = [ "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2", "hyperswitch_interfaces/v2", "common_types/v2", "revenue_recovery", "scheduler/v2", "euclid/v2", "payment_methods/v2", "tokenization_v2", "subscriptions/v2"]-v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_link/v1", "payment_methods/v1", "subscriptions/v1"]+v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_link/v1", "payment_methods/v1", "subscriptions/v1", "analytics/v1"]dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery", "external_services/revenue_recovery", "dep:prost-types"]tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"]diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rsindex 61ec8ed00a..de14d6cee9 100644--- a/crates/router/src/analytics.rs+++ b/crates/router/src/analytics.rs@@ -16,7 +16,8 @@ pub mod routes {use api_models::analytics::{api_event::QueryType,search::{- GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex,+ GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchFilters,+ SearchIndex,},AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest,GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest,@@ -30,13 +31,14 @@ pub mod routes {use error_stack::{report, ResultExt};use futures::{stream::FuturesUnordered, StreamExt};use masking::ExposeInterface;+ use router_env::logger;use crate::{analytics_validator::request_validator,consts::opensearch::SEARCH_INDEXES,core::{api_locking, errors::user::UserErrors, verification::utils},db::user_role::ListUserRolesByUserIdPayload,- routes::AppState,+ routes::{metrics, AppState},services::{api,authentication::{self as auth, AuthenticationData, UserFromToken},@@ -185,6 +187,10 @@ pub mod routes {web::resource("search/{domain}").route(web::post().to(get_search_results)),)+ .service(+ web::resource("payments/list")+ .route(web::post().to(get_payment_list_from_opensearch)),+ ).service(web::resource("metrics/disputes").route(web::post().to(get_merchant_dispute_metrics)),@@ -451,7 +457,10 @@ pub mod routes {.service(web::resource("metrics/auth_events/sankey").route(web::post().to(get_profile_auth_event_sankey)),- ),+ )+ .service(web::resource("payments/list").route(+ web::post().to(get_profile_payment_list_from_opensearch),+ )),),).service(@@ -3434,6 +3443,158 @@ pub mod routes {.await}+ #[cfg(feature = "v1")]+ pub async fn get_payment_list_from_opensearch(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ json_payload: web::Json<api_models::payments::PaymentListFilterConstraints>,+ ) -> impl Responder {+ let flow = AnalyticsFlow::GetPaymentListFromOpenSearch;+ let payload = json_payload.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state.clone(),+ &req,+ payload,+ |state, auth: AuthenticationData, constraints, _| async move {+ let req_merchant_id = auth.platform.get_processor().get_account().get_id().clone();+ common_utils::metrics::utils::record_operation_time(+ Box::pin(async move {+ let merchant_id = auth.platform.get_processor().get_account().get_id();+ let org_id = auth.platform.get_processor().get_account().get_org_id();++ let auth_info = vec![AuthInfo::MerchantLevel {+ org_id: org_id.clone(),+ merchant_ids: vec![merchant_id.clone()],+ }];++ let filters: SearchFilters = (&constraints).into();++ let search_req = GetSearchRequestWithIndex {+ index: SearchIndex::SessionizerPaymentIntents,+ search_req: GetSearchRequest {+ query: String::new(),+ filters: Some(filters),+ time_range: constraints.time_range,+ offset: constraints.offset.map(i64::from).unwrap_or(0),+ count: i64::from(constraints.limit),+ order: Some(constraints.order),+ },+ };++ analytics::search::search_results(+ state+ .opensearch_client+ .as_ref()+ .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?,+ search_req,+ auth_info,+ )+ .await+ .map(|response| {+ logger::info!(+ count = response.hits.len(),+ total = response.count,+ "Successfully retrieved payments from OpenSearch"+ );+ ApplicationResponse::Json(response)+ })+ }),+ &metrics::PAYMENT_LIST_OPENSEARCH_LATENCY,+ router_env::metric_attributes!(("merchant_id", req_merchant_id.clone())),+ )+ .await+ },+ &auth::JWTAuth {+ permission: Permission::MerchantPaymentRead,+ allow_connected: true,+ allow_platform: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+ }++ #[cfg(feature = "v1")]+ pub async fn get_profile_payment_list_from_opensearch(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ json_payload: web::Json<api_models::payments::PaymentListFilterConstraints>,+ ) -> impl Responder {+ let flow = AnalyticsFlow::GetPaymentListFromOpenSearch;+ let payload = json_payload.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state.clone(),+ &req,+ payload,+ |state, auth: AuthenticationData, constraints, _| async move {+ let req_merchant_id = auth.platform.get_processor().get_account().get_id().clone();+ common_utils::metrics::utils::record_operation_time(+ Box::pin(async move {+ let merchant_id = auth.platform.get_processor().get_account().get_id();+ let org_id = auth.platform.get_processor().get_account().get_org_id();++ let profile_id = auth+ .profile+ .ok_or(report!(UserErrors::JwtProfileIdMissing))+ .change_context(OpenSearchError::AccessForbiddenError)?+ .get_id()+ .clone();++ let auth_info = vec![AuthInfo::ProfileLevel {+ org_id: org_id.clone(),+ merchant_id: merchant_id.clone(),+ profile_ids: vec![profile_id.clone()],+ }];++ let filters: SearchFilters = (&constraints).into();++ let search_req = GetSearchRequestWithIndex {+ index: SearchIndex::SessionizerPaymentIntents,+ search_req: GetSearchRequest {+ query: String::new(),+ filters: Some(filters),+ time_range: constraints.time_range,+ offset: constraints.offset.map(i64::from).unwrap_or(0),+ count: i64::from(constraints.limit),+ order: Some(constraints.order),+ },+ };++ analytics::search::search_results(+ state+ .opensearch_client+ .as_ref()+ .ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?,+ search_req,+ auth_info,+ )+ .await+ .map(|response| {+ logger::info!(+ count = response.hits.len(),+ total = response.count,+ "Successfully retrieved payments for profile from OpenSearch"+ );+ ApplicationResponse::Json(response)+ })+ }),+ &metrics::PAYMENT_LIST_OPENSEARCH_LATENCY,+ router_env::metric_attributes!(("merchant_id", req_merchant_id.clone())),+ )+ .await+ },+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentRead,+ allow_connected: true,+ allow_platform: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+ }+pub async fn get_global_search_results(state: web::Data<AppState>,req: actix_web::HttpRequest,diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex c017ad5e5b..02aae13be6 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -20,6 +20,8 @@ counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER);//TODO: This can be removed, added for payment list debugginghistogram_metric_f64!(PAYMENT_LIST_LATENCY, GLOBAL_METER);+histogram_metric_f64!(PAYMENT_LIST_OPENSEARCH_LATENCY, GLOBAL_METER);+counter_metric!(REFUND_COUNT, GLOBAL_METER);counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER);