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(payouts): implement list and filter APIs (#3651)
Kashiffb5f0e6c7eb7
diff --git a/crates/api_models/src/events/payouts.rs b/crates/api_models/src/events/payouts.rsindex 303709acc4..9d86a6b38b 100644--- a/crates/api_models/src/events/payouts.rs+++ b/crates/api_models/src/events/payouts.rs@@ -1,7 +1,8 @@use common_utils::events::{ApiEventMetric, ApiEventsType};use crate::payouts::{- PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutRetrieveRequest,+ PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints,+ PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutRetrieveRequest,};impl ApiEventMetric for PayoutRetrieveRequest {@@ -27,3 +28,27 @@ impl ApiEventMetric for PayoutActionRequest {Some(ApiEventsType::Payout)}}++impl ApiEventMetric for PayoutListConstraints {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payout)+ }+}++impl ApiEventMetric for PayoutListFilterConstraints {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payout)+ }+}++impl ApiEventMetric for PayoutListResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payout)+ }+}++impl ApiEventMetric for PayoutListFilters {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payout)+ }+}diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 83aff4a007..ce2b1c3d68 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -2,6 +2,7 @@ use std::{collections::HashMap, fmt, num::NonZeroI64};use cards::CardNumber;use common_utils::{+ consts::default_payments_list_limit,crypto,ext_traits::Encode,pii::{self, Email},@@ -3197,7 +3198,7 @@ pub struct PaymentListConstraints {/// limit on the number of objects to return#[schema(default = 10, maximum = 100)]- #[serde(default = "default_limit")]+ #[serde(default = "default_payments_list_limit")]pub limit: u32,/// The time at which payment is created@@ -3283,7 +3284,7 @@ pub struct PaymentListFilterConstraints {/// The identifier for customerpub customer_id: Option<String>,/// The limit on the number of objects. The default limit is 10 and max limit is 20- #[serde(default = "default_limit")]+ #[serde(default = "default_payments_list_limit")]pub limit: u32,/// The starting point within a list of objectspub offset: Option<u32>,@@ -3353,10 +3354,6 @@ pub struct VerifyResponse {pub error_message: Option<String>,}-fn default_limit() -> u32 {- 10-}-#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]pub struct PaymentsRedirectionResponse {pub redirect_url: String,diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rsindex 3597f11f58..1cdbfe41eb 100644--- a/crates/api_models/src/payouts.rs+++ b/crates/api_models/src/payouts.rs@@ -1,10 +1,12 @@use cards::CardNumber;use common_utils::{+ consts::default_payouts_list_limit,crypto,pii::{self, Email},};use masking::Secret;use serde::{Deserialize, Serialize};+use time::PrimitiveDateTime;use utoipa::ToSchema;use crate::{enums as api_enums, payments};@@ -393,6 +395,54 @@ pub struct PayoutCreateResponse {/// The business profile that is associated with this paymentpub profile_id: String,++ /// Time when the payout was created+ #[schema(example = "2022-09-10T10:11:12Z")]+ #[serde(with = "common_utils::custom_serde::iso8601::option")]+ pub created: Option<PrimitiveDateTime>,++ /// List of attempts+ #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)]+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attempts: Option<Vec<PayoutAttemptResponse>>,+}++#[derive(+ Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,+)]+pub struct PayoutAttemptResponse {+ /// Unique identifier for the attempt+ pub attempt_id: String,+ /// The status of the attempt+ #[schema(value_type = PayoutStatus, example = "failed")]+ pub status: api_enums::PayoutStatus,+ /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,+ pub amount: i64,+ /// The currency of the amount of the payout attempt+ #[schema(value_type = Option<Currency>, example = "USD")]+ pub currency: Option<api_enums::Currency>,+ /// The connector used for the payout+ pub connector: Option<String>,+ /// Connector's error code in case of failures+ pub error_code: Option<String>,+ /// Connector's error message in case of failures+ pub error_message: Option<String>,+ /// The payout method that was used+ #[schema(value_type = Option<PayoutType>, example = "bank")]+ pub payment_method: Option<api_enums::PayoutType>,+ /// Payment Method Type+ #[schema(value_type = Option<PaymentMethodType>, example = "bacs")]+ pub payout_method_type: Option<api_enums::PaymentMethodType>,+ /// A unique identifier for a payout provided by the connector+ pub connector_transaction_id: Option<String>,+ /// If the payout was cancelled the reason provided here+ pub cancellation_reason: Option<String>,+ /// Provide a reference to a stored payout method+ pub payout_token: Option<String>,+ /// error code unified across the connectors is received here if there was an error while calling connector+ pub unified_code: Option<String>,+ /// error message unified across the connectors is received here if there was an error while calling connector+ pub unified_message: Option<String>,}#[derive(Default, Debug, Clone, Deserialize, ToSchema)]@@ -430,3 +480,96 @@ pub struct PayoutActionRequest {)]pub payout_id: String,}++#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]+#[serde(deny_unknown_fields)]+pub struct PayoutListConstraints {+ /// The identifier for customer+ #[schema(example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]+ pub customer_id: Option<String>,++ /// A cursor for use in pagination, fetch the next list after some object+ #[schema(example = "pay_fafa124123")]+ pub starting_after: Option<String>,++ /// A cursor for use in pagination, fetch the previous list before some object+ #[schema(example = "pay_fafa124123")]+ pub ending_before: Option<String>,++ /// limit on the number of objects to return+ #[schema(default = 10, maximum = 100)]+ #[serde(default = "default_payouts_list_limit")]+ pub limit: u32,++ /// The time at which payout is created+ #[schema(example = "2022-09-10T10:11:12Z")]+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created: Option<PrimitiveDateTime>,++ /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).+ #[serde(flatten)]+ #[schema(value_type = Option<TimeRange>)]+ pub time_range: Option<payments::TimeRange>,+}++#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]+#[serde(deny_unknown_fields)]+pub struct PayoutListFilterConstraints {+ /// The identifier for payout+ #[schema(+ value_type = Option<String>,+ min_length = 30,+ max_length = 30,+ example = "payout_mbabizu24mvu3mela5njyhpit4"+)]+ pub payout_id: Option<String>,+ /// The identifier for business profile+ pub profile_id: Option<String>,+ /// The identifier for customer+ #[schema(example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]+ pub customer_id: Option<String>,+ /// The limit on the number of objects. The default limit is 10 and max limit is 20+ #[serde(default = "default_payouts_list_limit")]+ pub limit: u32,+ /// The starting point within a list of objects+ pub offset: Option<u32>,+ /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).+ #[serde(flatten)]+ #[schema(value_type = Option<TimeRange>)]+ pub time_range: Option<payments::TimeRange>,+ /// The list of connectors to filter payouts list+ #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))]+ pub connector: Option<Vec<api_enums::PayoutConnectors>>,+ /// The list of currencies to filter payouts list+ #[schema(value_type = Currency, example = "USD")]+ pub currency: Option<Vec<api_enums::Currency>>,+ /// The list of payout status to filter payouts list+ #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))]+ pub status: Option<Vec<api_enums::PayoutStatus>>,+ /// The list of payout methods to filter payouts list+ #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))]+ pub payout_method: Option<Vec<common_enums::PayoutType>>,+ /// Type of recipient+ #[schema(value_type = PayoutEntityType, example = "Individual")]+ pub entity_type: Option<common_enums::PayoutEntityType>,+}++#[derive(Clone, Debug, serde::Serialize, ToSchema)]+pub struct PayoutListResponse {+ /// The number of payouts included in the list+ pub size: usize,+ // The list of payouts response objects+ pub data: Vec<PayoutCreateResponse>,+}++#[derive(Clone, Debug, serde::Serialize)]+pub struct PayoutListFilters {+ /// The list of available connector filters+ pub connector: Vec<api_enums::PayoutConnectors>,+ /// The list of available currency filters+ pub currency: Vec<common_enums::Currency>,+ /// The list of available payment status filters+ pub status: Vec<common_enums::PayoutStatus>,+ /// The list of available payment method filters+ pub payout_method: Vec<common_enums::PayoutType>,+}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex fd4f473c3f..97eb655121 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2028,6 +2028,7 @@ pub enum CanadaStatesAbbreviation {Debug,Default,Eq,+ Hash,PartialEq,ToSchema,serde::Deserialize,diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rsindex 1e28d2c47f..9ab5f0ac61 100644--- a/crates/common_utils/src/consts.rs+++ b/crates/common_utils/src/consts.rs@@ -23,10 +23,23 @@ pub static FRM_CONFIGS_EG: &str = r#"pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100;/// Maximum limit for payments list post api with filterspub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 20;+/// Default limit for payments list API+pub fn default_payments_list_limit() -> u32 {+ 10+}/// Maximum limit for payment link list get apipub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100;+/// Maximum limit for payouts list get api+pub const PAYOUTS_LIST_MAX_LIMIT_GET: u32 = 100;+/// Maximum limit for payouts list post api+pub const PAYOUTS_LIST_MAX_LIMIT_POST: u32 = 20;+/// Default limit for payouts list API+pub fn default_payouts_list_limit() -> u32 {+ 10+}+/// surcharge percentage maximum precision lengthpub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;diff --git a/crates/data_models/src/payouts.rs b/crates/data_models/src/payouts.rsindex 2017f96c06..75a5a21fb7 100644--- a/crates/data_models/src/payouts.rs+++ b/crates/data_models/src/payouts.rs@@ -1,3 +1,100 @@pub mod payout_attempt;#[allow(clippy::module_inception)]pub mod payouts;++use common_enums as storage_enums;+use common_utils::consts;+use time::PrimitiveDateTime;++pub enum PayoutFetchConstraints {+ Single { payout_id: String },+ List(Box<PayoutListParams>),+}++pub struct PayoutListParams {+ pub offset: u32,+ pub starting_at: Option<PrimitiveDateTime>,+ pub ending_at: Option<PrimitiveDateTime>,+ pub connector: Option<Vec<api_models::enums::PayoutConnectors>>,+ pub currency: Option<Vec<storage_enums::Currency>>,+ pub status: Option<Vec<storage_enums::PayoutStatus>>,+ pub payout_method: Option<Vec<common_enums::PayoutType>>,+ pub profile_id: Option<String>,+ pub customer_id: Option<String>,+ pub starting_after_id: Option<String>,+ pub ending_before_id: Option<String>,+ pub entity_type: Option<common_enums::PayoutEntityType>,+ pub limit: Option<u32>,+}++impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints {+ fn from(value: api_models::payouts::PayoutListConstraints) -> Self {+ Self::List(Box::new(PayoutListParams {+ offset: 0,+ starting_at: value+ .time_range+ .map_or(value.created, |t| Some(t.start_time)),+ ending_at: value.time_range.and_then(|t| t.end_time),+ connector: None,+ currency: None,+ status: None,+ payout_method: None,+ profile_id: None,+ customer_id: value.customer_id,+ starting_after_id: value.starting_after,+ ending_before_id: value.ending_before,+ entity_type: None,+ limit: Some(std::cmp::min(+ value.limit,+ consts::PAYOUTS_LIST_MAX_LIMIT_GET,+ )),+ }))+ }+}++impl From<api_models::payments::TimeRange> for PayoutFetchConstraints {+ fn from(value: api_models::payments::TimeRange) -> Self {+ Self::List(Box::new(PayoutListParams {+ offset: 0,+ starting_at: Some(value.start_time),+ ending_at: value.end_time,+ connector: None,+ currency: None,+ status: None,+ payout_method: None,+ profile_id: None,+ customer_id: None,+ starting_after_id: None,+ ending_before_id: None,+ entity_type: None,+ limit: None,+ }))+ }+}++impl From<api_models::payouts::PayoutListFilterConstraints> for PayoutFetchConstraints {+ fn from(value: api_models::payouts::PayoutListFilterConstraints) -> Self {+ if let Some(payout_id) = value.payout_id {+ Self::Single { payout_id }+ } else {+ Self::List(Box::new(PayoutListParams {+ offset: value.offset.unwrap_or_default(),+ starting_at: value.time_range.map(|t| t.start_time),+ ending_at: value.time_range.and_then(|t| t.end_time),+ connector: value.connector,+ currency: value.currency,+ status: value.status,+ payout_method: value.payout_method,+ profile_id: value.profile_id,+ customer_id: value.customer_id,+ starting_after_id: None,+ ending_before_id: None,+ entity_type: value.entity_type,+ limit: Some(std::cmp::min(+ value.limit,+ consts::PAYOUTS_LIST_MAX_LIMIT_POST,+ )),+ }))+ }+ }+}diff --git a/crates/data_models/src/payouts/payout_attempt.rs b/crates/data_models/src/payouts/payout_attempt.rsindex 081bc1cf98..5c4c98970f 100644--- a/crates/data_models/src/payouts/payout_attempt.rs+++ b/crates/data_models/src/payouts/payout_attempt.rs@@ -1,8 +1,10 @@+use api_models::enums::PayoutConnectors;use common_enums as storage_enums;use serde::{Deserialize, Serialize};use storage_enums::MerchantStorageScheme;use time::PrimitiveDateTime;+use super::payouts::Payouts;use crate::errors;#[async_trait::async_trait]@@ -26,6 +28,21 @@ pub trait PayoutAttemptInterface {_payout_attempt_id: &str,_storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PayoutAttempt, errors::StorageError>;++ async fn get_filters_for_payouts(+ &self,+ payout: &[Payouts],+ merchant_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PayoutListFilters, errors::StorageError>;+}++#[derive(Clone, Debug, Eq, PartialEq)]+pub struct PayoutListFilters {+ pub connector: Vec<PayoutConnectors>,+ pub currency: Vec<storage_enums::Currency>,+ pub status: Vec<storage_enums::PayoutStatus>,+ pub payout_method: Vec<storage_enums::PayoutType>,}#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]diff --git a/crates/data_models/src/payouts/payouts.rs b/crates/data_models/src/payouts/payouts.rsindex f897ca739b..e5a95108ef 100644--- a/crates/data_models/src/payouts/payouts.rs+++ b/crates/data_models/src/payouts/payouts.rs@@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};use storage_enums::MerchantStorageScheme;use time::PrimitiveDateTime;+#[cfg(feature = "olap")]+use super::{payout_attempt::PayoutAttempt, PayoutFetchConstraints};use crate::errors;#[async_trait::async_trait]@@ -34,6 +36,30 @@ pub trait PayoutsInterface {_payout_id: &str,_storage_scheme: MerchantStorageScheme,) -> error_stack::Result<Option<Payouts>, errors::StorageError>;++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_constraints(+ &self,+ _merchant_id: &str,+ _filters: &PayoutFetchConstraints,+ _storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;++ #[cfg(feature = "olap")]+ async fn filter_payouts_and_attempts(+ &self,+ _merchant_id: &str,+ _filters: &PayoutFetchConstraints,+ _storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt)>, errors::StorageError>;++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_time_range_constraints(+ &self,+ merchant_id: &str,+ time_range: &api_models::payments::TimeRange,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;}#[derive(Clone, Debug, Eq, PartialEq)]diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rsindex 9129d06e59..085423710f 100644--- a/crates/diesel_models/src/query/payout_attempt.rs+++ b/crates/diesel_models/src/query/payout_attempt.rs@@ -1,14 +1,22 @@-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};-use error_stack::report;+use std::collections::HashSet;++use async_bb8_diesel::AsyncRunQueryDsl;+use diesel::{+ associations::HasTable,+ query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl},+ BoolExpressionMethods, ExpressionMethods,+};+use error_stack::{report, IntoReport, ResultExt};use super::generics;use crate::{- errors,+ enums,+ errors::{self, DatabaseError},payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,},- schema::payout_attempt::dsl,- PgPooledConn, StorageResult,+ schema::{payout_attempt::dsl, payouts as payout_dsl},+ Payouts, PgPooledConn, StorageResult,};impl PayoutAttemptNew {@@ -114,4 +122,79 @@ impl PayoutAttempt {report!(errors::DatabaseError::NotFound).attach_printable("Error while updating payout")})}++ pub async fn get_filters_for_payouts(+ conn: &PgPooledConn,+ payouts: &[Payouts],+ merchant_id: &str,+ ) -> StorageResult<(+ Vec<String>,+ Vec<enums::Currency>,+ Vec<enums::PayoutStatus>,+ Vec<enums::PayoutType>,+ )> {+ let active_attempts: Vec<String> = payouts+ .iter()+ .map(|payout| {+ format!(+ "{}_{}",+ payout.payout_id.clone(),+ payout.attempt_count.clone()+ )+ })+ .collect();++ let filter = <Self as HasTable>::table()+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))+ .filter(dsl::payout_attempt_id.eq_any(active_attempts));++ let payout_status: Vec<enums::PayoutStatus> = payouts+ .iter()+ .map(|payout| payout.status)+ .collect::<HashSet<enums::PayoutStatus>>()+ .into_iter()+ .collect();++ let filter_connector = filter+ .clone()+ .select(dsl::connector)+ .distinct()+ .get_results_async::<Option<String>>(conn)+ .await+ .into_report()+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error filtering records by connector")?+ .into_iter()+ .flatten()+ .collect::<Vec<String>>();++ let filter_currency = <Payouts as HasTable>::table()+ .select(payout_dsl::destination_currency)+ .distinct()+ .get_results_async::<enums::Currency>(conn)+ .await+ .into_report()+ .change_context(DatabaseError::Others)+ .attach_printable("Error filtering records by currency")?+ .into_iter()+ .collect::<Vec<enums::Currency>>();++ let filter_payout_method = Payouts::table()+ .select(payout_dsl::payout_type)+ .distinct()+ .get_results_async::<enums::PayoutType>(conn)+ .await+ .into_report()+ .change_context(DatabaseError::Others)+ .attach_printable("Error filtering records by payout type")?+ .into_iter()+ .collect::<Vec<enums::PayoutType>>();++ Ok((+ filter_connector,+ filter_currency,+ payout_status,+ filter_payout_method,+ ))+ }}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex a341493f98..549353accb 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -163,6 +163,8 @@ Never share your secret api keys. Keep them guarded and secure.routes::payouts::payouts_update,routes::payouts::payouts_cancel,routes::payouts::payouts_fulfill,+ routes::payouts::payouts_list,+ routes::payouts::payouts_filter,// Routes for api keysroutes::api_keys::api_key_create,@@ -406,7 +408,6 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::CustomerDetails,api_models::payments::GiftCardData,api_models::payments::GiftCardDetails,- api_models::payouts::PayoutCreateRequest,api_models::payments::Address,api_models::payouts::Card,api_models::payouts::Wallet,@@ -414,11 +415,16 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payouts::AchBankTransfer,api_models::payouts::BacsBankTransfer,api_models::payouts::SepaBankTransfer,+ api_models::payouts::PayoutRequest,+ api_models::payouts::PayoutAttemptResponse,+ api_models::payouts::PayoutActionRequest,+ api_models::payouts::PayoutCreateRequest,api_models::payouts::PayoutCreateResponse,+ api_models::payouts::PayoutListConstraints,+ api_models::payouts::PayoutListFilterConstraints,+ api_models::payouts::PayoutListResponse,api_models::payouts::PayoutRetrieveBody,api_models::payouts::PayoutRetrieveRequest,- api_models::payouts::PayoutActionRequest,- api_models::payouts::PayoutRequest,api_models::payouts::PayoutMethodData,api_models::payouts::Bank,api_models::enums::PayoutEntityType,diff --git a/crates/openapi/src/routes/payouts.rs b/crates/openapi/src/routes/payouts.rsindex 3cc01de982..8a76be1289 100644--- a/crates/openapi/src/routes/payouts.rs+++ b/crates/openapi/src/routes/payouts.rs@@ -83,3 +83,31 @@ pub async fn payouts_cancel() {}security(("api_key" = [])))]pub async fn payouts_fulfill() {}++/// Payouts - List+#[utoipa::path(+ get,+ path = "/payouts/list",+ responses(+ (status = 200, description = "Payouts listed", body = PayoutListResponse),+ (status = 404, description = "Payout not found")+ ),+ tag = "Payouts",+ operation_id = "List payouts",+ security(("api_key" = []))+)]+pub async fn payouts_list() {}++/// Payouts - Filter+#[utoipa::path(+ post,+ path = "/payouts/list",+ responses(+ (status = 200, description = "Payouts filtered", body = PayoutListResponse),+ (status = 404, description = "Payout not found")+ ),+ tag = "Payouts",+ operation_id = "Filter payouts",+ security(("api_key" = []))+)]+pub async fn payouts_filter() {}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex bc440e1bc3..e6bac7e4aa 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -1,6 +1,8 @@use std::{fmt::Debug, marker::PhantomData, str::FromStr};use api_models::payments::{FrmMessage, RequestSurchargeDetails};+#[cfg(feature = "payouts")]+use api_models::payouts::PayoutAttemptResponse;use common_enums::RequestIncrementalAuthorization;use common_utils::{consts::X_HS_LATENCY, fp_utils};use diesel_models::ephemeral_key;@@ -959,6 +961,49 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay}}+#[cfg(feature = "payouts")]+impl ForeignFrom<(storage::Payouts, storage::PayoutAttempt)> for api::PayoutCreateResponse {+ fn foreign_from(item: (storage::Payouts, storage::PayoutAttempt)) -> Self {+ let payout = item.0;+ let payout_attempt = item.1;+ let attempt = PayoutAttemptResponse {+ attempt_id: payout_attempt.payout_attempt_id,+ status: payout_attempt.status,+ amount: payout.amount,+ currency: Some(payout.destination_currency),+ connector: payout_attempt.connector.clone(),+ error_code: payout_attempt.error_code,+ error_message: payout_attempt.error_message,+ payment_method: Some(payout.payout_type),+ payout_method_type: None,+ connector_transaction_id: Some(payout_attempt.connector_payout_id),+ cancellation_reason: None,+ payout_token: payout_attempt.payout_token,+ unified_code: None,+ unified_message: None,+ };+ let attempts = vec![attempt];+ Self {+ payout_id: payout.payout_id,+ merchant_id: payout.merchant_id,+ status: payout.status,+ amount: payout.amount,+ created: Some(payout.created_at),+ currency: payout.destination_currency,+ description: payout.description,+ metadata: payout.metadata,+ customer_id: payout.customer_id,+ connector: payout_attempt.connector,+ payout_type: payout.payout_type,+ business_label: payout_attempt.business_label,+ business_country: payout_attempt.business_country,+ recurring: payout.recurring,+ attempts: Some(attempts),+ ..Default::default()+ }+ }+}+impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse {fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self {Self {diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex b59ed10a49..5f47c5251e 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -7,12 +7,20 @@ use std::vec::IntoIter;use api_models::enums as api_enums;use common_utils::{crypto::Encryptable, ext_traits::ValueExt, pii};+#[cfg(feature = "olap")]+use data_models::errors::StorageError;use diesel_models::enums as storage_enums;use error_stack::{report, IntoReport, ResultExt};+#[cfg(feature = "olap")]+use futures::future::join_all;+#[cfg(feature = "olap")]+use router_env::logger;use router_env::{instrument, tracing};use serde_json;use super::errors::{ConnectorErrorExt, StorageErrorExt};+#[cfg(feature = "olap")]+use crate::types::transformers::ForeignFrom;use crate::{core::{errors::{self, RouterResponse, RouterResult},@@ -653,6 +661,133 @@ pub async fn payouts_fulfill_core(.await}+#[cfg(feature = "olap")]+pub async fn payouts_list_core(+ state: AppState,+ merchant_account: domain::MerchantAccount,+ constraints: payouts::PayoutListConstraints,+) -> RouterResponse<payouts::PayoutListResponse> {+ validator::validate_payout_list_request(&constraints)?;+ let merchant_id = &merchant_account.merchant_id;+ let db = state.store.as_ref();+ let payouts = helpers::filter_by_constraints(+ db,+ &constraints,+ merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;++ let collected_futures = payouts.into_iter().map(|payouts| async {+ match db+ .find_payout_attempt_by_merchant_id_payout_attempt_id(+ merchant_id,+ &utils::get_payment_attempt_id(payouts.payout_id.clone(), payouts.attempt_count),+ storage_enums::MerchantStorageScheme::PostgresOnly,+ )+ .await+ {+ Ok(payout_attempt) => Some(Ok((payouts, payout_attempt))),+ Err(error) => {+ if matches!(error.current_context(), StorageError::ValueNotFound(_)) {+ logger::warn!(+ ?error,+ "payout_attempt missing for payout_id : {}",+ payouts.payout_id,+ );+ return None;+ }+ Some(Err(error))+ }+ }+ });++ let pi_pa_tuple_vec: Result<Vec<(storage::Payouts, storage::PayoutAttempt)>, _> =+ join_all(collected_futures)+ .await+ .into_iter()+ .flatten()+ .collect::<Result<Vec<(storage::Payouts, storage::PayoutAttempt)>, _>>();++ let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec+ .change_context(errors::ApiErrorResponse::InternalServerError)?+ .into_iter()+ .map(ForeignFrom::foreign_from)+ .collect();++ Ok(services::ApplicationResponse::Json(+ api::PayoutListResponse {+ size: data.len(),+ data,+ },+ ))+}++#[cfg(feature = "olap")]+pub async fn payouts_filtered_list_core(+ state: AppState,+ merchant_account: domain::MerchantAccount,+ filters: payouts::PayoutListFilterConstraints,+) -> RouterResponse<payouts::PayoutListResponse> {+ let limit = &filters.limit;+ validator::validate_payout_list_request_for_joins(*limit)?;+ let db = state.store.as_ref();+ let list: Vec<(storage::Payouts, storage::PayoutAttempt)> = db+ .filter_payouts_and_attempts(+ &merchant_account.merchant_id,+ &filters.clone().into(),+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;++ let data: Vec<api::PayoutCreateResponse> =+ list.into_iter().map(ForeignFrom::foreign_from).collect();++ Ok(services::ApplicationResponse::Json(+ api::PayoutListResponse {+ size: data.len(),+ data,+ },+ ))+}++#[cfg(feature = "olap")]+pub async fn payouts_list_available_filters_core(+ state: AppState,+ merchant_account: domain::MerchantAccount,+ time_range: api::TimeRange,+) -> RouterResponse<api::PayoutListFilters> {+ let db = state.store.as_ref();+ let payout = db+ .filter_payouts_by_time_range_constraints(+ &merchant_account.merchant_id,+ &time_range,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ let filters = db+ .get_filters_for_payouts(+ payout.as_slice(),+ &merchant_account.merchant_id,+ storage_enums::MerchantStorageScheme::PostgresOnly,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ Ok(services::ApplicationResponse::Json(+ api::PayoutListFilters {+ connector: filters.connector,+ currency: filters.currency,+ status: filters.status,+ payout_method: filters.payout_method,+ },+ ))+}+// ********************************************** HELPERS **********************************************pub async fn call_connector_payout(state: &AppState,@@ -1332,6 +1467,8 @@ pub async fn response_handler(error_message: payout_attempt.error_message.to_owned(),error_code: payout_attempt.error_code,profile_id: payout_attempt.profile_id,+ created: Some(payouts.created_at),+ attempts: None,};Ok(services::ApplicationResponse::Json(response))}diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 4235be570e..f7ee340249 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -726,3 +726,16 @@ pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus| api_enums::PayoutStatus::RequiresPayoutMethodData,)}++#[cfg(feature = "olap")]+pub(super) async fn filter_by_constraints(+ db: &dyn StorageInterface,+ constraints: &api::PayoutListConstraints,+ merchant_id: &str,+ storage_scheme: storage::enums::MerchantStorageScheme,+) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {+ let result = db+ .filter_payouts_by_constraints(merchant_id, &constraints.clone().into(), storage_scheme)+ .await?;+ Ok(result)+}diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rsindex 8825835fc8..02ba306654 100644--- a/crates/router/src/core/payouts/validator.rs+++ b/crates/router/src/core/payouts/validator.rs@@ -1,3 +1,5 @@+#[cfg(feature = "olap")]+use common_utils::errors::CustomResult;pub use data_models::errors::StorageError;use error_stack::{report, ResultExt};use router_env::{instrument, tracing};@@ -116,3 +118,40 @@ pub async fn validate_create_request(Ok((payout_id, payout_method_data, profile_id))}++#[cfg(feature = "olap")]+pub(super) fn validate_payout_list_request(+ req: &payouts::PayoutListConstraints,+) -> CustomResult<(), errors::ApiErrorResponse> {+ use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_GET;++ utils::when(+ req.limit > PAYOUTS_LIST_MAX_LIMIT_GET || req.limit < 1,+ || {+ Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "limit should be in between 1 and {}",+ PAYOUTS_LIST_MAX_LIMIT_GET+ ),+ })+ },+ )?;+ Ok(())+}++#[cfg(feature = "olap")]+pub(super) fn validate_payout_list_request_for_joins(+ limit: u32,+) -> CustomResult<(), errors::ApiErrorResponse> {+ use common_utils::consts::PAYOUTS_LIST_MAX_LIMIT_POST;++ utils::when(!(1..=PAYOUTS_LIST_MAX_LIMIT_POST).contains(&limit), || {+ Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "limit should be in between 1 and {}",+ PAYOUTS_LIST_MAX_LIMIT_POST+ ),+ })+ })?;+ Ok(())+}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 46b3313788..a65a6ca462 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1403,6 +1403,20 @@ impl PayoutAttemptInterface for KafkaStore {.insert_payout_attempt(payout_attempt, storage_scheme).await}++ async fn get_filters_for_payouts(+ &self,+ payouts: &[data_models::payouts::payouts::Payouts],+ merchant_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<+ data_models::payouts::payout_attempt::PayoutListFilters,+ errors::DataStorageError,+ > {+ self.diesel_store+ .get_filters_for_payouts(payouts, merchant_id, storage_scheme)+ .await+ }}#[cfg(not(feature = "payouts"))]@@ -1453,6 +1467,43 @@ impl PayoutsInterface for KafkaStore {.find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme).await}++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_constraints(+ &self,+ merchant_id: &str,+ filters: &data_models::payouts::PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {+ self.diesel_store+ .filter_payouts_by_constraints(merchant_id, filters, storage_scheme)+ .await+ }++ #[cfg(feature = "olap")]+ async fn filter_payouts_and_attempts(+ &self,+ merchant_id: &str,+ filters: &data_models::payouts::PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<(storage::Payouts, storage::PayoutAttempt)>, errors::DataStorageError>+ {+ self.diesel_store+ .filter_payouts_and_attempts(merchant_id, filters, storage_scheme)+ .await+ }++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_time_range_constraints(+ &self,+ merchant_id: &str,+ time_range: &api_models::payments::TimeRange,+ storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {+ self.diesel_store+ .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)+ .await+ }}#[async_trait::async_trait]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 6a3f042a7e..c08aae5dc6 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -689,16 +689,30 @@ pub struct Payouts;#[cfg(feature = "payouts")]impl Payouts {pub fn server(state: AppState) -> Scope {- let route = web::scope("/payouts").app_data(web::Data::new(state));- route- .service(web::resource("/create").route(web::post().to(payouts_create)))- .service(web::resource("/{payout_id}/cancel").route(web::post().to(payouts_cancel)))- .service(web::resource("/{payout_id}/fulfill").route(web::post().to(payouts_fulfill)))+ let mut route = web::scope("/payouts").app_data(web::Data::new(state));+ route = route.service(web::resource("/create").route(web::post().to(payouts_create)));++ #[cfg(feature = "olap")]+ {+ route = route+ .service(+ web::resource("/list")+ .route(web::get().to(payouts_list))+ .route(web::post().to(payouts_list_by_filter)),+ )+ .service(+ web::resource("/filter").route(web::post().to(payouts_list_available_filters)),+ );+ }+ route = route.service(web::resource("/{payout_id}").route(web::get().to(payouts_retrieve)).route(web::put().to(payouts_update)),)+ .service(web::resource("/{payout_id}/cancel").route(web::post().to(payouts_cancel)))+ .service(web::resource("/{payout_id}/fulfill").route(web::post().to(payouts_fulfill)));+ route}}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 08b250e94b..43802d2445 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -123,6 +123,8 @@ impl From<Flow> for ApiIdentifier {| Flow::PayoutsUpdate| Flow::PayoutsCancel| Flow::PayoutsFulfill+ | Flow::PayoutsList+ | Flow::PayoutsFilter| Flow::PayoutsAccounts => Self::Payouts,Flow::RefundsCreatediff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rsindex a5bb22e87d..c8d1c05bb3 100644--- a/crates/router/src/routes/payouts.rs+++ b/crates/router/src/routes/payouts.rs@@ -5,6 +5,8 @@ use actix_web::{use router_env::{instrument, tracing, Flow};use super::app::AppState;+#[cfg(feature = "olap")]+use crate::types::api::payments as payment_types;use crate::{core::{api_locking, payouts::*},services::{api, authentication as auth},@@ -195,6 +197,108 @@ pub async fn payouts_fulfill(.await}+/// Payouts - List+#[cfg(feature = "olap")]+#[utoipa::path(+ get,+ path = "/payouts/list",+ responses(+ (status = 200, description = "Payouts listed", body = PayoutListResponse),+ (status = 404, description = "Payout not found")+ ),+ tag = "Payouts",+ operation_id = "List payouts",+ security(("api_key" = []))+)]+#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]+pub async fn payouts_list(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Query<payout_types::PayoutListConstraints>,+) -> HttpResponse {+ let flow = Flow::PayoutsList;+ let payload = json_payload.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth, req| payouts_list_core(state, auth.merchant_account, req),+ &auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++/// Payouts - Filtered list+#[cfg(feature = "olap")]+#[utoipa::path(+ post,+ path = "/payouts/list",+ responses(+ (status = 200, description = "Payouts filtered", body = PayoutListResponse),+ (status = 404, description = "Payout not found")+ ),+ tag = "Payouts",+ operation_id = "Filter payouts",+ security(("api_key" = []))+)]+#[instrument(skip_all, fields(flow = ?Flow::PayoutsList))]+pub async fn payouts_list_by_filter(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<payout_types::PayoutListFilterConstraints>,+) -> HttpResponse {+ let flow = Flow::PayoutsList;+ let payload = json_payload.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth, req| payouts_filtered_list_core(state, auth.merchant_account, req),+ &auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++/// Payouts - Available filters+#[cfg(feature = "olap")]+#[utoipa::path(+ post,+ path = "/payouts/filter",+ responses(+ (status = 200, description = "Payouts filtered", body = PayoutListFilters),+ (status = 404, description = "Payout not found")+ ),+ tag = "Payouts",+ operation_id = "Filter payouts",+ security(("api_key" = []))+)]+#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]+pub async fn payouts_list_available_filters(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<payment_types::TimeRange>,+) -> HttpResponse {+ let flow = Flow::PayoutsFilter;+ let payload = json_payload.into_inner();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth, req| payouts_list_available_filters_core(state, auth.merchant_account, req),+ &auth::ApiKeyAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[instrument(skip_all, fields(flow = ?Flow::PayoutsAccounts))]// #[get("/accounts")]pub async fn payouts_accounts() -> impl Responder {diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rsindex 0edc5d47a9..bed87173b8 100644--- a/crates/router/src/types/api/payouts.rs+++ b/crates/router/src/types/api/payouts.rs@@ -1,6 +1,7 @@pub use api_models::payouts::{AchBankTransfer, BacsBankTransfer, Bank as BankPayout, Card as CardPayout, PayoutActionRequest,- PayoutCreateRequest, PayoutCreateResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,+ PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints,+ PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,PayoutRetrieveRequest, SepaBankTransfer, Wallet as WalletPayout,};diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex abf5d1206e..b521acbdcd 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -164,6 +164,12 @@ pub enum Flow {#[cfg(feature = "payouts")]/// Payouts fulfill flow.PayoutsFulfill,+ #[cfg(feature = "payouts")]+ /// Payouts list flow.+ PayoutsList,+ #[cfg(feature = "payouts")]+ /// Payouts filter flow.+ PayoutsFilter,/// Payouts accounts flow.PayoutsAccounts,/// Payments Redirect flow.diff --git a/crates/storage_impl/src/mock_db/payout_attempt.rs b/crates/storage_impl/src/mock_db/payout_attempt.rsindex 543ce5cf65..1590dea6e7 100644--- a/crates/storage_impl/src/mock_db/payout_attempt.rs+++ b/crates/storage_impl/src/mock_db/payout_attempt.rs@@ -39,4 +39,13 @@ impl PayoutAttemptInterface for MockDb {// TODO: Implement function for `MockDb`Err(StorageError::MockDbError)?}++ async fn get_filters_for_payouts(+ &self,+ _payouts: &[data_models::payouts::payouts::Payouts],+ _merchant_id: &str,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<data_models::payouts::payout_attempt::PayoutListFilters, StorageError> {+ Err(StorageError::MockDbError)?+ }}diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rsindex 9b4305afce..1af0528369 100644--- a/crates/storage_impl/src/mock_db/payouts.rs+++ b/crates/storage_impl/src/mock_db/payouts.rs@@ -1,4 +1,6 @@use common_utils::errors::CustomResult;+#[cfg(all(feature = "olap", feature = "payouts"))]+use data_models::payouts::payout_attempt::PayoutAttempt;use data_models::{errors::StorageError,payouts::payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},@@ -47,4 +49,37 @@ impl PayoutsInterface for MockDb {// TODO: Implement function for `MockDb`Err(StorageError::MockDbError)?}++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_constraints(+ &self,+ _merchant_id: &str,+ _filters: &data_models::payouts::PayoutFetchConstraints,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<Vec<Payouts>, StorageError> {+ // TODO: Implement function for `MockDb`+ Err(StorageError::MockDbError)?+ }++ #[cfg(feature = "olap")]+ async fn filter_payouts_and_attempts(+ &self,+ _merchant_id: &str,+ _filters: &data_models::payouts::PayoutFetchConstraints,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<Vec<(Payouts, PayoutAttempt)>, StorageError> {+ // TODO: Implement function for `MockDb`+ Err(StorageError::MockDbError)?+ }++ #[cfg(feature = "olap")]+ async fn filter_payouts_by_time_range_constraints(+ &self,+ _merchant_id: &str,+ _time_range: &api_models::payments::TimeRange,+ _storage_scheme: storage_enums::MerchantStorageScheme,+ ) -> CustomResult<Vec<Payouts>, StorageError> {+ // TODO: Implement function for `MockDb`+ Err(StorageError::MockDbError)?+ }}diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rsindex 2c82d995f0..c52291253e 100644--- a/crates/storage_impl/src/payouts/payout_attempt.rs+++ b/crates/storage_impl/src/payouts/payout_attempt.rs@@ -1,8 +1,15 @@-use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found};+use std::str::FromStr;++use api_models::enums::PayoutConnectors;+use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found};use data_models::{errors,- payouts::payout_attempt::{- PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,+ payouts::{+ payout_attempt::{+ PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,+ PayoutListFilters,+ },+ payouts::Payouts,},};use diesel_models::{@@ -16,7 +23,7 @@ use diesel_models::{};use error_stack::{IntoReport, ResultExt};use redis_interface::HsetnxReply;-use router_env::{instrument, tracing};+use router_env::{instrument, logger, tracing};use crate::{diesel_error_to_data_error,@@ -227,6 +234,18 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {}}}++ #[instrument(skip_all)]+ async fn get_filters_for_payouts(+ &self,+ payouts: &[Payouts],+ merchant_id: &str,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<PayoutListFilters, errors::StorageError> {+ self.router_store+ .get_filters_for_payouts(payouts, merchant_id, storage_scheme)+ .await+ }}#[async_trait::async_trait]@@ -287,6 +306,48 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {er.change_context(new_err)})}++ #[instrument(skip_all)]+ async fn get_filters_for_payouts(+ &self,+ payouts: &[Payouts],+ merchant_id: &str,+ _storage_scheme: MerchantStorageScheme,+ ) -> CustomResult<PayoutListFilters, errors::StorageError> {+ let conn = pg_connection_read(self).await?;+ let payouts = payouts+ .iter()+ .cloned()+ .map(|payouts| payouts.to_storage_model())+ .collect::<Vec<diesel_models::Payouts>>();+ DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id)+ .await+ .map_err(|er| {+ let new_err = diesel_error_to_data_error(er.current_context());+ er.change_context(new_err)+ })+ .map(+ |(connector, currency, status, payout_method)| PayoutListFilters {+ connector: connector+ .iter()+ .filter_map(|c| {+ PayoutConnectors::from_str(c)+ .map_err(|e| {+ logger::error!(+ "Failed to parse payout connector '{}' - {}",+ c,+ e+ );+ })+ .ok()+ })+ .collect(),+ currency,+ status,+ payout_method,+ },+ )+ }}impl DataModelExt for PayoutAttempt {diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rsindex 5f27ddbbf1..c42ed12017 100644--- a/crates/storage_impl/src/payouts/payouts.rs+++ b/crates/storage_impl/src/payouts/payouts.rs@@ -1,8 +1,14 @@+#[cfg(feature = "olap")]+use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};use common_utils::ext_traits::Encode;+#[cfg(feature = "olap")]+use data_models::payouts::{payout_attempt::PayoutAttempt, PayoutFetchConstraints};use data_models::{errors::StorageError,payouts::payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},};+#[cfg(feature = "olap")]+use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};use diesel_models::{enums::MerchantStorageScheme,kv,@@ -11,10 +17,20 @@ use diesel_models::{PayoutsUpdate as DieselPayoutsUpdate,},};+#[cfg(feature = "olap")]+use diesel_models::{+ payout_attempt::PayoutAttempt as DieselPayoutAttempt,+ query::generics::db_metrics,+ schema::{payout_attempt::dsl as poa_dsl, payouts::dsl as po_dsl},+};use error_stack::{IntoReport, ResultExt};use redis_interface::HsetnxReply;+#[cfg(feature = "olap")]+use router_env::logger;use router_env::{instrument, tracing};+#[cfg(feature = "olap")]+use crate::connection;use crate::{diesel_error_to_data_error,errors::RedisErrorExt,@@ -233,6 +249,45 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {}.map(|payout| payout.map(Payouts::from_storage_model))}++ #[cfg(feature = "olap")]+ #[instrument(skip_all)]+ async fn filter_payouts_by_constraints(+ &self,+ merchant_id: &str,+ filters: &PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, StorageError> {+ self.router_store+ .filter_payouts_by_constraints(merchant_id, filters, storage_scheme)+ .await+ }++ #[cfg(feature = "olap")]+ #[instrument(skip_all)]+ async fn filter_payouts_and_attempts(+ &self,+ merchant_id: &str,+ filters: &PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt)>, StorageError> {+ self.router_store+ .filter_payouts_and_attempts(merchant_id, filters, storage_scheme)+ .await+ }++ #[cfg(feature = "olap")]+ #[instrument[skip_all]]+ async fn filter_payouts_by_time_range_constraints(+ &self,+ merchant_id: &str,+ time_range: &api_models::payments::TimeRange,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, StorageError> {+ self.router_store+ .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)+ .await+ }}#[async_trait::async_trait]@@ -306,6 +361,264 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {er.change_context(new_err)})}++ #[cfg(feature = "olap")]+ #[instrument(skip_all)]+ async fn filter_payouts_by_constraints(+ &self,+ merchant_id: &str,+ filters: &PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, StorageError> {+ use common_utils::errors::ReportSwitchExt;++ let conn = connection::pg_connection_read(self).await.switch()?;+ let conn = async_bb8_diesel::Connection::as_async_conn(&conn);++ //[#350]: Replace this with Boxable Expression and pass it into generic filter+ // when https://github.com/rust-lang/rust/issues/52662 becomes stable+ let mut query = <DieselPayouts as HasTable>::table()+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))+ .order(po_dsl::created_at.desc())+ .into_boxed();++ match filters {+ PayoutFetchConstraints::Single { payout_id } => {+ query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned()));+ }+ PayoutFetchConstraints::List(params) => {+ if let Some(limit) = params.limit {+ query = query.limit(limit.into());+ }++ if let Some(customer_id) = ¶ms.customer_id {+ query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));+ }+ if let Some(profile_id) = ¶ms.profile_id {+ query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));+ }++ query = match (params.starting_at, ¶ms.starting_after_id) {+ (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),+ (None, Some(starting_after_id)) => {+ // TODO: Fetch partial columns for this query since we only need some columns+ let starting_at = self+ .find_payout_by_merchant_id_payout_id(+ merchant_id,+ starting_after_id,+ storage_scheme,+ )+ .await?+ .created_at;+ query.filter(po_dsl::created_at.ge(starting_at))+ }+ (None, None) => query,+ };++ query = match (params.ending_at, ¶ms.ending_before_id) {+ (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),+ (None, Some(ending_before_id)) => {+ // TODO: Fetch partial columns for this query since we only need some columns+ let ending_at = self+ .find_payout_by_merchant_id_payout_id(+ merchant_id,+ ending_before_id,+ storage_scheme,+ )+ .await?+ .created_at;+ query.filter(po_dsl::created_at.le(ending_at))+ }+ (None, None) => query,+ };++ query = query.offset(params.offset.into());++ query = match ¶ms.currency {+ Some(currency) => {+ query.filter(po_dsl::destination_currency.eq_any(currency.clone()))+ }+ None => query,+ };++ query = match ¶ms.status {+ Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),+ None => query,+ };++ if let Some(currency) = ¶ms.currency {+ query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));+ }++ if let Some(status) = ¶ms.status {+ query = query.filter(po_dsl::status.eq_any(status.clone()));+ }+ }+ }++ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());++ db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(+ query.get_results_async::<DieselPayouts>(conn),+ db_metrics::DatabaseOperation::Filter,+ )+ .await+ .map(|payouts| {+ payouts+ .into_iter()+ .map(Payouts::from_storage_model)+ .collect::<Vec<Payouts>>()+ })+ .map_err(|er| {+ StorageError::DatabaseError(+ error_stack::report!(diesel_models::errors::DatabaseError::from(er))+ .attach_printable("Error filtering payout records"),+ )+ })+ .into_report()+ }++ #[cfg(feature = "olap")]+ #[instrument(skip_all)]+ async fn filter_payouts_and_attempts(+ &self,+ merchant_id: &str,+ filters: &PayoutFetchConstraints,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<(Payouts, PayoutAttempt)>, StorageError> {+ use common_utils::errors::ReportSwitchExt;++ let conn = connection::pg_connection_read(self).await.switch()?;+ let conn = async_bb8_diesel::Connection::as_async_conn(&conn);+ let mut query = DieselPayouts::table()+ .inner_join(+ diesel_models::schema::payout_attempt::table+ .on(poa_dsl::payout_id.eq(po_dsl::payout_id)),+ )+ .filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))+ .order(po_dsl::created_at.desc())+ .into_boxed();++ query = match filters {+ PayoutFetchConstraints::Single { payout_id } => {+ query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))+ }+ PayoutFetchConstraints::List(params) => {+ if let Some(limit) = params.limit {+ query = query.limit(limit.into());+ }++ if let Some(customer_id) = ¶ms.customer_id {+ query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));+ }++ if let Some(profile_id) = ¶ms.profile_id {+ query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));+ }++ query = match (params.starting_at, ¶ms.starting_after_id) {+ (Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),+ (None, Some(starting_after_id)) => {+ // TODO: Fetch partial columns for this query since we only need some columns+ let starting_at = self+ .find_payout_by_merchant_id_payout_id(+ merchant_id,+ starting_after_id,+ storage_scheme,+ )+ .await?+ .created_at;+ query.filter(po_dsl::created_at.ge(starting_at))+ }+ (None, None) => query,+ };++ query = match (params.ending_at, ¶ms.ending_before_id) {+ (Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),+ (None, Some(ending_before_id)) => {+ // TODO: Fetch partial columns for this query since we only need some columns+ let ending_at = self+ .find_payout_by_merchant_id_payout_id(+ merchant_id,+ ending_before_id,+ storage_scheme,+ )+ .await?+ .created_at;+ query.filter(po_dsl::created_at.le(ending_at))+ }+ (None, None) => query,+ };++ query = query.offset(params.offset.into());++ if let Some(currency) = ¶ms.currency {+ query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));+ }++ let connectors = params+ .connector+ .as_ref()+ .map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>());++ query = match connectors {+ Some(connectors) => query.filter(poa_dsl::connector.eq_any(connectors)),+ None => query,+ };++ query = match ¶ms.status {+ Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),+ None => query,+ };++ query = match ¶ms.payout_method {+ Some(payout_method) => {+ query.filter(po_dsl::payout_type.eq_any(payout_method.clone()))+ }+ None => query,+ };++ query+ }+ };++ logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());++ query+ .get_results_async::<(DieselPayouts, DieselPayoutAttempt)>(conn)+ .await+ .map(|results| {+ results+ .into_iter()+ .map(|(pi, pa)| {+ (+ Payouts::from_storage_model(pi),+ PayoutAttempt::from_storage_model(pa),+ )+ })+ .collect()+ })+ .map_err(|er| {+ StorageError::DatabaseError(+ error_stack::report!(diesel_models::errors::DatabaseError::from(er))+ .attach_printable("Error filtering payout records"),+ )+ })+ .into_report()+ }++ #[cfg(feature = "olap")]+ #[instrument(skip_all)]+ async fn filter_payouts_by_time_range_constraints(+ &self,+ merchant_id: &str,+ time_range: &api_models::payments::TimeRange,+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<Vec<Payouts>, StorageError> {+ let payout_filters = (*time_range).into();+ self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme)+ .await+ }}impl DataModelExt for Payouts {diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex bd4eee14d8..10bf5b3543 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -3303,6 +3303,64 @@]}},+ "/payouts/list": {+ "get": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - List",+ "description": "Payouts - List",+ "operationId": "List payouts",+ "responses": {+ "200": {+ "description": "Payouts listed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutListResponse"+ }+ }+ }+ },+ "404": {+ "description": "Payout not found"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ },+ "post": {+ "tags": [+ "Payouts"+ ],+ "summary": "Payouts - Filter",+ "description": "Payouts - Filter",+ "operationId": "Filter payouts",+ "responses": {+ "200": {+ "description": "Payouts filtered",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PayoutListResponse"+ }+ }+ }+ },+ "404": {+ "description": "Payout not found"+ }+ },+ "security": [+ {+ "api_key": []+ }+ ]+ }+ },"/payouts/{payout_id}": {"get": {"tags": [@@ -14842,6 +14900,92 @@}}},+ "PayoutAttemptResponse": {+ "type": "object",+ "required": [+ "attempt_id",+ "status",+ "amount"+ ],+ "properties": {+ "attempt_id": {+ "type": "string",+ "description": "Unique identifier for the attempt"+ },+ "status": {+ "$ref": "#/components/schemas/PayoutStatus"+ },+ "amount": {+ "type": "integer",+ "format": "int64",+ "description": "The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,"+ },+ "currency": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Currency"+ }+ ],+ "nullable": true+ },+ "connector": {+ "type": "string",+ "description": "The connector used for the payout",+ "nullable": true+ },+ "error_code": {+ "type": "string",+ "description": "Connector's error code in case of failures",+ "nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Connector's error message in case of failures",+ "nullable": true+ },+ "payment_method": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PayoutType"+ }+ ],+ "nullable": true+ },+ "payout_method_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/PaymentMethodType"+ }+ ],+ "nullable": true+ },+ "connector_transaction_id": {+ "type": "string",+ "description": "A unique identifier for a payout provided by the connector",+ "nullable": true+ },+ "cancellation_reason": {+ "type": "string",+ "description": "If the payout was cancelled the reason provided here",+ "nullable": true+ },+ "payout_token": {+ "type": "string",+ "description": "Provide a reference to a stored payout method",+ "nullable": true+ },+ "unified_code": {+ "type": "string",+ "description": "error code unified across the connectors is received here if there was an error while calling connector",+ "nullable": true+ },+ "unified_message": {+ "type": "string",+ "description": "error message unified across the connectors is received here if there was an error while calling connector",+ "nullable": true+ }+ }+ },"PayoutConnectors": {"type": "string","enum": [@@ -15172,6 +15316,21 @@"profile_id": {"type": "string","description": "The business profile that is associated with this payment"+ },+ "created": {+ "type": "string",+ "format": "date-time",+ "description": "Time when the payout was created",+ "example": "2022-09-10T10:11:12Z",+ "nullable": true+ },+ "attempts": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutAttemptResponse"+ },+ "description": "List of attempts",+ "nullable": true}}},@@ -15187,6 +15346,171 @@"Personal"]},+ "PayoutListConstraints": {+ "allOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/TimeRange"+ }+ ],+ "nullable": true+ },+ {+ "type": "object",+ "properties": {+ "customer_id": {+ "type": "string",+ "description": "The identifier for customer",+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",+ "nullable": true+ },+ "starting_after": {+ "type": "string",+ "description": "A cursor for use in pagination, fetch the next list after some object",+ "example": "pay_fafa124123",+ "nullable": true+ },+ "ending_before": {+ "type": "string",+ "description": "A cursor for use in pagination, fetch the previous list before some object",+ "example": "pay_fafa124123",+ "nullable": true+ },+ "limit": {+ "type": "integer",+ "format": "int32",+ "description": "limit on the number of objects to return",+ "default": 10,+ "maximum": 100,+ "minimum": 0+ },+ "created": {+ "type": "string",+ "format": "date-time",+ "description": "The time at which payout is created",+ "example": "2022-09-10T10:11:12Z",+ "nullable": true+ }+ }+ }+ ]+ },+ "PayoutListFilterConstraints": {+ "allOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/TimeRange"+ }+ ],+ "nullable": true+ },+ {+ "type": "object",+ "required": [+ "currency",+ "entity_type"+ ],+ "properties": {+ "payout_id": {+ "type": "string",+ "description": "The identifier for payout",+ "example": "payout_mbabizu24mvu3mela5njyhpit4",+ "nullable": true,+ "maxLength": 30,+ "minLength": 30+ },+ "profile_id": {+ "type": "string",+ "description": "The identifier for business profile",+ "nullable": true+ },+ "customer_id": {+ "type": "string",+ "description": "The identifier for customer",+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",+ "nullable": true+ },+ "limit": {+ "type": "integer",+ "format": "int32",+ "description": "The limit on the number of objects. The default limit is 10 and max limit is 20",+ "minimum": 0+ },+ "offset": {+ "type": "integer",+ "format": "int32",+ "description": "The starting point within a list of objects",+ "nullable": true,+ "minimum": 0+ },+ "connector": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutConnectors"+ },+ "description": "The list of connectors to filter payouts list",+ "example": [+ "wise",+ "adyen"+ ],+ "nullable": true+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "status": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutStatus"+ },+ "description": "The list of payout status to filter payouts list",+ "example": [+ "pending",+ "failed"+ ],+ "nullable": true+ },+ "payout_method": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutType"+ },+ "description": "The list of payout methods to filter payouts list",+ "example": [+ "bank",+ "card"+ ],+ "nullable": true+ },+ "entity_type": {+ "$ref": "#/components/schemas/PayoutEntityType"+ }+ }+ }+ ]+ },+ "PayoutListResponse": {+ "type": "object",+ "required": [+ "size",+ "data"+ ],+ "properties": {+ "size": {+ "type": "integer",+ "description": "The number of payouts included in the list",+ "minimum": 0+ },+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutCreateResponse"+ }+ }+ }+ },"PayoutMethodData": {"oneOf": [{