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(platform): implement platform refund list (#12615)
Ankit Kumar Guptaba7ef4bd8c8d
diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rsindex 3a20b1ce85..0b0d244737 100644--- a/crates/api_models/src/events/refund.rs+++ b/crates/api_models/src/events/refund.rs@@ -6,6 +6,7 @@ use crate::refunds::{};#[cfg(feature = "v1")]use crate::refunds::{+ PlatformRefundListFilters, PlatformRefundListRequest, PlatformRefundListResponse,RefundManualUpdateRequest, RefundRequest, RefundReverseRequest, RefundUpdateRequest,RefundsRetrieveRequest,};@@ -122,3 +123,24 @@ impl ApiEventMetric for RefundListFilters {Some(ApiEventsType::ResourceListAPI)}}++#[cfg(feature = "v1")]+impl ApiEventMetric for PlatformRefundListRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}++#[cfg(feature = "v1")]+impl ApiEventMetric for PlatformRefundListResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}++#[cfg(feature = "v1")]+impl ApiEventMetric for PlatformRefundListFilters {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 2cf221953a..c183cb498a 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -1,4 +1,4 @@-#[cfg(feature = "v1")]+#[cfg(any(feature = "v1", feature = "v2"))]use std::fmt;use std::{collections::{HashMap, HashSet},@@ -38,12 +38,12 @@ pub use self::recipient::{RecipientBankAccount, RecipientDetails,};use crate::customers::CustomerDocumentDetails;-#[cfg(feature = "v2")]-fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>+#[cfg(any(feature = "v1", feature = "v2"))]+pub(crate) fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error>where- D: serde::Deserializer<'de>,+ D: Deserializer<'de>,T: std::str::FromStr,- <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,+ <T as std::str::FromStr>::Err: fmt::Debug + fmt::Display + std::error::Error,{let opt_str: Option<String> = Option::deserialize(v)?;match opt_str {@@ -57,7 +57,7 @@ wherelet trimmed_item = item.trim();if !trimmed_item.is_empty() {let parsed_item = trimmed_item.parse::<T>().map_err(|e| {- <D::Error as serde::de::Error>::custom(format!(+ <D::Error as de::Error>::custom(format!("Invalid value '{trimmed_item}': {e}"))})?;@@ -71,7 +71,7 @@ where}use hyperswitch_masking::{PeekInterface, Secret, WithType};use router_derive::Setter;-#[cfg(feature = "v1")]+#[cfg(any(feature = "v1", feature = "v2"))]use serde::{de, Deserializer};use serde::{ser::Serializer, Deserialize, Serialize};use smithy::SmithyModel;diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rsindex 9e9072baba..9a21aaed89 100644--- a/crates/api_models/src/refunds.rs+++ b/crates/api_models/src/refunds.rs@@ -538,6 +538,110 @@ pub struct RefundListResponse {pub data: Vec<RefundResponse>,}+#[cfg(feature = "v1")]+#[derive(Debug, Clone, Deserialize, Serialize)]+pub struct PlatformRefundListRequest {+ /// The identifier for the connected (processor) merchant whose credentials processed the+ /// refund. When omitted, refunds across all connected merchants under the platform are returned.+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,+ /// The identifier for the payment+ pub payment_id: Option<common_utils::id_type::PaymentId>,+ /// The identifier for the refund+ pub refund_id: Option<String>,+ /// The identifier for business profile+ pub profile_id: Option<common_utils::id_type::ProfileId>,+ /// Limit on the number of objects to return+ #[serde(default)]+ pub limit: Option<common_utils::types::list::PageSize>,+ /// The starting point within a list of objects+ #[serde(default)]+ pub offset: common_utils::types::list::PageOffset,+ /// 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)]+ pub time_range: Option<TimeRange>,+ /// The start amount (inclusive) to filter refunds list by.+ pub start_amount: Option<i64>,+ /// The end amount (inclusive) to filter refunds list by.+ pub end_amount: Option<i64>,+ /// The comma separated list of connectors to filter refunds list+ #[serde(deserialize_with = "crate::payments::parse_comma_separated", default)]+ pub connector: Option<Vec<String>>,+ /// The comma separated list of merchant connector ids to filter the refunds list for selected label+ #[serde(deserialize_with = "crate::payments::parse_comma_separated", default)]+ pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,+ /// The comma separated list of currencies to filter refunds list+ #[serde(deserialize_with = "crate::payments::parse_comma_separated", default)]+ pub currency: Option<Vec<enums::Currency>>,+ /// The comma separated list of refund statuses to filter refunds list+ #[serde(deserialize_with = "crate::payments::parse_comma_separated", default)]+ pub refund_status: Option<Vec<enums::RefundStatus>>,+}++#[cfg(feature = "v1")]+#[derive(Debug, Clone, Serialize)]+pub struct PlatformRefundListItem {+ /// Unique identifier for the refund+ pub refund_id: String,+ /// The payment id against which the refund was initiated+ pub payment_id: common_utils::id_type::PaymentId,+ /// Identifier of the platform merchant. Equals the caller's merchant id.+ pub merchant_id: common_utils::id_type::MerchantId,+ /// Identifier of the connected merchant that owns this refund.+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,+ /// Identifier of the business profile under which this refund was created.+ pub profile_id: Option<common_utils::id_type::ProfileId>,+ /// The connector used for the refund+ pub connector: String,+ /// The merchant_connector_id of the processor through which this refund went through+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,+ /// A unique identifier for a refund provided by the connector+ pub connector_refund_id: Option<String>,+ /// Payment attempt id against which the refund is initiated+ pub attempt_id: String,+ /// The refund amount in lowest denomination of the currency+ pub refund_amount: MinorUnit,+ /// Total payment amount on which the refund was initiated+ pub total_amount: MinorUnit,+ /// The three-letter ISO currency code+ pub currency: enums::Currency,+ /// The status of the refund+ pub refund_status: enums::RefundStatus,+ /// Reason for the refund+ pub refund_reason: Option<String>,+ /// Description of the refund+ pub description: Option<String>,+ /// The timestamp at which refund was created+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub created_at: PrimitiveDateTime,+ /// The timestamp at which refund was last modified+ #[serde(with = "common_utils::custom_serde::iso8601")]+ pub modified_at: PrimitiveDateTime,+}++#[cfg(feature = "v1")]+#[derive(Debug, Clone, Serialize)]+pub struct PlatformRefundListResponse {+ /// The number of refunds included in the current response+ pub count: usize,+ /// The total number of refunds matching the given constraints (ignores limit/offset)+ pub total_count: i64,+ /// The list of refund summaries across the platform's connected merchants+ pub data: Vec<PlatformRefundListItem>,+}++/// Available filter values for a platform refunds list, aggregated across all of the+/// platform's connected merchants.+#[cfg(feature = "v1")]+#[derive(Debug, Clone, Serialize)]+pub struct PlatformRefundListFilters {+ /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances+ pub connector: HashMap<String, Vec<MerchantConnectorInfo>>,+ /// The list of available currency filters+ pub currency: Vec<enums::Currency>,+ /// The list of available refund status filters+ pub refund_status: Vec<enums::RefundStatus>,+}+#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)]pub struct RefundListMetaData {/// The list of available connector filtersdiff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rsindex 57fc93ab0b..8427a7098e 100644--- a/crates/hyperswitch_domain_models/src/refunds.rs+++ b/crates/hyperswitch_domain_models/src/refunds.rs@@ -16,6 +16,7 @@ pub struct RefundListConstraints {pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,pub currency: Option<Vec<common_enums::Currency>>,pub refund_status: Option<Vec<common_enums::RefundStatus>>,+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,}#[cfg(feature = "v2")]@@ -89,9 +90,6 @@ implpayment_id,refund_id,profile_id: profile_id_list,- // API keeps `Option<PageSize>` for wire compat; the domain holds a resolved- // value. `PageSize::default()` is the semantically-correct "no preference"- // — same behavior as the previous `Option<i64>` validator's `None → 10`.limit: limit.unwrap_or_default(),offset,time_range,@@ -100,10 +98,51 @@ implmerchant_connector_id,currency,refund_status,+ processor_merchant_id: None,})}}+#[cfg(feature = "v1")]+impl From<api_models::refunds::PlatformRefundListRequest> for RefundListConstraints {+ fn from(value: api_models::refunds::PlatformRefundListRequest) -> Self {+ let api_models::refunds::PlatformRefundListRequest {+ processor_merchant_id,+ payment_id,+ refund_id,+ profile_id,+ limit,+ offset,+ time_range,+ start_amount,+ end_amount,+ connector,+ merchant_connector_id,+ currency,+ refund_status,+ } = value;+ Self {+ payment_id,+ refund_id,+ profile_id: profile_id.map(|profile_id| vec![profile_id]),+ limit: limit.unwrap_or_default(),+ offset,+ time_range,+ amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some(+ api_models::payments::AmountFilter {+ start_amount,+ end_amount,+ },+ ),+ connector,+ merchant_connector_id,+ currency,+ refund_status,+ processor_merchant_id,+ }+ }+}+#[cfg(feature = "v2")]impl From<(api_models::refunds::RefundListRequest, Profile)> for RefundListConstraints {fn from((value, profile): (api_models::refunds::RefundListRequest, Profile)) -> Self {diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex 4d8e9d0c73..f67498a78f 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -1870,6 +1870,139 @@ pub async fn refund_list())}+#[instrument(skip_all)]+#[cfg(all(feature = "olap", feature = "v1"))]+pub async fn refund_list_for_platform(+ state: SessionState,+ platform: domain::Platform,+ req: api_models::refunds::PlatformRefundListRequest,+) -> RouterResponse<api_models::refunds::PlatformRefundListResponse> {+ common_utils::fp_utils::when(+ !platform.get_provider().get_account().is_platform_account(),+ || {+ Err(report!(errors::ApiErrorResponse::Unauthorized))+ .attach_printable("Platform refunds list is only accessible to platform merchants")+ },+ )?;++ let db = state.store;+ let limit = req.limit.unwrap_or_default();+ let offset = req.offset;+ let platform_merchant_id = platform.get_provider().get_account().get_id();+ let refund_constraints: hyperswitch_domain_models::refunds::RefundListConstraints = req.into();++ let refund_list = db+ .filter_refund_by_platform_merchant_id(+ platform_merchant_id,+ &refund_constraints,+ limit,+ offset,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;++ let data: Vec<api_models::refunds::PlatformRefundListItem> = refund_list+ .into_iter()+ .map(ForeignFrom::foreign_from)+ .collect();++ let total_count = db+ .get_total_count_of_refunds_for_platform(platform_merchant_id, &refund_constraints)+ .await+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;++ Ok(services::ApplicationResponse::Json(+ api_models::refunds::PlatformRefundListResponse {+ count: data.len(),+ total_count,+ data,+ },+ ))+}++#[instrument(skip_all)]+#[cfg(all(feature = "olap", feature = "v1"))]+pub async fn get_platform_refund_filters(+ state: SessionState,+ platform: domain::Platform,+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,+) -> RouterResponse<api_models::refunds::PlatformRefundListFilters> {+ common_utils::fp_utils::when(+ !platform.get_provider().get_account().is_platform_account(),+ || {+ Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(+ "Platform refund filters are only accessible to platform merchants",+ )+ },+ )?;++ let db = state.store.as_ref();++ let merchant_accounts = db+ .list_merchant_accounts_by_organization_id(+ platform.get_provider().get_account().get_org_id(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;++ let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();++ for connected_account in merchant_accounts.into_iter().filter(|account| {+ account.merchant_account_type == common_enums::MerchantAccountType::Connected+ }) {+ let merchant_id = connected_account.get_id().clone();+ let key_store = db+ .get_merchant_key_store_by_merchant_id(+ &merchant_id,+ &db.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;++ let processor = domain::Platform::new(+ connected_account.clone(),+ key_store.clone(),+ connected_account,+ key_store,+ None,+ )+ .get_processor()+ .clone();++ let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =+ super::admin::list_payment_connectors(state.clone(), processor, profile_id_list.clone())+ .await?+ {+ data+ } else {+ return Err(errors::ApiErrorResponse::InternalServerError.into());+ };++ merchant_connector_accounts+ .into_iter()+ .filter_map(|merchant_connector_account| {+ merchant_connector_account+ .connector_label+ .clone()+ .map(|label| {+ let info = merchant_connector_account.to_merchant_connector_info(&label);+ (merchant_connector_account.connector_name, info)+ })+ })+ .for_each(|(connector_name, info)| {+ connector_map.entry(connector_name).or_default().push(info);+ });+ }++ Ok(services::ApplicationResponse::Json(+ api_models::refunds::PlatformRefundListFilters {+ connector: connector_map,+ currency: enums::Currency::iter().collect(),+ refund_status: enums::RefundStatus::iter().collect(),+ },+ ))+}+#[instrument(skip_all)]#[cfg(feature = "olap")]pub async fn refund_filter_list(@@ -2131,6 +2264,35 @@ impl ForeignFrom<diesel_refund::Refund> for api::RefundResponse {}}+#[cfg(all(feature = "olap", feature = "v1"))]+impl ForeignFrom<diesel_refund::Refund> for api_models::refunds::PlatformRefundListItem {+ fn foreign_from(refund: diesel_refund::Refund) -> Self {+ Self {+ refund_id: refund.refund_id,+ payment_id: refund.payment_id,+ merchant_id: refund.merchant_id,+ processor_merchant_id: refund.processor_merchant_id,+ profile_id: refund.profile_id,+ connector: refund.connector,+ merchant_connector_id: refund.merchant_connector_id,+ connector_refund_id: refund+ .connector_refund_id+ .as_ref()+ .map(ConnectorTransactionId::get_id)+ .map(ToOwned::to_owned),+ attempt_id: refund.attempt_id,+ refund_amount: refund.refund_amount,+ total_amount: refund.total_amount,+ currency: refund.currency,+ refund_status: refund.refund_status,+ refund_reason: refund.refund_reason,+ description: refund.description,+ created_at: refund.created_at,+ modified_at: refund.modified_at,+ }+ }+}+implForeignFrom<(diesel_refund::Refund,diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 012309e1ab..833358fed7 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -3217,6 +3217,35 @@ impl RefundInterface for KafkaStore {.await}+ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn filter_refund_by_platform_merchant_id(+ &self,+ platform_merchant_id: &id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ limit: diesel_models::list::PageSize,+ offset: diesel_models::list::PageOffset,+ ) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {+ self.diesel_store+ .filter_refund_by_platform_merchant_id(+ platform_merchant_id,+ refund_details,+ limit,+ offset,+ )+ .await+ }++ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn get_total_count_of_refunds_for_platform(+ &self,+ platform_merchant_id: &id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::StorageError> {+ self.diesel_store+ .get_total_count_of_refunds_for_platform(platform_merchant_id, refund_details)+ .await+ }+#[cfg(all(feature = "v1", feature = "olap"))]async fn filter_refund_by_meta_constraints(&self,diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rsindex 474350b7ed..6c940eea4a 100644--- a/crates/router/src/db/refund.rs+++ b/crates/router/src/db/refund.rs@@ -97,6 +97,22 @@ pub trait RefundInterface {offset: diesel_models::list::PageOffset,) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;+ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn filter_refund_by_platform_merchant_id(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ limit: diesel_models::list::PageSize,+ offset: diesel_models::list::PageOffset,+ ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;++ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn get_total_count_of_refunds_for_platform(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::StorageError>;+#[cfg(all(feature = "v1", feature = "olap"))]async fn filter_refund_by_meta_constraints(&self,@@ -416,6 +432,44 @@ mod storage {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[cfg(all(feature = "v1", feature = "olap"))]+ #[instrument(skip_all)]+ async fn filter_refund_by_platform_merchant_id(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ limit: diesel_models::list::PageSize,+ offset: diesel_models::list::PageOffset,+ ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_platform_constraints(+ &conn,+ platform_merchant_id,+ refund_details,+ limit,+ offset,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[cfg(all(feature = "v1", feature = "olap"))]+ #[instrument(skip_all)]+ async fn get_total_count_of_refunds_for_platform(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_platform_refunds_count(+ &conn,+ platform_merchant_id,+ refund_details,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[cfg(all(feature = "v1", feature = "olap"))]#[instrument(skip_all)]async fn filter_refund_by_meta_constraints(@@ -1240,6 +1294,44 @@ mod storage {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[cfg(all(feature = "v1", feature = "olap"))]+ #[instrument(skip_all)]+ async fn filter_refund_by_platform_merchant_id(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ limit: diesel_models::list::PageSize,+ offset: diesel_models::list::PageOffset,+ ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_platform_constraints(+ &conn,+ platform_merchant_id,+ refund_details,+ limit,+ offset,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[cfg(all(feature = "v1", feature = "olap"))]+ #[instrument(skip_all)]+ async fn get_total_count_of_refunds_for_platform(+ &self,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_platform_refunds_count(+ &conn,+ platform_merchant_id,+ refund_details,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[cfg(all(feature = "v1", feature = "olap"))]#[instrument(skip_all)]async fn filter_refund_by_meta_constraints(@@ -1849,6 +1941,26 @@ impl RefundInterface for MockDb {Ok(filtered_refunds)}+ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn filter_refund_by_platform_merchant_id(+ &self,+ _platform_merchant_id: &common_utils::id_type::MerchantId,+ _refund_details: &refunds::RefundListConstraints,+ _limit: diesel_models::list::PageSize,+ _offset: diesel_models::list::PageOffset,+ ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }++ #[cfg(all(feature = "v1", feature = "olap"))]+ async fn get_total_count_of_refunds_for_platform(+ &self,+ _platform_merchant_id: &common_utils::id_type::MerchantId,+ _refund_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+#[cfg(all(feature = "v1", feature = "olap"))]async fn filter_refund_by_meta_constraints(&self,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex a0e89aec16..733d9b7867 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1568,6 +1568,13 @@ impl Refunds {{route = route.service(web::resource("/list").route(web::post().to(refunds_list)))+ .service(+ web::resource("/platform/list").route(web::get().to(refunds_list_for_platform)),+ )+ .service(+ web::resource("/platform/filter")+ .route(web::get().to(refunds_filter_list_for_platform)),+ ).service(web::resource("/profile/list").route(web::post().to(refunds_list_profile))).service(web::resource("/filter").route(web::post().to(refunds_filter_list))).service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters)))diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 45e7cc6359..5319861bc6 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -229,6 +229,8 @@ impl From<Flow> for ApiIdentifier {| Flow::RefundsUpdate| Flow::RefundsReverse| Flow::RefundsList+ | Flow::PlatformRefundsList+ | Flow::PlatformRefundsFilters| Flow::RefundsFilters| Flow::RefundsAggregate| Flow::RefundsManualUpdate => Self::Refunds,diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rsindex 74d8958f79..a0972b1ac2 100644--- a/crates/router/src/routes/refunds.rs+++ b/crates/router/src/routes/refunds.rs@@ -518,6 +518,77 @@ pub async fn refunds_list(.await}+#[cfg(all(feature = "v1", feature = "olap"))]+/// Refunds - Platform List+///+/// To list the refunds across all connected merchants under a platform org+#[instrument(skip_all, fields(flow = ?Flow::PlatformRefundsList))]+pub async fn refunds_list_for_platform(+ state: web::Data<AppState>,+ req: HttpRequest,+ payload: web::Query<api_models::refunds::PlatformRefundListRequest>,+) -> HttpResponse {+ let flow = Flow::PlatformRefundsList;+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload.into_inner(),+ |state, auth: auth::AuthenticationData, req, _| {+ refund_list_for_platform(state, auth.platform, req)+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: false,+ allow_platform_self_operation: true,+ }),+ &auth::JWTAuth {+ permission: Permission::MerchantRefundRead,+ allow_connected: false,+ allow_platform: true,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[cfg(all(feature = "v1", feature = "olap"))]+/// Refunds - Platform Filter+///+/// To list the filters available for the refunds list across all connected merchants under a platform org+#[instrument(skip_all, fields(flow = ?Flow::PlatformRefundsFilters))]+pub async fn refunds_filter_list_for_platform(+ state: web::Data<AppState>,+ req: HttpRequest,+) -> HttpResponse {+ let flow = Flow::PlatformRefundsFilters;+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ (),+ |state, auth: auth::AuthenticationData, _, _| {+ get_platform_refund_filters(state, auth.platform, None)+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: false,+ allow_platform_self_operation: true,+ }),+ &auth::JWTAuth {+ permission: Permission::MerchantRefundRead,+ allow_connected: false,+ allow_platform: true,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(all(feature = "v1", feature = "olap"))]/// Refunds - List at profile level///diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rsindex 29b53d97fc..4d749b0beb 100644--- a/crates/router/src/types/storage/refund.rs+++ b/crates/router/src/types/storage/refund.rs@@ -38,6 +38,22 @@ pub trait RefundDbExt: Sized {offset: PageOffset,) -> CustomResult<Vec<Self>, errors::DatabaseError>;+ #[cfg(feature = "v1")]+ async fn filter_by_platform_constraints(+ conn: &DatabaseConnectionWithContext<'_>,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_list_details: &refunds::RefundListConstraints,+ limit: PageSize,+ offset: PageOffset,+ ) -> CustomResult<Vec<Self>, errors::DatabaseError>;++ #[cfg(feature = "v1")]+ async fn get_platform_refunds_count(+ conn: &DatabaseConnectionWithContext<'_>,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_list_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::DatabaseError>;+#[cfg(feature = "v1")]async fn filter_by_meta_constraints(conn: &DatabaseConnectionWithContext<'_>,@@ -170,6 +186,168 @@ impl RefundDbExt for Refund {.attach_printable_lazy(|| "Error filtering records by predicate")}+ #[cfg(feature = "v1")]+ async fn filter_by_platform_constraints(+ conn: &DatabaseConnectionWithContext<'_>,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_list_details: &refunds::RefundListConstraints,+ limit: PageSize,+ offset: PageOffset,+ ) -> CustomResult<Vec<Self>, errors::DatabaseError> {+ let mut filter = diesel_models::boxed_list_query!(+ Refund,+ scope = dsl::merchant_id.eq(platform_merchant_id.to_owned()),+ order = dsl::modified_at.desc()+ );++ if let Some(processor_merchant_id) = &refund_list_details.processor_merchant_id {+ filter = filter.filter(dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()));+ }++ if let Some(payment_id) = &refund_list_details.payment_id {+ filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));+ }++ if let Some(refund_id) = &refund_list_details.refund_id {+ filter = filter.filter(dsl::refund_id.eq(refund_id.to_owned()));+ }++ if let Some(profile_id) = &refund_list_details.profile_id {+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));+ }++ if let Some(time_range) = refund_list_details.time_range {+ filter = filter.filter(dsl::created_at.ge(time_range.start_time));++ if let Some(end_time) = time_range.end_time {+ filter = filter.filter(dsl::created_at.le(end_time));+ }+ }++ filter = match refund_list_details.amount_filter {+ Some(AmountFilter {+ start_amount: Some(start),+ end_amount: Some(end),+ }) => filter.filter(dsl::refund_amount.between(start, end)),+ Some(AmountFilter {+ start_amount: Some(start),+ end_amount: None,+ }) => filter.filter(dsl::refund_amount.ge(start)),+ Some(AmountFilter {+ start_amount: None,+ end_amount: Some(end),+ }) => filter.filter(dsl::refund_amount.le(end)),+ _ => filter,+ };++ if let Some(connector) = refund_list_details.connector.clone() {+ filter = filter.filter(dsl::connector.eq_any(connector));+ }++ if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {+ filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));+ }++ if let Some(filter_currency) = &refund_list_details.currency {+ filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));+ }++ if let Some(filter_refund_status) = &refund_list_details.refund_status {+ filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));+ }++ let filter = diesel_models::list::apply_pagination(filter, limit, offset);++ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());++ db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(+ conn.request_id(),+ conn.event_emitter(),+ db_metrics::DatabaseOperation::Filter,+ filter.get_results_async(conn.raw_connection()),+ )+ .await+ .change_context(errors::DatabaseError::NotFound)+ .attach_printable_lazy(|| "Error filtering records by predicate")+ }++ #[cfg(feature = "v1")]+ async fn get_platform_refunds_count(+ conn: &DatabaseConnectionWithContext<'_>,+ platform_merchant_id: &common_utils::id_type::MerchantId,+ refund_list_details: &refunds::RefundListConstraints,+ ) -> CustomResult<i64, errors::DatabaseError> {+ let mut filter = diesel_models::list::into_boxed_list(+ <Self as HasTable>::table()+ .count()+ .filter(dsl::merchant_id.eq(platform_merchant_id.to_owned())),+ );++ if let Some(processor_merchant_id) = &refund_list_details.processor_merchant_id {+ filter = filter.filter(dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()));+ }++ if let Some(payment_id) = &refund_list_details.payment_id {+ filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));+ }++ if let Some(refund_id) = &refund_list_details.refund_id {+ filter = filter.filter(dsl::refund_id.eq(refund_id.to_owned()));+ }++ if let Some(profile_id) = &refund_list_details.profile_id {+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.to_owned()));+ }++ if let Some(time_range) = refund_list_details.time_range {+ filter = filter.filter(dsl::created_at.ge(time_range.start_time));++ if let Some(end_time) = time_range.end_time {+ filter = filter.filter(dsl::created_at.le(end_time));+ }+ }++ filter = match refund_list_details.amount_filter {+ Some(AmountFilter {+ start_amount: Some(start),+ end_amount: Some(end),+ }) => filter.filter(dsl::refund_amount.between(start, end)),+ Some(AmountFilter {+ start_amount: Some(start),+ end_amount: None,+ }) => filter.filter(dsl::refund_amount.ge(start)),+ Some(AmountFilter {+ start_amount: None,+ end_amount: Some(end),+ }) => filter.filter(dsl::refund_amount.le(end)),+ _ => filter,+ };++ if let Some(connector) = refund_list_details.connector.clone() {+ filter = filter.filter(dsl::connector.eq_any(connector));+ }++ if let Some(merchant_connector_id) = refund_list_details.merchant_connector_id.clone() {+ filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id));+ }++ if let Some(filter_currency) = &refund_list_details.currency {+ filter = filter.filter(dsl::currency.eq_any(filter_currency.clone()));+ }++ if let Some(filter_refund_status) = &refund_list_details.refund_status {+ filter = filter.filter(dsl::refund_status.eq_any(filter_refund_status.clone()));+ }++ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());++ filter+ .get_result_async::<i64>(conn.raw_connection())+ .await+ .change_context(errors::DatabaseError::NotFound)+ .attach_printable_lazy(|| "Error filtering count of platform refunds")+ }+#[cfg(feature = "v2")]async fn filter_by_constraints(conn: &DatabaseConnectionWithContext<'_>,diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 7eb73e963c..1853699928 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -275,6 +275,10 @@ pub enum Flow {RefundsReverse,/// Refunds list flow.RefundsList,+ /// Aggregated refunds list flow for a platform across its connected merchants.+ PlatformRefundsList,+ /// Aggregated refunds filter-values flow for a platform across its connected merchants.+ PlatformRefundsFilters,/// Refunds filters flowRefundsFilters,/// Refunds aggregates flow