Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(disputes): add platform disputes list and filter endpoints (#12946)

Apoorv Dixit2ebdbe58cdd6
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index f9b93d3b50..179eb7fd84 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -188,6 +188,119 @@ pub struct DisputeListFilters {
pub dispute_stage: Vec<DisputeStage>,
}
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PlatformDisputeListConstraints {
+ /// The identifier for dispute
+ pub dispute_id: Option<String>,
+ /// The payment_id against which dispute is raised
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
+ /// The connected (processor) merchant id to filter the list by.
+ /// When omitted, disputes across all connected merchants under the platform are returned.
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ /// Limit on the number of objects to return
+ #[serde(default)]
+ pub limit: common_utils::types::list::PageSize,
+ /// The starting point within a list of object
+ #[serde(default)]
+ pub offset: common_utils::types::list::PageOffset,
+ /// The identifier for business profile
+ pub profile_id: Option<common_utils::id_type::ProfileId>,
+ /// The comma separated list of status of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub dispute_status: Option<Vec<DisputeStatus>>,
+ /// The comma separated list of stages of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub dispute_stage: Option<Vec<DisputeStage>>,
+ /// Reason for the dispute
+ pub reason: Option<String>,
+ /// The comma separated list of connectors linked to disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub connector: Option<Vec<String>>,
+ /// The comma separated list of currencies of the disputes
+ #[serde(default, deserialize_with = "parse_comma_separated")]
+ pub currency: Option<Vec<Currency>>,
+ /// The merchant connector id to filter the disputes list
+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ /// 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>,
+}
+
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, Serialize)]
+pub struct PlatformDisputeListItem {
+ /// The identifier for dispute
+ pub dispute_id: String,
+ /// The identifier for payment_intent
+ pub payment_id: common_utils::id_type::PaymentId,
+ /// The identifier for payment_attempt
+ pub attempt_id: String,
+ /// 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 dispute.
+ pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,
+ /// The dispute amount
+ pub amount: StringMinorUnit,
+ /// The three-letter ISO currency code
+ pub currency: Currency,
+ /// Stage of the dispute
+ pub dispute_stage: DisputeStage,
+ /// Status of the dispute
+ pub dispute_status: DisputeStatus,
+ /// connector to which dispute is associated with
+ pub connector: String,
+ /// Status of the dispute sent by connector
+ pub connector_status: String,
+ /// Dispute id sent by connector
+ pub connector_dispute_id: String,
+ /// Reason of dispute sent by connector
+ pub connector_reason: Option<String>,
+ /// Reason code of dispute sent by connector
+ pub connector_reason_code: Option<String>,
+ /// Evidence deadline of dispute sent by connector
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub challenge_required_by: Option<PrimitiveDateTime>,
+ /// Dispute created time sent by connector
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub connector_created_at: Option<PrimitiveDateTime>,
+ /// Dispute updated time sent by connector
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub connector_updated_at: Option<PrimitiveDateTime>,
+ /// Time at which dispute is received
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: PrimitiveDateTime,
+ /// The `profile_id` associated with the dispute
+ pub profile_id: Option<common_utils::id_type::ProfileId>,
+ /// The `merchant_connector_id` of the connector / processor through which the dispute was processed
+ pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+}
+
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, Serialize)]
+pub struct PlatformDisputeListFilters {
+ /// 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<Currency>,
+ /// The list of available dispute status filters
+ pub dispute_status: Vec<DisputeStatus>,
+ /// The list of available dispute stage filters
+ pub dispute_stage: Vec<DisputeStage>,
+}
+
+#[cfg(feature = "v1")]
+#[derive(Clone, Debug, Serialize)]
+pub struct PlatformDisputeListResponse {
+ /// The number of disputes included in the current response.
+ pub count: usize,
+ /// The total number of disputes matching the given constraints (ignores limit/offset).
+ pub total_count: i64,
+ /// The list of dispute summaries across the platform's connected merchants.
+ pub data: Vec<PlatformDisputeListItem>,
+}
+
#[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct SubmitEvidenceRequest {
///Dispute Id
diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs
index 1b23029508..52ab68be0b 100644
--- a/crates/api_models/src/events/dispute.rs
+++ b/crates/api_models/src/events/dispute.rs
@@ -48,3 +48,24 @@ impl ApiEventMetric for DisputesAggregateResponse {
Some(ApiEventsType::ResourceListAPI)
}
}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for super::PlatformDisputeListConstraints {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for super::PlatformDisputeListResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for super::PlatformDisputeListFilters {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/disputes.rs b/crates/hyperswitch_domain_models/src/disputes.rs
index fac5bf12e6..36b93e2f2f 100644
--- a/crates/hyperswitch_domain_models/src/disputes.rs
+++ b/crates/hyperswitch_domain_models/src/disputes.rs
@@ -13,6 +13,7 @@ pub struct DisputeListConstraints {
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub currency: Option<Vec<common_enums::Currency>>,
pub time_range: Option<common_utils::types::TimeRange>,
+ pub processor_merchant_id: Option<Vec<common_utils::id_type::MerchantId>>,
}
impl
@@ -84,6 +85,78 @@ impl
merchant_connector_id,
currency,
time_range,
+ processor_merchant_id: None,
+ })
+ }
+}
+
+#[cfg(feature = "v1")]
+impl
+ TryFrom<(
+ api_models::disputes::PlatformDisputeListConstraints,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ )> for DisputeListConstraints
+{
+ type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
+ fn try_from(
+ (value, auth_profile_id_list): (
+ api_models::disputes::PlatformDisputeListConstraints,
+ Option<Vec<common_utils::id_type::ProfileId>>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let api_models::disputes::PlatformDisputeListConstraints {
+ dispute_id,
+ payment_id,
+ processor_merchant_id,
+ limit,
+ offset,
+ profile_id,
+ dispute_status,
+ dispute_stage,
+ reason,
+ connector,
+ currency,
+ merchant_connector_id,
+ time_range,
+ } = value;
+ let profile_id_from_request_body = profile_id;
+ let profile_id_list = match (profile_id_from_request_body, auth_profile_id_list) {
+ (None, None) => None,
+ (None, Some(auth_profile_id_list)) => Some(auth_profile_id_list),
+ (Some(profile_id_from_request_body), None) => Some(vec![profile_id_from_request_body]),
+ (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
+ let profile_id_from_request_body_is_available_in_auth_profile_id_list =
+ auth_profile_id_list.contains(&profile_id_from_request_body);
+
+ if profile_id_from_request_body_is_available_in_auth_profile_id_list {
+ Some(vec![profile_id_from_request_body])
+ } else {
+ return Err(error_stack::Report::new(
+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Access not available for the given profile_id {profile_id_from_request_body:?}",
+ ),
+ },
+ ));
+ }
+ }
+ };
+
+ Ok(Self {
+ dispute_id,
+ payment_id,
+ limit,
+ offset,
+ profile_id: profile_id_list,
+ dispute_status,
+ dispute_stage,
+ reason,
+ connector,
+ merchant_connector_id,
+ currency,
+ time_range,
+ processor_merchant_id: processor_merchant_id
+ .map(|processor_merchant_id| vec![processor_merchant_id]),
})
}
}
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index a931b70aab..eb1d30e881 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -289,6 +289,137 @@ pub async fn get_filters_for_disputes(
))
}
+#[cfg(feature = "v1")]
+#[instrument(skip(state))]
+pub async fn retrieve_disputes_list_for_platform(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ constraints: api_models::disputes::PlatformDisputeListConstraints,
+) -> RouterResponse<api_models::disputes::PlatformDisputeListResponse> {
+ common_utils::fp_utils::when(
+ !platform.get_provider().get_account().is_platform_account(),
+ || {
+ Err(error_stack::report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Platform disputes list is only accessible to platform merchants")
+ },
+ )?;
+
+ let platform_merchant_id = platform.get_provider().get_account().get_id();
+ let db = state.store.as_ref();
+
+ let dispute_list_constraints = &(constraints, profile_id_list).try_into()?;
+
+ let disputes = db
+ .find_disputes_by_constraints_for_platform(platform_merchant_id, dispute_list_constraints)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to retrieve platform disputes")?;
+
+ let total_count = db
+ .get_disputes_count_for_platform(platform_merchant_id, dispute_list_constraints)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to count platform disputes")?;
+
+ let data: Vec<api_models::disputes::PlatformDisputeListItem> = disputes
+ .into_iter()
+ .map(api_models::disputes::PlatformDisputeListItem::foreign_from)
+ .collect();
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::disputes::PlatformDisputeListResponse {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+}
+
+#[cfg(feature = "v1")]
+#[instrument(skip(state))]
+pub async fn get_platform_disputes_filters(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+) -> RouterResponse<api_models::disputes::PlatformDisputeListFilters> {
+ common_utils::fp_utils::when(
+ !platform.get_provider().get_account().is_platform_account(),
+ || {
+ Err(error_stack::report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
+ "Platform dispute 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::disputes::PlatformDisputeListFilters {
+ connector: connector_map,
+ currency: storage_enums::Currency::iter().collect(),
+ dispute_status: storage_enums::DisputeStatus::iter().collect(),
+ dispute_stage: storage_enums::DisputeStage::iter().collect(),
+ },
+ ))
+}
+
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn accept_dispute(
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 48c464b1e9..a61fc8a362 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -38,6 +38,20 @@ pub trait DisputeInterface {
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
+ #[cfg(feature = "v1")]
+ async fn find_disputes_by_constraints_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
+
+ #[cfg(feature = "v1")]
+ async fn get_disputes_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::StorageError>;
+
async fn find_disputes_by_processor_merchant_id_payment_id(
&self,
processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -194,6 +208,40 @@ mod storage_impl {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_disputes_by_constraints_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<storage_types::Dispute>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::Dispute::filter_by_constraints_for_platform(
+ &conn,
+ platform_merchant_id,
+ dispute_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn get_disputes_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::Dispute::get_disputes_count_for_platform(
+ &conn,
+ platform_merchant_id,
+ dispute_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
#[instrument(skip_all)]
async fn update_dispute(
&self,
@@ -590,6 +638,40 @@ mod storage_impl {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn find_disputes_by_constraints_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<storage_types::Dispute>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::Dispute::filter_by_constraints_for_platform(
+ &conn,
+ platform_merchant_id,
+ dispute_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[cfg(feature = "v1")]
+ #[instrument(skip_all)]
+ async fn get_disputes_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage_types::Dispute::get_disputes_count_for_platform(
+ &conn,
+ platform_merchant_id,
+ dispute_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
#[instrument(skip_all)]
async fn update_dispute(
&self,
@@ -886,6 +968,185 @@ impl DisputeInterface for MockDb {
Ok(filtered_disputes)
}
+ #[cfg(feature = "v1")]
+ async fn find_disputes_by_constraints_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
+ let locked_disputes = self.disputes.lock().await;
+ let limit_usize = dispute_constraints.limit.as_usize();
+ let offset_usize = dispute_constraints.offset.as_usize();
+ let filtered_disputes: Vec<storage::Dispute> = locked_disputes
+ .iter()
+ .filter(|dispute| {
+ dispute.merchant_id == *platform_merchant_id
+ && dispute_constraints
+ .processor_merchant_id
+ .as_ref()
+ .is_none_or(|merchant_ids| {
+ dispute
+ .processor_merchant_id
+ .as_ref()
+ .is_some_and(|id| merchant_ids.contains(id))
+ })
+ && dispute_constraints
+ .dispute_id
+ .as_ref()
+ .is_none_or(|id| &dispute.dispute_id == id)
+ && dispute_constraints
+ .payment_id
+ .as_ref()
+ .is_none_or(|id| &dispute.payment_id == id)
+ && dispute_constraints
+ .profile_id
+ .as_ref()
+ .is_none_or(|profile_ids| {
+ dispute
+ .profile_id
+ .as_ref()
+ .is_none_or(|id| profile_ids.contains(id))
+ })
+ && dispute_constraints
+ .dispute_status
+ .as_ref()
+ .is_none_or(|statuses| statuses.contains(&dispute.dispute_status))
+ && dispute_constraints
+ .dispute_stage
+ .as_ref()
+ .is_none_or(|stages| stages.contains(&dispute.dispute_stage))
+ && dispute_constraints.reason.as_ref().is_none_or(|reason| {
+ dispute
+ .connector_reason
+ .as_ref()
+ .is_none_or(|d_reason| d_reason == reason)
+ })
+ && dispute_constraints
+ .connector
+ .as_ref()
+ .is_none_or(|connectors| {
+ connectors
+ .iter()
+ .any(|connector| dispute.connector.as_str() == *connector)
+ })
+ && dispute_constraints
+ .merchant_connector_id
+ .as_ref()
+ .is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id))
+ && dispute_constraints
+ .currency
+ .as_ref()
+ .is_none_or(|currencies| {
+ currencies.iter().any(|currency| {
+ dispute
+ .dispute_currency
+ .map(|dispute_currency| &dispute_currency == currency)
+ .unwrap_or(dispute.currency.as_str() == currency.to_string())
+ })
+ })
+ && dispute_constraints.time_range.as_ref().is_none_or(|range| {
+ let dispute_time = dispute.created_at;
+ dispute_time >= range.start_time
+ && range
+ .end_time
+ .is_none_or(|end_time| dispute_time <= end_time)
+ })
+ })
+ .skip(offset_usize)
+ .take(limit_usize)
+ .cloned()
+ .collect();
+
+ Ok(filtered_disputes)
+ }
+
+ #[cfg(feature = "v1")]
+ async fn get_disputes_count_for_platform(
+ &self,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let locked_disputes = self.disputes.lock().await;
+ let count = locked_disputes
+ .iter()
+ .filter(|dispute| {
+ dispute.merchant_id == *platform_merchant_id
+ && dispute_constraints
+ .processor_merchant_id
+ .as_ref()
+ .is_none_or(|merchant_ids| {
+ dispute
+ .processor_merchant_id
+ .as_ref()
+ .is_some_and(|id| merchant_ids.contains(id))
+ })
+ && dispute_constraints
+ .dispute_id
+ .as_ref()
+ .is_none_or(|id| &dispute.dispute_id == id)
+ && dispute_constraints
+ .payment_id
+ .as_ref()
+ .is_none_or(|id| &dispute.payment_id == id)
+ && dispute_constraints
+ .profile_id
+ .as_ref()
+ .is_none_or(|profile_ids| {
+ dispute
+ .profile_id
+ .as_ref()
+ .is_none_or(|id| profile_ids.contains(id))
+ })
+ && dispute_constraints
+ .dispute_status
+ .as_ref()
+ .is_none_or(|statuses| statuses.contains(&dispute.dispute_status))
+ && dispute_constraints
+ .dispute_stage
+ .as_ref()
+ .is_none_or(|stages| stages.contains(&dispute.dispute_stage))
+ && dispute_constraints.reason.as_ref().is_none_or(|reason| {
+ dispute
+ .connector_reason
+ .as_ref()
+ .is_none_or(|d_reason| d_reason == reason)
+ })
+ && dispute_constraints
+ .connector
+ .as_ref()
+ .is_none_or(|connectors| {
+ connectors
+ .iter()
+ .any(|connector| dispute.connector.as_str() == *connector)
+ })
+ && dispute_constraints
+ .merchant_connector_id
+ .as_ref()
+ .is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id))
+ && dispute_constraints
+ .currency
+ .as_ref()
+ .is_none_or(|currencies| {
+ currencies.iter().any(|currency| {
+ dispute
+ .dispute_currency
+ .map(|dispute_currency| &dispute_currency == currency)
+ .unwrap_or(dispute.currency.as_str() == currency.to_string())
+ })
+ })
+ && dispute_constraints.time_range.as_ref().is_none_or(|range| {
+ let dispute_time = dispute.created_at;
+ dispute_time >= range.start_time
+ && range
+ .end_time
+ .is_none_or(|end_time| dispute_time <= end_time)
+ })
+ })
+ .count();
+
+ Ok(i64::try_from(count).unwrap_or(i64::MAX))
+ }
+
async fn update_dispute(
&self,
this: storage::Dispute,
@@ -1273,6 +1534,7 @@ mod tests {
dispute_stage: None,
reason: None,
time_range: None,
+ processor_merchant_id: None,
},
diesel_models::enums::MerchantStorageScheme::PostgresOnly,
)
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 833358fed7..d7aedd5c35 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -668,6 +668,28 @@ impl DisputeInterface for KafkaStore {
.await
}
+ #[cfg(feature = "v1")]
+ async fn find_disputes_by_constraints_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
+ self.diesel_store
+ .find_disputes_by_constraints_for_platform(platform_merchant_id, dispute_constraints)
+ .await
+ }
+
+ #[cfg(feature = "v1")]
+ async fn get_disputes_count_for_platform(
+ &self,
+ platform_merchant_id: &id_type::MerchantId,
+ dispute_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.diesel_store
+ .get_disputes_count_for_platform(platform_merchant_id, dispute_constraints)
+ .await
+ }
+
async fn update_dispute(
&self,
this: storage::Dispute,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 733d9b7867..418a331160 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -2489,6 +2489,14 @@ impl Disputes {
web::resource("/profile/filter")
.route(web::get().to(disputes::get_disputes_filters_profile)),
)
+ .service(
+ web::resource("/platform/list")
+ .route(web::get().to(disputes::retrieve_disputes_list_for_platform)),
+ )
+ .service(
+ web::resource("/platform/filter")
+ .route(web::get().to(disputes::get_platform_disputes_filters)),
+ )
.service(
web::resource("/accept/{dispute_id}")
.route(web::post().to(disputes::accept_dispute)),
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index a85b9a1fe7..4b702f2f81 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -167,6 +167,103 @@ pub async fn retrieve_disputes_list(
.await
}
+#[cfg(feature = "v1")]
+/// Disputes - List Disputes Across a Platform's Connected Merchants
+#[utoipa::path(
+ get,
+ path = "/disputes/platform/list",
+ params(
+ ("processor_merchant_id" = Option<String>, Query, description = "Comma separated connected merchant ids to filter by"),
+ ("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
+ ("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
+ ("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
+ ("reason" = Option<String>, Query, description = "The reason for dispute"),
+ ("connector" = Option<String>, Query, description = "The connector linked to dispute"),
+ ),
+ responses(
+ (status = 200, description = "The platform dispute list was retrieved successfully", body = PlatformDisputeListResponse),
+ (status = 401, description = "Unauthorized request")
+ ),
+ tag = "Disputes",
+ operation_id = "List Disputes for a Platform",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::PlatformDisputesList))]
+pub async fn retrieve_disputes_list_for_platform(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<dispute_models::PlatformDisputeListConstraints>,
+) -> HttpResponse {
+ let flow = Flow::PlatformDisputesList;
+ let payload = query.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ disputes::retrieve_disputes_list_for_platform(state, auth.platform, None, req)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: true,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantDisputeRead,
+ allow_connected: false,
+ allow_platform: true,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v1")]
+/// Disputes - Platform Disputes Filters
+#[utoipa::path(
+ get,
+ path = "/disputes/platform/filter",
+ responses(
+ (status = 200, description = "List of filters", body = PlatformDisputeListFilters),
+ ),
+ tag = "Disputes",
+ operation_id = "List all dispute filters for a Platform",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::PlatformDisputesFilters))]
+pub async fn get_platform_disputes_filters(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::PlatformDisputesFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ disputes::get_platform_disputes_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::MerchantDisputeRead,
+ allow_connected: false,
+ allow_platform: true,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v1")]
/// Disputes - List Disputes for The Given Business Profiles
#[utoipa::path(
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5319861bc6..8c188247bc 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -251,6 +251,8 @@ impl From<Flow> for ApiIdentifier {
Flow::DisputesRetrieve
| Flow::DisputesList
| Flow::DisputesFilters
+ | Flow::PlatformDisputesList
+ | Flow::PlatformDisputesFilters
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index a3a3461e1a..9735f8ae10 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -16,6 +16,20 @@ pub trait DisputeDbExt: Sized {
dispute_list_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
+ #[cfg(feature = "v1")]
+ async fn filter_by_constraints_for_platform(
+ conn: &DatabaseConnectionWithContext<'_>,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<Self>, errors::DatabaseError>;
+
+ #[cfg(feature = "v1")]
+ async fn get_disputes_count_for_platform(
+ conn: &DatabaseConnectionWithContext<'_>,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<i64, errors::DatabaseError>;
+
async fn get_dispute_status_with_count(
conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -115,6 +129,137 @@ impl DisputeDbExt for Dispute {
.attach_printable_lazy(|| "Error filtering records by predicate")
}
+ #[cfg(feature = "v1")]
+ async fn filter_by_constraints_for_platform(
+ conn: &DatabaseConnectionWithContext<'_>,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
+ ) -> CustomResult<Vec<Self>, errors::DatabaseError> {
+ let mut filter = diesel_models::boxed_list_query!(
+ Dispute,
+ scope = dsl::merchant_id.eq(platform_merchant_id.to_owned()),
+ order = dsl::modified_at.desc()
+ );
+
+ if let Some(processor_merchant_id) = &dispute_list_constraints.processor_merchant_id {
+ filter =
+ filter.filter(dsl::processor_merchant_id.eq_any(processor_merchant_id.clone()));
+ }
+ if let Some(payment_id) = &dispute_list_constraints.payment_id {
+ filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
+ }
+ if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
+ filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
+ }
+ if let Some(time_range) = dispute_list_constraints.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));
+ }
+ }
+ if let Some(profile_id) = &dispute_list_constraints.profile_id {
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
+ }
+ if let Some(connector_list) = &dispute_list_constraints.connector {
+ filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
+ }
+ if let Some(reason) = &dispute_list_constraints.reason {
+ filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
+ }
+ if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
+ filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
+ }
+ if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
+ filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
+ }
+ if let Some(currency_list) = &dispute_list_constraints.currency {
+ filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
+ }
+ if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
+ filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()));
+ }
+ let filter = diesel_models::list::apply_pagination(
+ filter,
+ dispute_list_constraints.limit,
+ dispute_list_constraints.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 platform dispute records")
+ }
+
+ #[cfg(feature = "v1")]
+ async fn get_disputes_count_for_platform(
+ conn: &DatabaseConnectionWithContext<'_>,
+ platform_merchant_id: &common_utils::id_type::MerchantId,
+ dispute_list_constraints: &disputes::DisputeListConstraints,
+ ) -> 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) = &dispute_list_constraints.processor_merchant_id {
+ filter =
+ filter.filter(dsl::processor_merchant_id.eq_any(processor_merchant_id.clone()));
+ }
+ if let Some(payment_id) = &dispute_list_constraints.payment_id {
+ filter = filter.filter(dsl::payment_id.eq(payment_id.to_owned()));
+ }
+ if let Some(dispute_id) = &dispute_list_constraints.dispute_id {
+ filter = filter.filter(dsl::dispute_id.eq(dispute_id.clone()));
+ }
+ if let Some(time_range) = dispute_list_constraints.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));
+ }
+ }
+ if let Some(profile_id) = &dispute_list_constraints.profile_id {
+ filter = filter.filter(dsl::profile_id.eq_any(profile_id.clone()));
+ }
+ if let Some(connector_list) = &dispute_list_constraints.connector {
+ filter = filter.filter(dsl::connector.eq_any(connector_list.clone()));
+ }
+ if let Some(reason) = &dispute_list_constraints.reason {
+ filter = filter.filter(dsl::connector_reason.eq(reason.clone()));
+ }
+ if let Some(dispute_stage) = &dispute_list_constraints.dispute_stage {
+ filter = filter.filter(dsl::dispute_stage.eq_any(dispute_stage.clone()));
+ }
+ if let Some(dispute_status) = &dispute_list_constraints.dispute_status {
+ filter = filter.filter(dsl::dispute_status.eq_any(dispute_status.clone()));
+ }
+ if let Some(currency_list) = &dispute_list_constraints.currency {
+ filter = filter.filter(dsl::dispute_currency.eq_any(currency_list.clone()));
+ }
+ if let Some(merchant_connector_id) = &dispute_list_constraints.merchant_connector_id {
+ filter = filter.filter(dsl::merchant_connector_id.eq(merchant_connector_id.clone()));
+ }
+
+ 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::Count,
+ filter.get_result_async::<i64>(conn.raw_connection()),
+ )
+ .await
+ .change_context(errors::DatabaseError::NotFound)
+ .attach_printable_lazy(|| "Error counting platform dispute records")
+ }
+
async fn get_dispute_status_with_count(
conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 492a9de661..7d18250ac9 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -761,6 +761,40 @@ impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse {
}
}
+#[cfg(feature = "v1")]
+impl ForeignFrom<storage::Dispute> for api_models::disputes::PlatformDisputeListItem {
+ fn foreign_from(dispute: storage::Dispute) -> Self {
+ Self {
+ dispute_id: dispute.dispute_id,
+ payment_id: dispute.payment_id,
+ attempt_id: dispute.attempt_id,
+ merchant_id: dispute.merchant_id,
+ processor_merchant_id: dispute.processor_merchant_id,
+ amount: dispute.amount,
+ currency: dispute.dispute_currency.unwrap_or(
+ dispute
+ .currency
+ .to_uppercase()
+ .parse_enum("Currency")
+ .unwrap_or_default(),
+ ),
+ dispute_stage: dispute.dispute_stage,
+ dispute_status: dispute.dispute_status,
+ connector: dispute.connector,
+ connector_status: dispute.connector_status,
+ connector_dispute_id: dispute.connector_dispute_id,
+ connector_reason: dispute.connector_reason,
+ connector_reason_code: dispute.connector_reason_code,
+ challenge_required_by: dispute.challenge_required_by,
+ connector_created_at: dispute.connector_created_at,
+ connector_updated_at: dispute.connector_updated_at,
+ created_at: dispute.created_at,
+ profile_id: dispute.profile_id,
+ merchant_connector_id: dispute.merchant_connector_id,
+ }
+ }
+}
+
impl ForeignFrom<storage::Authorization> for payments::IncrementalAuthorizationResponse {
fn foreign_from(authorization: storage::Authorization) -> Self {
Self {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 1853699928..ac849eb771 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -389,6 +389,10 @@ pub enum Flow {
DisputesList,
/// Dispute Filters flow
DisputesFilters,
+ /// Aggregated disputes list flow for a platform across its connected merchants.
+ PlatformDisputesList,
+ /// Aggregated disputes filter-values flow for a platform across its connected merchants.
+ PlatformDisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow