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(revenue_recovery): revenue recovery invoices list API and get intent routes for payments (#9409)

Sagar naikfdfd3aa32fbd
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index f1de76a4f6..ca98262e75 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -4,7 +4,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use super::{
PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest,
PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest,
- RecoveryPaymentsCreate, RecoveryPaymentsResponse,
+ RecoveryPaymentListResponse, RecoveryPaymentsCreate, RecoveryPaymentsResponse,
+ RevenueRecoveryGetIntentResponse,
};
#[cfg(feature = "v2")]
use crate::payment_methods::{
@@ -258,6 +259,15 @@ impl ApiEventMetric for PaymentsIntentResponse {
}
}
+#[cfg(all(feature = "v2", feature = "olap"))]
+impl ApiEventMetric for RevenueRecoveryGetIntentResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Payment {
+ payment_id: self.id.clone(),
+ })
+ }
+}
+
#[cfg(feature = "v2")]
impl ApiEventMetric for payments::PaymentsResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -494,6 +504,13 @@ impl ApiEventMetric for RecoveryPaymentsResponse {
}
}
+#[cfg(feature = "v2")]
+impl ApiEventMetric for RecoveryPaymentListResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
+
#[cfg(feature = "v1")]
impl ApiEventMetric for PaymentListResponseV2 {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index eccce6f596..ba9f81f72b 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -703,6 +703,152 @@ pub struct PaymentsIntentResponse {
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[cfg(feature = "v2")]
+pub struct RevenueRecoveryGetIntentResponse {
+ /// Global Payment Id for the payment
+ #[schema(value_type = String)]
+ pub id: id_type::GlobalPaymentId,
+
+ /// The recovery status of the payment
+ #[schema(value_type = RecoveryStatus, example = "scheduled")]
+ pub status: common_enums::RecoveryStatus,
+
+ /// The amount details for the payment
+ pub amount_details: AmountDetailsResponse,
+
+ /// It's a token used for client side verification.
+ #[schema(value_type = String, example = "cs_0195b34da95d75239c6a4bf514458896")]
+ pub client_secret: Option<Secret<String>>,
+
+ /// The identifier for the profile. This is inferred from the `x-profile-id` header
+ #[schema(value_type = String)]
+ pub profile_id: id_type::ProfileId,
+
+ /// Unique identifier for the payment. This ensures idempotency for multiple payments
+ /// that have been done by a single merchant.
+ #[schema(
+ value_type = Option<String>,
+ min_length = 30,
+ max_length = 30,
+ example = "pay_mbabizu24mvu3mela5njyhpit4"
+ )]
+ pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
+
+ /// The routing algorithm id to be used for the payment
+ #[schema(value_type = Option<String>)]
+ pub routing_algorithm_id: Option<id_type::RoutingId>,
+
+ #[schema(value_type = CaptureMethod, example = "automatic")]
+ pub capture_method: api_enums::CaptureMethod,
+
+ /// The authentication type for the payment
+ #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")]
+ pub authentication_type: Option<api_enums::AuthenticationType>,
+
+ /// The billing details of the payment. This address will be used for invoicing.
+ #[schema(value_type = Option<Address>)]
+ pub billing: Option<Address>,
+
+ /// The shipping address for the payment
+ #[schema(value_type = Option<Address>)]
+ pub shipping: Option<Address>,
+
+ /// The identifier for the customer
+ #[schema(
+ min_length = 32,
+ max_length = 64,
+ example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
+ value_type = String
+ )]
+ pub customer_id: Option<id_type::GlobalCustomerId>,
+
+ /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
+ #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)]
+ pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
+
+ /// A description for the payment
+ #[schema(example = "It's my first payment request", value_type = Option<String>)]
+ pub description: Option<common_utils::types::Description>,
+
+ /// The URL to which you want the user to be redirected after the completion of the payment operation
+ #[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
+ pub return_url: Option<common_utils::types::Url>,
+
+ #[schema(value_type = FutureUsage, example = "off_session")]
+ pub setup_future_usage: api_enums::FutureUsage,
+
+ /// Apply MIT exemption for a payment
+ #[schema(value_type = MitExemptionRequest)]
+ pub apply_mit_exemption: common_enums::MitExemptionRequest,
+
+ /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
+ #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)]
+ pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
+
+ /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
+ #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
+ "product_name": "Apple iPhone 16",
+ "quantity": 1,
+ "amount" : 69000
+ "product_img_link" : "https://dummy-img-link.com"
+ }]"#)]
+ pub order_details: Option<Vec<OrderDetailsWithAmount>>,
+
+ /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
+ #[schema(value_type = Option<Vec<PaymentMethodType>>)]
+ pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
+ #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
+ #[schema(value_type = Option<ConnectorMetadata>)]
+ pub connector_metadata: Option<ConnectorMetadata>,
+
+ /// Additional data that might be required by hyperswitch based on the requested features by the merchants.
+ #[schema(value_type = Option<FeatureMetadata>)]
+ pub feature_metadata: Option<FeatureMetadata>,
+
+ /// Whether to generate the payment link for this payment or not (if applicable)
+ #[schema(value_type = EnablePaymentLinkRequest)]
+ pub payment_link_enabled: common_enums::EnablePaymentLinkRequest,
+
+ /// Configure a custom payment link for the particular payment
+ #[schema(value_type = Option<PaymentLinkConfigRequest>)]
+ pub payment_link_config: Option<admin::PaymentLinkConfigRequest>,
+
+ ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
+ #[schema(value_type = RequestIncrementalAuthorization)]
+ pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization,
+
+ /// Enable split payments, i.e., split the amount between multiple payment methods
+ #[schema(value_type = SplitTxnsEnabled, default = "skip")]
+ pub split_txns_enabled: common_enums::SplitTxnsEnabled,
+
+ ///Will be used to expire client secret after certain amount of time to be supplied in seconds
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub expires_on: PrimitiveDateTime,
+
+ /// Additional data related to some frm(Fraud Risk Management) connectors
+ #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
+ pub frm_metadata: Option<pii::SecretSerdeValue>,
+
+ /// Whether to perform external authentication (if applicable)
+ #[schema(value_type = External3dsAuthenticationRequest)]
+ pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
+
+ /// Allow partial authorization for this payment
+ #[schema(value_type = Option<bool>, default = false)]
+ pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
+
+ /// Number of cards/tokens attached to the connector customer in Redis
+ #[schema(value_type = u32, example = 2)]
+ pub card_attached: u32,
+}
+
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct AmountDetails {
@@ -7286,6 +7432,93 @@ pub struct PaymentsListResponseItem {
pub is_split_payment: bool,
}
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, serde::Serialize, ToSchema)]
+pub struct RecoveryPaymentsListResponseItem {
+ /// Unique identifier for the payment
+ #[schema(
+ min_length = 32,
+ max_length = 64,
+ example = "12345_pay_01926c58bc6e77c09e809964e72af8c8",
+ value_type = String,
+ )]
+ pub id: id_type::GlobalPaymentId,
+
+ /// This is an identifier for the merchant account
+ #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
+
+ /// The business profile that is associated with this payment
+ #[schema(value_type = String)]
+ pub profile_id: id_type::ProfileId,
+
+ /// The identifier for the customer
+ #[schema(
+ min_length = 32,
+ max_length = 64,
+ example = "12345_cus_01926c58bc6e77c09e809964e72af8c8",
+ value_type = Option<String>
+ )]
+ pub customer_id: Option<id_type::GlobalCustomerId>,
+
+ /// Status of the payment
+ #[schema(value_type = RecoveryStatus, example = "failed", default = "requires_confirmation")]
+ pub status: api_enums::RecoveryStatus,
+
+ /// Amount related information for this payment and attempt
+ pub amount: PaymentAmountDetailsResponse,
+
+ /// Time when the payment was created
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created: PrimitiveDateTime,
+
+ /// The payment method type for this payment attempt
+ #[schema(value_type = Option<PaymentMethod>, example = "wallet")]
+ pub payment_method_type: Option<api_enums::PaymentMethod>,
+
+ #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")]
+ pub payment_method_subtype: Option<api_enums::PaymentMethodType>,
+
+ /// The connector used for the payment
+ #[schema(value_type = Option<Connector>, example = "stripe")]
+ pub connector: Option<String>,
+
+ /// Identifier of the connector which was chosen to make the payment
+ #[schema(value_type = Option<String>)]
+ pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
+
+ /// Details of the customer
+ pub customer: Option<CustomerDetailsResponse>,
+
+ /// The reference id for the order in the merchant's system. This value can be passed by the merchant.
+ #[schema(value_type = Option<String>)]
+ pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
+
+ /// A description of the payment
+ #[schema(example = "It's my first payment request")]
+ pub description: Option<String>,
+
+ /// Total number of attempts associated with this payment
+ pub attempt_count: i16,
+
+ /// Error details for the payment if any
+ pub error: Option<ErrorDetails>,
+
+ /// If the payment was cancelled the reason will be provided here
+ pub cancellation_reason: Option<String>,
+
+ /// Date time at which payment was updated
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub modified_at: Option<PrimitiveDateTime>,
+
+ /// Date time at which payment last attempt was created
+ #[schema(example = "2022-09-10T10:11:12Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_attempt_at: Option<PrimitiveDateTime>,
+}
+
// Serialize is implemented because, this will be serialized in the api events.
// Usually request types should not have serialize implemented.
//
@@ -8145,6 +8378,18 @@ pub struct PaymentListResponse {
/// The list of payments response objects
pub data: Vec<PaymentsListResponseItem>,
}
+
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, serde::Serialize, ToSchema)]
+pub struct RecoveryPaymentListResponse {
+ /// The number of payments included in the current response
+ pub count: usize,
+ /// The total number of available payments for given constraints
+ pub total_count: i64,
+ /// The list of payments response objects
+ pub data: Vec<RecoveryPaymentsListResponseItem>,
+}
+
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema, SmithyModel)]
#[smithy(namespace = "com.hyperswitch.smithy.types")]
pub struct IncrementalAuthorizationResponse {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index e45e98b902..03373f7943 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1839,6 +1839,56 @@ impl IntentStatus {
}
}
+/// Represents the overall status of a recovery payment intent.
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ ToSchema,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumIter,
+ strum::EnumString,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum RecoveryStatus {
+ /// The payment has been successfully recovered through retry mechanisms.
+ /// This indicates that a previously failed payment has been completed.
+ Recovered,
+ /// The payment is scheduled for retry and will be processed automatically.
+ /// This status is shown when a retry is queued but not yet picked up for processing.
+ Scheduled,
+ /// The payment has exceeded the maximum retry threshold but was never picked up for processing.
+ /// This typically occurs when the payment is a hard decline that the merchant has not enabled for retry.
+ NoPicked,
+ /// The payment is currently being processed with the payment gateway.
+ /// This status is shown during active retry attempts.
+ Processing,
+ /// The payment cannot be recovered due to terminal failure conditions.
+ /// This includes cases where all retries have been exhausted or the payment has hard decline errors.
+ Terminated,
+ /// The payment is being monitored for potential recovery.
+ /// This status is shown when the attempt count is below the threshold and the system is waiting to pick it up.
+ #[default]
+ Monitoring,
+ /// The payment is queued in the calculate workflow but has not yet been scheduled for execution.
+ /// This status indicates the payment is in the initial queuing phase of the recovery process.
+ Queued,
+ /// The payment has been partially recovered through retry mechanisms.
+ /// This indicates that a partially captured payment has been processed.
+ PartiallyRecovered,
+ /// The payment is pending action from the customer, merchant, or requires additional information.
+ /// This status is shown for payments that require customer action, merchant action, payment method, confirmation, or capture.
+ Pending,
+}
+
/// Specifies how the payment method can be used for future payments.
/// - `off_session`: The payment method can be used for future payments when the customer is not present.
/// - `on_session`: The payment method is intended for use only when the customer is present during checkout.
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 080896ed82..3245cb834d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -31,6 +31,8 @@ use std::future;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
+#[cfg(feature = "v2")]
+use api_models::payments::RevenueRecoveryGetIntentResponse;
use api_models::{
self, enums,
mandates::RecurringDetails,
@@ -53,8 +55,6 @@ use hyperswitch_domain_models::payments::{
PaymentAttemptListData, PaymentCancelData, PaymentCaptureData, PaymentConfirmData,
PaymentIntentData, PaymentStatusData,
};
-#[cfg(feature = "v2")]
-use hyperswitch_domain_models::router_response_types::RedirectForm;
pub use hyperswitch_domain_models::{
mandates::MandateData,
payment_address::PaymentAddress,
@@ -113,6 +113,10 @@ use crate::core::payments::helpers::{
process_through_direct, process_through_direct_with_shadow_unified_connector_service,
process_through_ucs,
};
+#[cfg(feature = "v2")]
+use crate::core::revenue_recovery::get_workflow_entries;
+#[cfg(feature = "v2")]
+use crate::core::revenue_recovery::map_to_recovery_payment_item;
#[cfg(feature = "v1")]
use crate::core::routing::helpers as routing_helpers;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
@@ -2637,6 +2641,101 @@ where
)
}
+#[cfg(all(feature = "v2", feature = "olap"))]
+#[allow(clippy::too_many_arguments)]
+pub async fn revenue_recovery_get_intent_core(
+ state: SessionState,
+ req_state: ReqState,
+ platform: domain::Platform,
+ profile: domain::Profile,
+ request: api_models::payments::PaymentsGetIntentRequest,
+ global_payment_id: id_type::GlobalPaymentId,
+ header_payload: HeaderPayload,
+) -> RouterResponse<RevenueRecoveryGetIntentResponse> {
+ use hyperswitch_domain_models::payments::PaymentIntentData;
+
+ use crate::{
+ core::revenue_recovery::{get_workflow_entries, map_recovery_status},
+ types::storage::revenue_recovery_redis_operation::RedisTokenManager,
+ };
+
+ // Get payment intent using the existing operation
+ let (payment_data, _req, customer) = Box::pin(payments_intent_operation_core::<
+ api::PaymentGetIntent,
+ _,
+ _,
+ PaymentIntentData<api::PaymentGetIntent>,
+ >(
+ &state,
+ req_state,
+ platform.clone(),
+ profile.clone(),
+ operations::PaymentGetIntent,
+ request.clone(),
+ global_payment_id.clone(),
+ header_payload.clone(),
+ ))
+ .await?;
+
+ let payment_intent = payment_data.get_payment_intent();
+
+ // Get workflow entries to determine recovery status
+ let (calculate_workflow, execute_workflow) = get_workflow_entries(&state, &payment_intent.id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch workflow entries")?;
+
+ // Get billing connector account to get retry threshold
+ let billing_mca_id = payment_intent.get_billing_merchant_connector_account_id();
+ let max_retry_threshold = if let Some(billing_mca_id) = billing_mca_id {
+ state
+ .store
+ .find_merchant_connector_account_by_id(
+ &billing_mca_id,
+ platform.get_processor().get_key_store(),
+ )
+ .await
+ .ok()
+ .and_then(|mca| mca.get_retry_threshold())
+ .unwrap_or(0)
+ } else {
+ 0
+ };
+
+ // Map recovery status
+ let recovery_status = map_recovery_status(
+ payment_intent.status,
+ calculate_workflow.as_ref(),
+ execute_workflow.as_ref(),
+ payment_intent.attempt_count,
+ max_retry_threshold.try_into().unwrap_or(0),
+ );
+
+ // Get card_attached count from Redis
+ let card_attached = if let Some(connector_customer_id) =
+ payment_intent.get_connector_customer_id_from_feature_metadata()
+ {
+ RedisTokenManager::get_connector_customer_payment_processor_tokens(
+ &state,
+ &connector_customer_id,
+ )
+ .await
+ .ok()
+ .and_then(|tokens| tokens.len().try_into().ok())
+ .unwrap_or(0)
+ } else {
+ 0
+ };
+
+ let response = transformers::generate_revenue_recovery_get_intent_response(
+ payment_data,
+ recovery_status,
+ card_attached,
+ );
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_get_intent_using_merchant_reference(
@@ -8298,6 +8397,147 @@ pub async fn list_payments(
.await
}
+#[cfg(all(feature = "v2", feature = "olap"))]
+pub async fn revenue_recovery_list_payments(
+ state: SessionState,
+ platform: domain::Platform,
+ constraints: api::PaymentListConstraints,
+) -> RouterResponse<payments_api::RecoveryPaymentListResponse> {
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ let limit = &constraints.limit;
+ helpers::validate_payment_list_request_for_joins(*limit)?;
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let fetch_constraints = constraints.clone().into();
+ let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
+ .get_filtered_payment_intents_attempt(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ // Get all billing connector account IDs
+ let billing_connector_ids: Vec<_> = list
+ .iter()
+ .map(|(payment_intent, _)| {
+ payment_intent.get_billing_merchant_connector_account_id()
+ })
+ .collect();
+
+ // Create futures for workflow lookups
+ let workflow_futures: Vec<_> = list
+ .iter()
+ .map(|(payment_intent, _)| get_workflow_entries(&state, &payment_intent.id))
+ .collect();
+
+ let billing_connector_futures: Vec<_> = billing_connector_ids
+ .into_iter()
+ .map(|billing_mca_id| {
+ let platform_clone = platform.clone(); // Clone for each future
+ async move {
+ if let Some(billing_mca_id) = billing_mca_id {
+ db.find_merchant_connector_account_by_id(
+ &billing_mca_id,
+ platform_clone.get_processor().get_key_store(),
+ )
+ .await
+ .ok()
+ } else {
+ None
+ }
+ }
+ })
+ .collect();
+
+ let workflow_results = join_all(workflow_futures).await;
+ let billing_connector_results = join_all(billing_connector_futures).await;
+
+ let data: Vec<api_models::payments::RecoveryPaymentsListResponseItem> = list
+ .into_iter()
+ .zip(workflow_results.into_iter())
+ .zip(billing_connector_results.into_iter())
+ .map(
+ |(
+ ((payment_intent, payment_attempt), workflow_result),
+ billing_connector_account,
+ )| {
+ let (calculate_workflow, execute_workflow) =
+ workflow_result.unwrap_or((None, None));
+
+ // Get retry threshold from billing connector account
+ let max_retry_threshold = billing_connector_account
+ .as_ref()
+ .and_then(|mca| mca.get_retry_threshold())
+ .unwrap_or(0); // Default fallback
+
+ // Use custom mapping function
+ map_to_recovery_payment_item(
+ payment_intent,
+ payment_attempt,
+ calculate_workflow,
+ execute_workflow,
+ max_retry_threshold.try_into().unwrap_or(0),
+ )
+ },
+ )
+ .collect();
+
+ let active_attempt_ids = db
+ .get_filtered_active_attempt_ids_for_total_count(
+ platform.get_processor().get_account().get_id(),
+ &fetch_constraints,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving active_attempt_ids for merchant")?;
+
+ let total_count = if constraints.has_no_attempt_filters() {
+ i64::try_from(active_attempt_ids.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i64")
+ } else {
+ let active_attempt_ids = active_attempt_ids
+ .into_iter()
+ .flatten()
+ .collect::<Vec<String>>();
+
+ db.get_total_count_of_filtered_payment_attempts(
+ platform.get_processor().get_account().get_id(),
+ &active_attempt_ids,
+ constraints.connector,
+ constraints.payment_method_type,
+ constraints.payment_method_subtype,
+ constraints.authentication_type,
+ constraints.merchant_connector_id,
+ constraints.card_network,
+ platform.get_processor().get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while retrieving total count of payment attempts")
+ }?;
+
+ Ok(services::ApplicationResponse::Json(
+ api_models::payments::RecoveryPaymentListResponse {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
+ },
+ &metrics::PAYMENT_LIST_LATENCY,
+ router_env::metric_attributes!((
+ "merchant_id",
+ platform.get_processor().get_account().get_id().clone()
+ )),
+ )
+ .await
+}
+
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn apply_filters_on_payments(
state: SessionState,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 6542da6b82..25063afe1d 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2,6 +2,8 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr};
#[cfg(feature = "v2")]
use api_models::enums as api_enums;
+#[cfg(feature = "v2")]
+use api_models::payments::RevenueRecoveryGetIntentResponse;
use api_models::payments::{
Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,
MandateIds, NetworkDetails, RequestSurchargeDetails,
@@ -2167,6 +2169,77 @@ where
) -> RouterResponse<Self>;
}
+#[cfg(all(feature = "v2", feature = "olap"))]
+pub fn generate_revenue_recovery_get_intent_response<F, D>(
+ payment_data: D,
+ recovery_status: common_enums::RecoveryStatus,
+ card_attached: u32,
+) -> RevenueRecoveryGetIntentResponse
+where
+ F: Clone,
+ D: OperationSessionGetters<F>,
+{
+ let payment_intent = payment_data.get_payment_intent();
+ let client_secret = payment_data.get_client_secret();
+
+ RevenueRecoveryGetIntentResponse {
+ id: payment_intent.id.clone(),
+ profile_id: payment_intent.profile_id.clone(),
+ status: recovery_status, // Note: field is named 'status' not 'recovery_status'
+ amount_details: api_models::payments::AmountDetailsResponse::foreign_from(
+ payment_intent.amount_details.clone(),
+ ),
+ client_secret: client_secret.clone(),
+ merchant_reference_id: payment_intent.merchant_reference_id.clone(),
+ routing_algorithm_id: payment_intent.routing_algorithm_id.clone(),
+ capture_method: payment_intent.capture_method,
+ authentication_type: payment_intent.authentication_type,
+ billing: payment_intent
+ .billing_address
+ .clone()
+ .map(|billing| billing.into_inner())
+ .map(From::from),
+ shipping: payment_intent
+ .shipping_address
+ .clone()
+ .map(|shipping| shipping.into_inner())
+ .map(From::from),
+ customer_id: payment_intent.customer_id.clone(),
+ customer_present: payment_intent.customer_present,
+ description: payment_intent.description.clone(),
+ return_url: payment_intent.return_url.clone(),
+ setup_future_usage: payment_intent.setup_future_usage,
+ apply_mit_exemption: payment_intent.apply_mit_exemption,
+ statement_descriptor: payment_intent.statement_descriptor.clone(),
+ order_details: payment_intent.order_details.clone().map(|order_details| {
+ order_details
+ .into_iter()
+ .map(|order_detail| order_detail.expose().convert_back())
+ .collect()
+ }),
+ allowed_payment_method_types: payment_intent.allowed_payment_method_types.clone(),
+ metadata: payment_intent.metadata.clone(),
+ connector_metadata: payment_intent.connector_metadata.clone(),
+ feature_metadata: payment_intent
+ .feature_metadata
+ .clone()
+ .map(|feature_metadata| feature_metadata.convert_back()),
+ payment_link_enabled: payment_intent.enable_payment_link,
+ payment_link_config: payment_intent
+ .payment_link_config
+ .clone()
+ .map(ForeignFrom::foreign_from),
+ request_incremental_authorization: payment_intent.request_incremental_authorization,
+ split_txns_enabled: payment_intent.split_txns_enabled,
+ expires_on: payment_intent.session_expiry,
+ frm_metadata: payment_intent.frm_metadata.clone(),
+ request_external_three_ds_authentication: payment_intent
+ .request_external_three_ds_authentication,
+ enable_partial_authorization: payment_intent.enable_partial_authorization,
+ card_attached,
+ }
+}
+
/// Generate a response from the given Data. This should be implemented on a payment data object
pub trait GenerateResponse<Response>
where
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index e92c4900d7..4c5a67d20d 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -5,15 +5,20 @@ use std::marker::PhantomData;
use api_models::{
enums,
- payments::{self as api_payments, PaymentsGetIntentRequest, PaymentsResponse},
+ payments::{
+ self as api_payments, PaymentsGetIntentRequest, PaymentsResponse,
+ RecoveryPaymentsListResponseItem,
+ },
process_tracker::revenue_recovery,
webhooks,
};
+use common_enums::enums::{IntentStatus, RecoveryStatus};
use common_utils::{
self,
errors::CustomResult,
ext_traits::{AsyncExt, OptionExt, ValueExt},
id_type,
+ id_type::GlobalPaymentId,
};
use diesel_models::{enums as diesel_enum, process_tracker::business_status};
use error_stack::{self, report, ResultExt};
@@ -42,7 +47,9 @@ use crate::{
services::ApplicationResponse,
types::{
api as router_api_types, domain,
- storage::{self, revenue_recovery as pcr},
+ storage::{
+ self, revenue_recovery as pcr, PaymentAttempt, ProcessTracker as ProcessTrackerStorage,
+ },
transformers::{ForeignFrom, ForeignInto},
},
workflows::revenue_recovery as revenue_recovery_workflow,
@@ -51,6 +58,8 @@ pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW";
pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW";
pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW";
+use common_enums::enums::ProcessTrackerStatus;
+
#[allow(clippy::too_many_arguments)]
pub async fn upsert_calculate_pcr_task(
billing_connector_account: &domain::MerchantConnectorAccount,
@@ -218,7 +227,7 @@ pub async fn record_internal_attempt_and_execute_payment(
Err(err) => {
logger::error!("Error while recording attempt: {:?}", err);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
- status: enums::ProcessTrackerStatus::Pending,
+ status: ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
@@ -391,7 +400,7 @@ pub async fn perform_execute_payment(
enums::TriggeredBy::Internal => {
// requeue the current tasks to update the fields for rescheduling a payment
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
- status: enums::ProcessTrackerStatus::Pending,
+ status: ProcessTrackerStatus::Pending,
business_status: Some(String::from(
business_status::EXECUTE_WORKFLOW_REQUEUE,
)),
@@ -430,7 +439,7 @@ async fn insert_psync_pcr_task_to_pt(
billing_mca_id: id_type::MerchantConnectorAccountId,
db: &dyn StorageInterface,
merchant_id: id_type::MerchantId,
- payment_id: id_type::GlobalPaymentId,
+ payment_id: GlobalPaymentId,
profile_id: id_type::ProfileId,
payment_attempt_id: id_type::GlobalAttemptId,
runner: storage::ProcessTrackerRunner,
@@ -811,7 +820,7 @@ async fn update_calculate_job_schedule_time(
schedule_time: Some(new_schedule_time),
tracking_data: Some(tracking_data),
business_status: Some(String::from(business_status::PENDING)),
- status: Some(common_enums::ProcessTrackerStatus::Pending),
+ status: Some(ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
@@ -905,7 +914,7 @@ async fn insert_execute_pcr_task_to_pt(
schedule_time: Some(schedule_time),
tracking_data: Some(tracking_data_json),
business_status: Some(String::from(business_status::PENDING)),
- status: Some(enums::ProcessTrackerStatus::Pending),
+ status: Some(ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
@@ -1011,7 +1020,7 @@ async fn insert_execute_pcr_task_to_pt(
pub async fn retrieve_revenue_recovery_process_tracker(
state: SessionState,
- id: id_type::GlobalPaymentId,
+ id: GlobalPaymentId,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
let db = &*state.store;
let task = EXECUTE_WORKFLOW;
@@ -1065,7 +1074,7 @@ pub async fn retrieve_revenue_recovery_process_tracker(
pub async fn resume_revenue_recovery_process_tracker(
state: SessionState,
- id: id_type::GlobalPaymentId,
+ id: GlobalPaymentId,
request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
let db = &*state.store;
@@ -1128,7 +1137,7 @@ pub async fn resume_revenue_recovery_process_tracker(
.attach_printable("Unexpected response from payments core")?;
match response.status {
- enums::IntentStatus::Failed => {
+ IntentStatus::Failed => {
let pt_update = storage::ProcessTrackerUpdate::Update {
name: process_tracker.name.clone(),
tracking_data: Some(process_tracker.tracking_data.clone()),
@@ -1156,27 +1165,27 @@ pub async fn resume_revenue_recovery_process_tracker(
};
Ok(ApplicationResponse::Json(response))
}
- enums::IntentStatus::Succeeded
- | enums::IntentStatus::Cancelled
- | enums::IntentStatus::CancelledPostCapture
- | enums::IntentStatus::Processing
- | enums::IntentStatus::RequiresCustomerAction
- | enums::IntentStatus::RequiresMerchantAction
- | enums::IntentStatus::RequiresPaymentMethod
- | enums::IntentStatus::RequiresConfirmation
- | enums::IntentStatus::RequiresCapture
- | enums::IntentStatus::PartiallyCaptured
- | enums::IntentStatus::PartiallyCapturedAndCapturable
- | enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
- | enums::IntentStatus::Conflicted
- | enums::IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported {
+ IntentStatus::Succeeded
+ | IntentStatus::Cancelled
+ | IntentStatus::CancelledPostCapture
+ | IntentStatus::Processing
+ | IntentStatus::RequiresCustomerAction
+ | IntentStatus::RequiresMerchantAction
+ | IntentStatus::RequiresPaymentMethod
+ | IntentStatus::RequiresConfirmation
+ | IntentStatus::RequiresCapture
+ | IntentStatus::PartiallyCaptured
+ | IntentStatus::PartiallyCapturedAndCapturable
+ | IntentStatus::PartiallyAuthorizedAndRequiresCapture
+ | IntentStatus::Conflicted
+ | IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Invalid Payment Status ".to_owned(),
})),
}
}
pub async fn get_payment_response_using_payment_get_operation(
state: &SessionState,
- payment_intent_id: &id_type::GlobalPaymentId,
+ payment_intent_id: &GlobalPaymentId,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
platform: &domain::Platform,
active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
@@ -1258,3 +1267,229 @@ pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_t
None => Ok(None),
}
}
+
+pub async fn get_workflow_entries(
+ state: &SessionState,
+ payment_id: &GlobalPaymentId,
+) -> RouterResult<(Option<ProcessTrackerStorage>, Option<ProcessTrackerStorage>)> {
+ let db = &state.store;
+ let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
+
+ // Get calculate workflow entry
+ let calculate_task = CALCULATE_WORKFLOW;
+ let calculate_process_tracker_id =
+ format!("{runner}_{calculate_task}_{}", payment_id.get_string_repr());
+
+ let calculate_workflow = db
+ .as_scheduler()
+ .find_process_by_id(&calculate_process_tracker_id)
+ .await
+ .ok()
+ .flatten();
+
+ // Get execute workflow entry
+ let execute_task = EXECUTE_WORKFLOW;
+ let execute_process_tracker_id =
+ payment_id.get_execute_revenue_recovery_id(execute_task, runner);
+
+ let execute_workflow = db
+ .as_scheduler()
+ .find_process_by_id(&execute_process_tracker_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to fetch execute workflow entry for payment_id: {}",
+ payment_id.get_string_repr()
+ ))?;
+
+ Ok((calculate_workflow, execute_workflow))
+}
+
+fn determine_recovery_status_from_workflows(
+ calculate_business_status: Option<String>,
+ calculate_process_tracker_status: Option<String>,
+ execute_business_status: Option<String>,
+ execute_process_tracker_status: Option<String>,
+ default_fallback: impl FnOnce() -> RecoveryStatus,
+) -> RecoveryStatus {
+ match (
+ calculate_business_status,
+ calculate_process_tracker_status,
+ execute_business_status,
+ execute_process_tracker_status,
+ ) {
+ // Queued status conditions
+ (Some(cal_biz_status), Some(cal_pt_status), _, _)
+ if (cal_biz_status == business_status::PENDING
+ && (cal_pt_status
+ == ProcessTrackerStatus::Processing.to_string().to_uppercase()
+ || cal_pt_status
+ == ProcessTrackerStatus::Pending.to_string().to_uppercase())) =>
+ {
+ RecoveryStatus::Queued
+ }
+
+ // Scheduled status conditions
+ (Some(cal_biz_status), Some(cal_pt_status), Some(exe_biz_status), Some(exe_pt_status))
+ if (cal_biz_status == business_status::CALCULATE_WORKFLOW_SCHEDULED
+ && cal_pt_status == ProcessTrackerStatus::Finish.to_string().to_uppercase())
+ || (exe_biz_status == business_status::PENDING
+ && exe_pt_status == ProcessTrackerStatus::New.to_string().to_uppercase())
+ || (exe_biz_status == business_status::PENDING
+ && exe_pt_status
+ == ProcessTrackerStatus::Pending.to_string().to_uppercase())
+ || (exe_biz_status == business_status::PENDING
+ && exe_pt_status
+ == ProcessTrackerStatus::ProcessStarted
+ .to_string()
+ .to_uppercase()) =>
+ {
+ RecoveryStatus::Scheduled
+ }
+
+ (_, _, Some(exe_biz_status), Some(exe_pt_status))
+ if (exe_biz_status == business_status::PENDING
+ && exe_pt_status
+ == ProcessTrackerStatus::Processing.to_string().to_uppercase()) =>
+ {
+ RecoveryStatus::Processing
+ }
+
+ // Terminated status conditions
+ (Some(cal_biz_status), _, _, _)
+ if cal_biz_status == business_status::CALCULATE_WORKFLOW_FINISH
+ || cal_biz_status == business_status::RETRIES_EXCEEDED
+ || cal_biz_status == business_status::FAILURE
+ || cal_biz_status == business_status::GLOBAL_FAILURE =>
+ {
+ RecoveryStatus::Terminated
+ }
+
+ // Default fallback
+ _ => default_fallback(),
+ }
+}
+
+pub fn map_recovery_status(
+ intent_status: IntentStatus,
+ calculate_workflow: Option<&ProcessTrackerStorage>,
+ execute_workflow: Option<&ProcessTrackerStorage>,
+ attempt_count: i16,
+ max_retry_threshold: i16,
+) -> RecoveryStatus {
+ let (calculate_business_status, calculate_process_tracker_status) = calculate_workflow
+ .map(|calculate| {
+ (
+ Some(calculate.business_status.clone()),
+ Some(calculate.status.to_string().to_uppercase()),
+ )
+ })
+ .unwrap_or((None, None));
+
+ let (execute_business_status, execute_process_tracker_status) = execute_workflow
+ .map(|execute| {
+ (
+ Some(execute.business_status.clone()),
+ Some(execute.status.to_string().to_uppercase()),
+ )
+ })
+ .unwrap_or((None, None));
+
+ match intent_status {
+ // Only Failed payments are eligible for recovery
+ IntentStatus::Failed => determine_recovery_status_from_workflows(
+ calculate_business_status,
+ calculate_process_tracker_status,
+ execute_business_status,
+ execute_process_tracker_status,
+ || {
+ if attempt_count > max_retry_threshold {
+ RecoveryStatus::NoPicked
+ } else {
+ RecoveryStatus::Monitoring
+ }
+ },
+ ),
+
+ IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => {
+ determine_recovery_status_from_workflows(
+ calculate_business_status,
+ calculate_process_tracker_status,
+ execute_business_status,
+ execute_process_tracker_status,
+ || RecoveryStatus::PartiallyRecovered,
+ )
+ }
+
+ // For all other intent statuses, return the mapped recovery status
+ IntentStatus::Succeeded => RecoveryStatus::Recovered,
+ IntentStatus::Processing => RecoveryStatus::Processing,
+ IntentStatus::Cancelled
+ | IntentStatus::CancelledPostCapture
+ | IntentStatus::Conflicted
+ | IntentStatus::Expired => RecoveryStatus::Terminated,
+
+ // For statuses that don't need recovery
+ IntentStatus::RequiresCustomerAction
+ | IntentStatus::RequiresMerchantAction
+ | IntentStatus::RequiresPaymentMethod
+ | IntentStatus::RequiresConfirmation
+ | IntentStatus::RequiresCapture
+ | IntentStatus::PartiallyAuthorizedAndRequiresCapture => RecoveryStatus::Pending,
+ }
+}
+
+pub fn map_to_recovery_payment_item(
+ payment_intent: PaymentIntent,
+ payment_attempt: Option<PaymentAttempt>,
+ calculate_workflow: Option<ProcessTrackerStorage>,
+ execute_workflow: Option<ProcessTrackerStorage>,
+ max_retry_threshold: i16,
+) -> RecoveryPaymentsListResponseItem {
+ // Map the recovery status
+ let recovery_status = map_recovery_status(
+ payment_intent.status,
+ calculate_workflow.as_ref(),
+ execute_workflow.as_ref(),
+ payment_intent.attempt_count,
+ max_retry_threshold,
+ );
+
+ RecoveryPaymentsListResponseItem {
+ id: payment_intent.id,
+ merchant_id: payment_intent.merchant_id,
+ profile_id: payment_intent.profile_id,
+ customer_id: payment_intent.customer_id,
+ status: recovery_status,
+ amount: api_models::payments::PaymentAmountDetailsResponse::foreign_from((
+ &payment_intent.amount_details,
+ payment_attempt.as_ref().map(|p| &p.amount_details),
+ )),
+ created: payment_intent.created_at,
+ payment_method_type: payment_attempt
+ .as_ref()
+ .and_then(|p| p.payment_method_type.into()),
+ payment_method_subtype: payment_attempt
+ .as_ref()
+ .and_then(|p| p.payment_method_subtype.into()),
+ connector: payment_attempt.as_ref().and_then(|p| p.connector.clone()),
+ merchant_connector_id: payment_attempt
+ .as_ref()
+ .and_then(|p| p.merchant_connector_id.clone()),
+ customer: None,
+ merchant_reference_id: payment_intent.merchant_reference_id,
+ description: payment_intent
+ .description
+ .map(|val| val.get_string_repr().to_string()),
+ attempt_count: payment_intent.attempt_count,
+ error: payment_attempt
+ .as_ref()
+ .and_then(|p| p.error.as_ref())
+ .map(api_models::payments::ErrorDetails::foreign_from),
+ cancellation_reason: payment_attempt
+ .as_ref()
+ .and_then(|p| p.cancellation_reason.clone()),
+ modified_at: payment_attempt.as_ref().map(|p| p.modified_at),
+ last_attempt_at: payment_attempt.as_ref().map(|p| p.created_at),
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index b3faebe6b4..4542ac35c2 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -769,6 +769,10 @@ impl Payments {
.route(web::post().to(payments::payments_create_and_confirm_intent)),
)
.service(web::resource("/list").route(web::get().to(payments::payments_list)))
+ .service(
+ web::resource("/recovery-list")
+ .route(web::get().to(payments::revenue_recovery_invoices_list)),
+ )
.service(
web::resource("/aggregate").route(web::get().to(payments::get_payments_aggregates)),
)
@@ -814,6 +818,10 @@ impl Payments {
web::resource("/get-intent")
.route(web::get().to(payments::payments_get_intent)),
)
+ .service(
+ web::resource("/get-revenue-recovery-intent")
+ .route(web::get().to(payments::revenue_recovery_get_intent)),
+ )
.service(
web::resource("/update-intent")
.route(web::put().to(payments::payments_update_intent)),
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 2c9de9b925..09c6e86c52 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -284,6 +284,65 @@ pub async fn payments_get_intent(
.await
}
+#[cfg(all(feature = "v2", feature = "olap"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
+pub async fn revenue_recovery_get_intent(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ path: web::Path<common_utils::id_type::GlobalPaymentId>,
+) -> impl Responder {
+ use api_models::payments::PaymentsGetIntentRequest;
+ use hyperswitch_domain_models::payments::PaymentIntentData;
+
+ let flow = Flow::PaymentsGetIntent;
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => {
+ return api::log_and_return_error_response(err);
+ }
+ };
+
+ let payload = PaymentsGetIntentRequest {
+ id: path.into_inner(),
+ };
+
+ let global_payment_id = payload.id.clone();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, req_state| {
+ let platform = auth.clone().into();
+ payments::revenue_recovery_get_intent_core(
+ state,
+ req_state,
+ platform,
+ auth.profile,
+ req,
+ global_payment_id.clone(),
+ header_payload.clone(),
+ )
+ },
+ auth::api_or_client_or_jwt_auth(
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ &auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Payment(
+ global_payment_id.clone(),
+ )),
+ &auth::JWTAuth {
+ permission: Permission::ProfileRevenueRecoveryRead,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentAttemptsList, payment_id,))]
pub async fn list_payment_attempts(
@@ -1671,6 +1730,38 @@ pub async fn payments_list(
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(all(feature = "olap", feature = "v2"))]
+pub async fn revenue_recovery_invoices_list(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Query<payment_types::PaymentListConstraints>,
+) -> impl Responder {
+ let flow = Flow::PaymentsList;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let platform = auth.into();
+ payments::revenue_recovery_list_payments(state, platform, req)
+ },
+ auth::auth_type(
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantPaymentRead,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v2")]
pub async fn payments_list(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,