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(customers): add time range filtering and count functionality to customer list endpoints (#9767)
Venu Madhav Bandarupalli587588f8709e
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rsindex 62fd000ddb..536d630a81 100644--- a/crates/api_models/src/customers.rs+++ b/crates/api_models/src/customers.rs@@ -46,6 +46,17 @@ pub struct CustomerRequest {#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]pub struct CustomerListRequest {+ /// Offset+ #[schema(example = 32)]+ pub offset: Option<u32>,+ /// Limit+ #[schema(example = 32)]+ pub limit: Option<u16>,+ pub customer_id: Option<id_type::CustomerId>,+}++#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]+pub struct CustomerListRequestWithConstraints {/// Offset#[schema(example = 32)]pub offset: Option<u32>,@@ -54,6 +65,9 @@ pub struct CustomerListRequest {pub limit: Option<u16>,/// Unique identifier for a customerpub customer_id: Option<id_type::CustomerId>,+ /// Filter with created time range+ #[serde(flatten)]+ pub time_range: Option<common_utils::types::TimeRange>,}#[cfg(feature = "v1")]@@ -388,3 +402,11 @@ pub struct CustomerUpdateRequestInternal {pub id: id_type::GlobalCustomerId,pub request: CustomerUpdateRequest,}++#[derive(Debug, Serialize, ToSchema)]+pub struct CustomerListResponse {+ /// List of customers+ pub data: Vec<CustomerResponse>,+ /// Total count of customers+ pub total_count: usize,+}diff --git a/crates/api_models/src/events/customer.rs b/crates/api_models/src/events/customer.rsindex 290ccfdd46..602bdf8a12 100644--- a/crates/api_models/src/events/customer.rs+++ b/crates/api_models/src/events/customer.rs@@ -1,7 +1,8 @@use common_utils::events::{ApiEventMetric, ApiEventsType};use crate::customers::{- CustomerDeleteResponse, CustomerRequest, CustomerResponse, CustomerUpdateRequestInternal,+ CustomerDeleteResponse, CustomerListRequestWithConstraints, CustomerListResponse,+ CustomerRequest, CustomerResponse, CustomerUpdateRequestInternal,};#[cfg(feature = "v1")]@@ -73,3 +74,33 @@ impl ApiEventMetric for CustomerUpdateRequestInternal {})}}++#[cfg(feature = "v1")]+impl ApiEventMetric for CustomerListRequestWithConstraints {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Customer {+ customer_id: self.customer_id.clone()?,+ })+ }+}++#[cfg(feature = "v2")]+impl ApiEventMetric for CustomerListRequestWithConstraints {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Customer { customer_id: None })+ }+}++#[cfg(feature = "v1")]+impl ApiEventMetric for CustomerListResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}++#[cfg(feature = "v2")]+impl ApiEventMetric for CustomerListResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rsindex a6121d408c..989bcdc9d9 100644--- a/crates/diesel_models/src/query/customers.rs+++ b/crates/diesel_models/src/query/customers.rs@@ -21,6 +21,7 @@ pub struct CustomerListConstraints {pub limit: i64,pub offset: Option<i64>,pub customer_id: Option<id_type::CustomerId>,+ pub time_range: Option<common_utils::types::TimeRange>,}impl Customer {@@ -56,7 +57,67 @@ impl Customer {}#[cfg(feature = "v1")]- pub async fn list_by_merchant_id(+ pub async fn get_customer_count_by_merchant_id_and_constraints(+ conn: &PgPooledConn,+ merchant_id: &id_type::MerchantId,+ customer_list_constraints: CustomerListConstraints,+ ) -> StorageResult<usize> {+ if let Some(customer_id) = customer_list_constraints.customer_id {+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::customer_id.eq(customer_id));+ generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await+ } else if let Some(time_range) = customer_list_constraints.time_range {+ let start_time = time_range.start_time;+ let end_time = time_range+ .end_time+ .unwrap_or_else(common_utils::date_time::now);+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::created_at.between(start_time, end_time));++ generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await+ } else {+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ dsl::merchant_id.eq(merchant_id.to_owned()),+ )+ .await+ }+ }++ #[cfg(feature = "v2")]+ pub async fn get_customer_count_by_merchant_id_and_constraints(+ conn: &PgPooledConn,+ merchant_id: &id_type::MerchantId,+ customer_list_constraints: CustomerListConstraints,+ ) -> StorageResult<usize> {+ if let Some(customer_id) = customer_list_constraints.customer_id {+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::merchant_reference_id.eq(customer_id));+ generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await+ } else if let Some(time_range) = customer_list_constraints.time_range {+ let start_time = time_range.start_time;+ let end_time = time_range+ .end_time+ .unwrap_or_else(common_utils::date_time::now);+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::created_at.between(start_time, end_time));++ generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await+ } else {+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ dsl::merchant_id.eq(merchant_id.to_owned()),+ )+ .await+ }+ }++ #[cfg(feature = "v1")]+ pub async fn list_customers_by_merchant_id_and_constraints(conn: &PgPooledConn,merchant_id: &id_type::MerchantId,constraints: CustomerListConstraints,@@ -73,6 +134,23 @@ impl Customer {Some(dsl::created_at),).await+ } else if let Some(time_range) = constraints.time_range {+ let start_time = time_range.start_time;+ let end_time = time_range+ .end_time+ .unwrap_or_else(common_utils::date_time::now);+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::created_at.between(start_time, end_time));++ generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(+ conn,+ predicate,+ Some(constraints.limit),+ constraints.offset,+ Some(dsl::created_at),+ )+ .await} else {let predicate = dsl::merchant_id.eq(merchant_id.clone());generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(@@ -87,7 +165,7 @@ impl Customer {}#[cfg(feature = "v2")]- pub async fn list_by_merchant_id(+ pub async fn list_customers_by_merchant_id_and_constraints(conn: &PgPooledConn,merchant_id: &id_type::MerchantId,constraints: CustomerListConstraints,@@ -104,6 +182,23 @@ impl Customer {Some(dsl::created_at),).await+ } else if let Some(time_range) = constraints.time_range {+ let start_time = time_range.start_time;+ let end_time = time_range+ .end_time+ .unwrap_or_else(common_utils::date_time::now);+ let predicate = dsl::merchant_id+ .eq(merchant_id.clone())+ .and(dsl::created_at.between(start_time, end_time));++ generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(+ conn,+ predicate,+ Some(constraints.limit),+ constraints.offset,+ Some(dsl::created_at),+ )+ .await} else {let predicate = dsl::merchant_id.eq(merchant_id.clone());generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rsindex d5581932ea..d809f3cb19 100644--- a/crates/diesel_models/src/query/generics.rs+++ b/crates/diesel_models/src/query/generics.rs@@ -4,7 +4,7 @@ use async_bb8_diesel::AsyncRunQueryDsl;use diesel::{associations::HasTable,debug_query,- dsl::{Find, IsNotNull, Limit},+ dsl::{count_star, Find, IsNotNull, Limit},helper_types::{Filter, IntoBoxed},insertable::CanInsertInSingleQuery,pg::{Pg, PgConnection},@@ -13,7 +13,7 @@ use diesel::{QueryId, UpdateStatement,},query_dsl::{- methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl},+ methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl, SelectDsl},LoadQuery, RunQueryDsl,},result::Error as DieselError,@@ -445,6 +445,32 @@ where.attach_printable("Error filtering records by predicate")}+pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>+where+ T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,+ Filter<T, P>: SelectDsl<count_star>,+ diesel::dsl::Select<Filter<T, P>, count_star>:+ LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static,+{+ let query = <T as HasTable>::table()+ .filter(predicate)+ .select(count_star());++ logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());++ let count_i64: i64 =+ track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count)+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error counting records by predicate")?;++ let count_usize = usize::try_from(count_i64).map_err(|_| {+ report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")+ })?;++ Ok(count_usize)+}+fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {match arg {Ok(value) => Ok(Some(value)),diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex 84c9510c4b..d440a2d5da 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -558,6 +558,7 @@ pub struct CustomerListConstraints {pub limit: u16,pub offset: Option<u32>,pub customer_id: Option<id_type::CustomerId>,+ pub time_range: Option<common_utils::types::TimeRange>,}impl From<CustomerListConstraints> for query::CustomerListConstraints {@@ -566,6 +567,7 @@ impl From<CustomerListConstraints> for query::CustomerListConstraints {limit: i64::from(value.limit),offset: value.offset.map(i64::from),customer_id: value.customer_id,+ time_range: value.time_range,}}}@@ -657,6 +659,14 @@ whereconstraints: CustomerListConstraints,) -> CustomResult<Vec<Customer>, Self::Error>;+ async fn list_customers_by_merchant_id_with_count(+ &self,+ state: &KeyManagerState,+ merchant_id: &id_type::MerchantId,+ key_store: &MerchantKeyStore,+ constraints: CustomerListConstraints,+ ) -> CustomResult<(Vec<Customer>, usize), Self::Error>;+async fn insert_customer(&self,customer_data: Customer,diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex a0bec1a5a1..c9713475db 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -861,6 +861,9 @@ impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse {match self {Self::CustomerRedacted => SC::CustomerRedacted,Self::InternalServerError => SC::InternalServerError,+ Self::InvalidRequestData { message } => SC::InvalidRequestData {+ message: message.clone(),+ },Self::MandateActive => SC::MandateActive,Self::CustomerNotFound => SC::CustomerNotFound,Self::CustomerAlreadyExists => SC::DuplicateCustomer,diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 09f12d62ba..42deeddf51 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -22,6 +22,10 @@ use crate::{core::{errors::{self, StorageErrorExt},payment_methods::{cards, network_tokenization},+ utils::{+ self,+ customer_validation::{CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT},+ },},db::StorageInterface,pii::PeekInterface,@@ -591,6 +595,7 @@ pub async fn list_customers(.unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT),offset: request.offset,customer_id: request.customer_id,+ time_range: None,};let domain_customers = db@@ -618,6 +623,61 @@ pub async fn list_customers(Ok(services::ApplicationResponse::Json(customers))}+#[instrument(skip(state))]+pub async fn list_customers_with_count(+ state: SessionState,+ merchant_id: id_type::MerchantId,+ _profile_id_list: Option<Vec<id_type::ProfileId>>,+ key_store: domain::MerchantKeyStore,+ request: customers::CustomerListRequestWithConstraints,+) -> errors::CustomerResponse<customers::CustomerListResponse> {+ let db = state.store.as_ref();+ let limit = utils::customer_validation::validate_customer_list_limit(request.limit)+ .change_context(errors::CustomersErrorResponse::InvalidRequestData {+ message: format!(+ "limit should be between {CUSTOMER_LIST_LOWER_LIMIT} and {CUSTOMER_LIST_UPPER_LIMIT}"+ ),+ })?;++ let customer_list_constraints = crate::db::customers::CustomerListConstraints {+ limit: request.limit.unwrap_or(limit),+ offset: request.offset,+ customer_id: request.customer_id,+ time_range: request.time_range,+ };++ let domain_customers = db+ .list_customers_by_merchant_id_with_count(+ &(&state).into(),+ &merchant_id,+ &key_store,+ customer_list_constraints,+ )+ .await+ .switch()?;++ #[cfg(feature = "v1")]+ let customers: Vec<customers::CustomerResponse> = domain_customers+ .0+ .into_iter()+ .map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))+ .collect();++ #[cfg(feature = "v2")]+ let customers: Vec<customers::CustomerResponse> = domain_customers+ .0+ .into_iter()+ .map(customers::CustomerResponse::foreign_from)+ .collect();++ Ok(services::ApplicationResponse::Json(+ customers::CustomerListResponse {+ data: customers.into_iter().map(|c| c.0).collect(),+ total_count: domain_customers.1,+ },+ ))+}+#[cfg(feature = "v2")]#[instrument(skip_all)]pub async fn delete_customer(diff --git a/crates/router/src/core/errors/customers_error_response.rs b/crates/router/src/core/errors/customers_error_response.rsindex 5bda9a69a8..cde84198b2 100644--- a/crates/router/src/core/errors/customers_error_response.rs+++ b/crates/router/src/core/errors/customers_error_response.rs@@ -8,6 +8,9 @@ pub enum CustomersErrorResponse {#[error("Something went wrong")]InternalServerError,+ #[error("Invalid request data: {message}")]+ InvalidRequestData { message: String },+#[error("Customer has already been redacted")]MandateActive,diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rsindex f5e90771c1..fc4fb26fcb 100644--- a/crates/router/src/core/errors/transformers.rs+++ b/crates/router/src/core/errors/transformers.rs@@ -16,6 +16,12 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for CustomersErrorSelf::InternalServerError => {AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))}+ Self::InvalidRequestData { message } => AER::BadRequest(ApiError::new(+ "IR",+ 7,+ format!("Invalid value provided:{}", message),+ None,+ )),Self::MandateActive => AER::BadRequest(ApiError::new("IR",10,diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rsindex bea3ff4e58..d40585eb8a 100644--- a/crates/router/src/core/locker_migration.rs+++ b/crates/router/src/core/locker_migration.rs@@ -55,6 +55,7 @@ pub async fn rust_locker_migration(limit: u16::MAX,offset: None,customer_id: None,+ time_range: None,};let domain_customers = dbdiff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 753129f031..80b522b7a1 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -1,3 +1,4 @@+pub mod customer_validation;pub mod refunds_transformers;pub mod refunds_validator;diff --git a/crates/router/src/core/utils/customer_validation.rs b/crates/router/src/core/utils/customer_validation.rsnew file mode 100644index 0000000000..14df0fb0e0--- /dev/null+++ b/crates/router/src/core/utils/customer_validation.rs@@ -0,0 +1,21 @@+use crate::core::errors::{self, CustomResult};++pub const CUSTOMER_LIST_LOWER_LIMIT: u16 = 1;+pub const CUSTOMER_LIST_UPPER_LIMIT: u16 = 100;+pub const CUSTOMER_LIST_DEFAULT_LIMIT: u16 = 10;++pub fn validate_customer_list_limit(+ limit: Option<u16>,+) -> CustomResult<u16, errors::ApiErrorResponse> {+ match limit {+ Some(l) if (CUSTOMER_LIST_LOWER_LIMIT..=CUSTOMER_LIST_UPPER_LIMIT).contains(&l) => Ok(l),+ Some(_) => Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "limit should be between {} and {}",+ CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT+ ),+ }+ .into()),+ None => Ok(CUSTOMER_LIST_DEFAULT_LIMIT),+ }+}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 22c3d1022a..befb7329b7 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -510,6 +510,18 @@ impl CustomerInterface for KafkaStore {.await}+ async fn list_customers_by_merchant_id_with_count(+ &self,+ state: &KeyManagerState,+ merchant_id: &id_type::MerchantId,+ key_store: &domain::MerchantKeyStore,+ constraints: super::customers::CustomerListConstraints,+ ) -> CustomResult<(Vec<domain::Customer>, usize), errors::StorageError> {+ self.diesel_store+ .list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints)+ .await+ }+#[cfg(feature = "v1")]async fn find_customer_by_customer_id_merchant_id(&self,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex f575f80af1..989845638d 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1284,6 +1284,10 @@ impl Customers {{route = route.service(web::resource("/list").route(web::get().to(customers::customers_list)))+ .service(+ web::resource("/list_with_count")+ .route(web::get().to(customers::customers_list_with_count)),+ ).service(web::resource("/total-payment-methods").route(web::get().to(payment_methods::get_total_payment_method_count)),@@ -1321,6 +1325,10 @@ impl Customers {.route(web::get().to(customers::get_customer_mandates)),).service(web::resource("/list").route(web::get().to(customers::customers_list)))+ .service(+ web::resource("/list_with_count")+ .route(web::get().to(customers::customers_list_with_count)),+ )}#[cfg(feature = "oltp")]diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rsindex 9673318160..0c37afd10b 100644--- a/crates/router/src/routes/customers.rs+++ b/crates/router/src/routes/customers.rs@@ -239,6 +239,83 @@ pub async fn customers_list(.await}+#[cfg(feature = "v2")]+#[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))]+pub async fn customers_list_with_count(+ state: web::Data<AppState>,+ req: HttpRequest,+ query: web::Query<customers::CustomerListRequestWithConstraints>,+) -> HttpResponse {+ let flow = Flow::CustomersListWithConstraints;+ let payload = query.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, request, _| {+ list_customers_with_count(+ state,+ auth.merchant_account.get_id().to_owned(),+ None,+ auth.key_store,+ request,+ )+ },+ auth::auth_type(+ &auth::V2ApiKeyAuth {+ is_connected_allowed: false,+ is_platform_allowed: false,+ },+ &auth::JWTAuth {+ permission: Permission::MerchantCustomerRead,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[cfg(feature = "v1")]+#[instrument(skip_all, fields(flow = ?Flow::CustomersListWithConstraints))]+pub async fn customers_list_with_count(+ state: web::Data<AppState>,+ req: HttpRequest,+ query: web::Query<customers::CustomerListRequestWithConstraints>,+) -> HttpResponse {+ let flow = Flow::CustomersListWithConstraints;+ let payload = query.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, request, _| {+ list_customers_with_count(+ state,+ auth.merchant_account.get_id().to_owned(),+ None,+ auth.key_store,+ request,+ )+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ is_connected_allowed: false,+ is_platform_allowed: false,+ }),+ &auth::JWTAuth {+ permission: Permission::MerchantCustomerRead,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]pub async fn customers_update(diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex a8b7294c1c..8a199c7867 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -114,7 +114,8 @@ impl From<Flow> for ApiIdentifier {| Flow::CustomersUpdate| Flow::CustomersDelete| Flow::CustomersGetMandates- | Flow::CustomersList => Self::Customers,+ | Flow::CustomersList+ | Flow::CustomersListWithConstraints => Self::Customers,Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health,Flow::MandatesRetrieve | Flow::MandatesRevoke | Flow::MandatesList => Self::Mandates,diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rsindex 149239d2e3..6d7e2430b9 100644--- a/crates/router/src/types/api/customers.rs+++ b/crates/router/src/types/api/customers.rs@@ -1,7 +1,7 @@use api_models::customers;pub use api_models::customers::{- CustomerDeleteResponse, CustomerListRequest, CustomerRequest, CustomerUpdateRequest,- CustomerUpdateRequestInternal,+ CustomerDeleteResponse, CustomerListRequest, CustomerListRequestWithConstraints,+ CustomerListResponse, CustomerRequest, CustomerUpdateRequest, CustomerUpdateRequestInternal,};#[cfg(feature = "v2")]use hyperswitch_domain_models::customer;diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 1968447a16..76f0e28a3a 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -130,6 +130,8 @@ pub enum Flow {GetPaymentMethodTokenData,/// List Customers for a merchantCustomersList,+ ///List Customers for a merchant with constraints.+ CustomersListWithConstraints,/// Retrieve countries and currencies for connector and payment methodListCountriesCurrencies,/// Payment method create collect link flow.diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex 53056a137c..befbf5d7f6 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -10,9 +10,8 @@ use hyperswitch_domain_models::{use masking::PeekInterface;use router_env::{instrument, tracing};-#[cfg(feature = "v1")]-use crate::diesel_error_to_data_error;use crate::{+ diesel_error_to_data_error,errors::StorageError,kv_router_store,redis::kv_store::{decide_storage_scheme, KvStorePartition, Op, PartitionKey},@@ -290,6 +289,19 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.await}+ #[instrument(skip_all)]+ async fn list_customers_by_merchant_id_with_count(+ &self,+ state: &KeyManagerState,+ merchant_id: &id_type::MerchantId,+ key_store: &MerchantKeyStore,+ constraints: domain::CustomerListConstraints,+ ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {+ self.router_store+ .list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints)+ .await+ }+#[cfg(feature = "v2")]#[instrument(skip_all)]async fn insert_customer(@@ -661,11 +673,56 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {self.find_resources(state,key_store,- customers::Customer::list_by_merchant_id(&conn, merchant_id, customer_list_constraints),+ customers::Customer::list_customers_by_merchant_id_and_constraints(+ &conn,+ merchant_id,+ customer_list_constraints,+ ),).await}+ #[instrument(skip_all)]+ async fn list_customers_by_merchant_id_with_count(+ &self,+ state: &KeyManagerState,+ merchant_id: &id_type::MerchantId,+ key_store: &MerchantKeyStore,+ constraints: domain::CustomerListConstraints,+ ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {+ let conn = pg_connection_read(self).await?;+ let customer_list_constraints =+ diesel_models::query::customers::CustomerListConstraints::from(constraints);+ let customers_constraints = diesel_models::query::customers::CustomerListConstraints {+ limit: customer_list_constraints.limit,+ offset: customer_list_constraints.offset,+ customer_id: customer_list_constraints.customer_id.clone(),+ time_range: customer_list_constraints.time_range,+ };+ let customers = self+ .find_resources(+ state,+ key_store,+ customers::Customer::list_customers_by_merchant_id_and_constraints(+ &conn,+ merchant_id,+ customers_constraints,+ ),+ )+ .await?;+ let total_count = customers::Customer::get_customer_count_by_merchant_id_and_constraints(+ &conn,+ merchant_id,+ customer_list_constraints,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })?;+ Ok((customers, total_count))+ }+#[instrument(skip_all)]async fn insert_customer(&self,@@ -822,6 +879,41 @@ impl domain::CustomerInterface for MockDb {Ok(customers)}+ async fn list_customers_by_merchant_id_with_count(+ &self,+ state: &KeyManagerState,+ merchant_id: &id_type::MerchantId,+ key_store: &MerchantKeyStore,+ constraints: domain::CustomerListConstraints,+ ) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {+ let customers = self.customers.lock().await;++ let customers_list = try_join_all(+ customers+ .iter()+ .filter(|customer| customer.merchant_id == *merchant_id)+ .take(usize::from(constraints.limit))+ .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))+ .map(|customer| async {+ customer+ .to_owned()+ .convert(+ state,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)+ }),+ )+ .await?;+ let total_count = customers+ .iter()+ .filter(|customer| customer.merchant_id == *merchant_id)+ .count();+ Ok((customers_list, total_count))+ }+#[cfg(feature = "v1")]#[instrument(skip_all)]async fn update_customer_by_customer_id_merchant_id(