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

fix(core): Implemented Payouts Aggregate API (#10559)

Sayak Bhattacharyab0dc444d9a5a
diff --git a/crates/api_models/src/events/payouts.rs b/crates/api_models/src/events/payouts.rs
index 9d365ed32e..3e6e80d010 100644
--- a/crates/api_models/src/events/payouts.rs
+++ b/crates/api_models/src/events/payouts.rs
@@ -3,7 +3,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::payouts::{
PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkInitiateRequest,
PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListFiltersV2,
- PayoutListResponse, PayoutRetrieveRequest,
+ PayoutListResponse, PayoutRetrieveRequest, PayoutsAggregateResponse,
};
impl ApiEventMetric for PayoutRetrieveRequest {
@@ -75,3 +75,9 @@ impl ApiEventMetric for PayoutLinkInitiateRequest {
})
}
}
+
+impl ApiEventMetric for PayoutsAggregateResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 88b5b0f0dd..8dafdcc93a 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -1118,3 +1118,9 @@ impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataR
}
}
}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct PayoutsAggregateResponse {
+ /// The list of intent status with their count
+ pub status_with_count: HashMap<common_enums::PayoutStatus, i64>,
+}
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index b1f1883257..f7651e22bd 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -154,6 +154,15 @@ impl ApiEventMetric for id_type::PaymentId {
}
}
+#[cfg(feature = "v1")]
+impl ApiEventMetric for id_type::PayoutId {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Payout {
+ payout_id: self.clone(),
+ })
+ }
+}
+
#[cfg(feature = "v2")]
impl ApiEventMetric for id_type::GlobalPaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 35fe1c2529..d33dd54acd 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -89,6 +89,14 @@ pub trait PayoutsInterface {
_merchant_id: &id_type::MerchantId,
_constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<id_type::PayoutId>, Self::Error>;
+
+ #[cfg(feature = "olap")]
+ async fn get_payout_intent_status_with_count(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ constraints: &common_utils::types::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, Self::Error>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 865fd12dee..c1f9f509a0 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -969,7 +969,7 @@ pub async fn payouts_list_available_filters_core(
platform.get_processor().get_account().storage_scheme,
)
.await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
@@ -980,7 +980,7 @@ pub async fn payouts_list_available_filters_core(
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
Ok(services::ApplicationResponse::Json(
api::PayoutListFilters {
@@ -3448,3 +3448,33 @@ pub async fn get_mca_from_profile_id(
Ok(merchant_connector_account)
}
+
+#[cfg(feature = "olap")]
+pub async fn get_aggregates_for_payouts(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ time_range: common_utils::types::TimeRange,
+) -> RouterResponse<api_models::payouts::PayoutsAggregateResponse> {
+ let db = state.store.as_ref();
+ let intent_status_with_count = db
+ .get_payout_intent_status_with_count(
+ platform.get_processor().get_account().get_id(),
+ profile_id_list,
+ &time_range,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
+
+ let mut status_map: HashMap<common_enums::PayoutStatus, i64> =
+ intent_status_with_count.into_iter().collect();
+ for status in common_enums::PayoutStatus::iter() {
+ status_map.entry(status).or_default();
+ }
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::payouts::PayoutsAggregateResponse {
+ status_with_count: status_map,
+ },
+ ))
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 833911662f..a085804317 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2503,6 +2503,18 @@ impl PayoutsInterface for KafkaStore {
.filter_active_payout_ids_by_constraints(merchant_id, constraints)
.await
}
+
+ #[cfg(feature = "olap")]
+ async fn get_payout_intent_status_with_count(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ constraints: &common_utils::types::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, Self::Error> {
+ self.diesel_store
+ .get_payout_intent_status_with_count(merchant_id, profile_id_list, constraints)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 7909b5f58a..576a6bb0d5 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1515,6 +1515,11 @@ impl Payouts {
.route(web::get().to(payouts_list))
.route(web::post().to(payouts_list_by_filter)),
)
+ .service(web::resource("/aggregate").route(web::get().to(get_payouts_aggregates)))
+ .service(
+ web::resource("/profile/aggregate")
+ .route(web::get().to(get_payouts_aggregates_profile)),
+ )
.service(
web::resource("/profile/list")
.route(web::get().to(payouts_list_profile))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 7a191c477a..dda2f679b3 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -187,7 +187,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PayoutsFilter
| Flow::PayoutsAccounts
| Flow::PayoutsConfirm
- | Flow::PayoutLinkInitiate => Self::Payouts,
+ | Flow::PayoutLinkInitiate
+ | Flow::PayoutsAggregate => Self::Payouts,
Flow::RefundsCreate
| Flow::RefundsRetrieve
| Flow::RefundsRetrieveForceSync
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 9fd4c24ccc..915ed9e1a2 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -563,3 +563,60 @@ pub fn populate_browser_info_for_payouts(
Ok(())
}
+
+#[instrument(skip_all, fields(flow = ?Flow::PayoutsAggregate))]
+#[cfg(feature = "olap")]
+pub async fn get_payouts_aggregates(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Query<common_utils::types::TimeRange>,
+) -> impl Responder {
+ let flow = Flow::PayoutsAggregate;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let platform = auth.into();
+ get_aggregates_for_payouts(state, platform, None, req)
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantPayoutRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::PayoutsAggregate))]
+#[cfg(all(feature = "olap", feature = "v1"))]
+pub async fn get_payouts_aggregates_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Query<common_utils::types::TimeRange>,
+) -> impl Responder {
+ let flow = Flow::PayoutsAggregate;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let platform = auth.clone().into();
+ get_aggregates_for_payouts(
+ state,
+ platform,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ &auth::JWTAuth {
+ permission: Permission::ProfilePayoutRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 3229ec857d..43a27a9e03 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -698,6 +698,8 @@ pub enum Flow {
PaymentsSubmitEligibility,
/// Apply payment method data flow
ApplyPaymentMethodData,
+ /// Payouts aggregates flow
+ PayoutsAggregate,
}
/// Trait for providing generic behaviour to flow metric
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 648e09bd5c..f836dc71f0 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -114,4 +114,14 @@ impl PayoutsInterface for MockDb {
// TODO: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
+
+ #[cfg(feature = "olap")]
+ async fn get_payout_intent_status_with_count(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ _time_range: &common_utils::types::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::PayoutStatus, i64)>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
}
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 547500449d..8a8e73a8e1 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -383,6 +383,18 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
.filter_active_payout_ids_by_constraints(merchant_id, constraints)
.await
}
+
+ #[cfg(feature = "olap")]
+ async fn get_payout_intent_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &common_utils::types::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, StorageError> {
+ self.router_store
+ .get_payout_intent_status_with_count(merchant_id, profile_id_list, time_range)
+ .await
+ }
}
#[async_trait::async_trait]
@@ -893,6 +905,50 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> {
todo!()
}
+
+ #[cfg(feature = "olap")]
+ #[instrument(skip_all)]
+ async fn get_payout_intent_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &common_utils::types::TimeRange,
+ ) -> error_stack::Result<Vec<(common_enums::PayoutStatus, i64)>, StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
+
+ let mut query = <DieselPayouts as HasTable>::table()
+ .group_by(po_dsl::status)
+ .select((po_dsl::status, diesel::dsl::count_star()))
+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .into_boxed();
+
+ if let Some(profile_id) = profile_id_list {
+ query = query.filter(po_dsl::profile_id.eq_any(profile_id));
+ }
+
+ query = query.filter(po_dsl::created_at.ge(time_range.start_time));
+
+ query = match time_range.end_time {
+ Some(ending_at) => query.filter(po_dsl::created_at.le(ending_at)),
+ None => query,
+ };
+
+ logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
+ query.get_results_async::<(common_enums::PayoutStatus, i64)>(conn),
+ db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ .map_err(|er| {
+ StorageError::DatabaseError(
+ error_stack::report!(diesel_models::errors::DatabaseError::from(er))
+ .attach_printable("Error filtering payout records"),
+ )
+ .into()
+ })
+ }
}
impl DataModelExt for Payouts {