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): add cancel invoice action and cancel API for v2 (#14716)

CHALLA NISHANTH BABU2c9a35e07a83
diff --git a/api-reference/docs.json b/api-reference/docs.json
index 81797bc560..9d654ac86c 100644
--- a/api-reference/docs.json
+++ b/api-reference/docs.json
@@ -514,7 +514,8 @@
{
"group": "Revenue Recovery",
"pages": [
- "v2/revenue-recovery/revenue-recovery--create"
+ "v2/revenue-recovery/revenue-recovery--create",
+ "v2/revenue-recovery/revenue-recovery--cancel"
]
}
]
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index b1a9d80ffd..d686f33c6c 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -4977,6 +4977,75 @@
]
}
},
+ "/v2/recovery/{merchant_reference_id}/cancel": {
+ "post": {
+ "tags": [
+ "Revenue Recovery"
+ ],
+ "summary": "Revenue Recovery - Cancel",
+ "description": "Cancel the revenue recovery workflow of an invoice that is still in recovery: its scheduled\nretries are stopped and no further recovery attempts are made. A `failed` payment moves to\n`cancelled`, and a partially captured payment moves to `cancelled_post_capture`. The request\nis refused with `400` when the payment is in any other state, when a retry is in progress,\nor when recovery already reached a terminal status. The invoice is looked up by its merchant\nreference id within the business profile given in the `X-Profile-Id` header.",
+ "operationId": "Cancel a Revenue Recovery Workflow",
+ "parameters": [
+ {
+ "name": "merchant_reference_id",
+ "in": "path",
+ "description": "Merchant reference id of the invoice whose revenue recovery workflow should be cancelled",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "Unique identifier of the business profile under which the invoice is processed.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": "pro_abcdefghijklmnop"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Revenue Recovery workflow cancelled successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RecoveryPaymentsResponse"
+ },
+ "example": {
+ "id": "12_pay_01a3868d94a471219b5c4bc71638e2zc",
+ "intent_status": "cancelled",
+ "merchant_reference_id": "invoice_mbabizu24mvu3mela5njyh"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "The invoice cannot be cancelled: its payment is not failed or partially captured, a retry is in progress, or recovery already reached a terminal status",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Invoice not found"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/proxy": {
"post": {
"tags": [
diff --git a/api-reference/v2/revenue-recovery/revenue-recovery--cancel.mdx b/api-reference/v2/revenue-recovery/revenue-recovery--cancel.mdx
new file mode 100644
index 0000000000..ec2c1cc280
--- /dev/null
+++ b/api-reference/v2/revenue-recovery/revenue-recovery--cancel.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/recovery/{merchant_reference_id}/cancel
+---
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index b9da46f2d5..d706a3d5cc 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -239,6 +239,10 @@ pub mod business_status {
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED";
+ /// The invoice behind the task was cancelled, so recovery must not continue.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const CANCELLED: &str = "CANCELLED";
+
/// A revenue recovery invoice reached the end of its grace window, so there is no legitimate
/// time left to schedule a retry at — whatever retry budget remains. Distinct from
/// `RETRIES_EXCEEDED`, which is the budget itself running out.
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 48b09915d6..457afb0c09 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -179,6 +179,7 @@ Never share your secret api keys. Keep them guarded and secure.
// Routes for Revenue Recovery flow under Process Tracker
routes::revenue_recovery::revenue_recovery_pt_retrieve_api,
routes::revenue_recovery::revenue_recovery_payments_create,
+ routes::revenue_recovery::revenue_recovery_cancel,
// Routes for proxy
routes::proxy::proxy_core,
diff --git a/crates/openapi/src/routes/revenue_recovery.rs b/crates/openapi/src/routes/revenue_recovery.rs
index c68ebafe6d..66b7eef1cf 100644
--- a/crates/openapi/src/routes/revenue_recovery.rs
+++ b/crates/openapi/src/routes/revenue_recovery.rs
@@ -103,3 +103,44 @@ pub async fn revenue_recovery_pt_retrieve_api() {}
security(("api_key" = []))
)]
pub async fn revenue_recovery_payments_create() {}
+
+#[cfg(feature = "v2")]
+/// Revenue Recovery - Cancel
+///
+/// Cancel the revenue recovery workflow of an invoice that is still in recovery: its scheduled
+/// retries are stopped and no further recovery attempts are made. A `failed` payment moves to
+/// `cancelled`, and a partially captured payment moves to `cancelled_post_capture`. The request
+/// is refused with `400` when the payment is in any other state, when a retry is in progress,
+/// or when recovery already reached a terminal status. The invoice is looked up by its merchant
+/// reference id within the business profile given in the `X-Profile-Id` header.
+#[utoipa::path(
+ post,
+ path = "/v2/recovery/{merchant_reference_id}/cancel",
+ params(
+ ("merchant_reference_id" = String, Path, description = "Merchant reference id of the invoice whose revenue recovery workflow should be cancelled"),
+ (
+ "X-Profile-Id" = String, Header,
+ description = "Unique identifier of the business profile under which the invoice is processed.",
+ example = "pro_abcdefghijklmnop"
+ ),
+ ),
+ responses(
+ (
+ status = 200,
+ description = "Revenue Recovery workflow cancelled successfully",
+ body = RecoveryPaymentsResponse,
+ example = json!({
+ "id": "12_pay_01a3868d94a471219b5c4bc71638e2zc",
+ "intent_status": "cancelled",
+ "merchant_reference_id": "invoice_mbabizu24mvu3mela5njyh"
+ })
+ ),
+ (status = 400, description = "The invoice cannot be cancelled: its payment is not failed or partially captured, a retry is in progress, or recovery already reached a terminal status", body = GenericErrorResponseOpenApi),
+ (status = 404, description = "Invoice not found"),
+ (status = 500, description = "Internal server error"),
+ ),
+ tag = "Revenue Recovery",
+ operation_id = "Cancel a Revenue Recovery Workflow",
+ security(("api_key" = []))
+)]
+pub async fn revenue_recovery_cancel() {}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 7ec9306a3b..442ab8d0a4 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -460,6 +460,8 @@ pub enum RevenueRecoveryError {
TransactionWebhookProcessingFailed,
#[error("Failed to create payment intent")]
PaymentIntentCreateFailed,
+ #[error("Failed to update payment intent")]
+ PaymentIntentUpdateFailed,
#[error("Source verification failed for billing connector")]
WebhookAuthenticationFailed,
#[error("Payment merchant connector account {id} not found using account reference id")]
@@ -523,7 +525,8 @@ impl common_utils::errors::ErrorSwitch<ApiErrorResponse> for RevenueRecoveryErro
Self::PaymentAttemptIdNotFound | Self::RetryAlgorithmTypeNotFound => {
ApiErrorResponse::WebhookResourceNotFound
}
- Self::PaymentIntentFetchFailed
+ Self::PaymentIntentUpdateFailed
+ | Self::PaymentIntentFetchFailed
| Self::PaymentAttemptFetchFailed
| Self::PaymentIntentCreateFailed
| Self::ScheduleTimeFetchFailed
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index bec1da0774..9194a60fc4 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -25,7 +25,9 @@ use common_utils::{
use diesel_models::{enums as diesel_enum, process_tracker::business_status};
use error_stack::{self, report, ResultExt};
use hyperswitch_domain_models::{
- payments::{PaymentIntent, PaymentIntentData, PaymentStatusData},
+ payments::{
+ payment_intent::PaymentIntentUpdate, PaymentIntent, PaymentIntentData, PaymentStatusData,
+ },
platform, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor,
};
use scheduler::errors as sch_errors;
@@ -1875,6 +1877,140 @@ pub async fn get_workflow_entries(
Ok((calculate_workflow, execute_workflow))
}
+/// Why an invoice's recovery workflow cannot be cancelled right now.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum CancelInvoiceRefusal {
+ #[error("invoice cannot be cancelled while its payment is in {0} state")]
+ IntentNotCancellable(IntentStatus),
+ #[error("invoice cannot be cancelled while a retry is in progress; try again shortly")]
+ RetryInProgress,
+ #[error("invoice recovery already reached a terminal status")]
+ AlreadyTerminal,
+}
+
+/// Business statuses of a CALCULATE task after which recovery never resumes.
+fn is_terminal_calculate_status(calculate_business_status: &str) -> bool {
+ [
+ business_status::CALCULATE_WORKFLOW_FINISH,
+ business_status::CANCELLED,
+ business_status::RETRIES_EXCEEDED,
+ business_status::FAILURE,
+ business_status::GLOBAL_FAILURE,
+ ]
+ .contains(&calculate_business_status)
+}
+
+/// Decide whether an invoice can be cancelled from its payment status and the current state of
+/// its CALCULATE and EXECUTE tasks, returning the status its payment intent moves to.
+///
+/// A payment sync task is only open while the intent is processing, so the intent status check
+/// already covers it.
+pub fn decide_invoice_cancellation(
+ intent_status: IntentStatus,
+ calculate: Option<&ProcessTrackerStorage>,
+ execute: Option<&ProcessTrackerStorage>,
+) -> Result<IntentStatus, CancelInvoiceRefusal> {
+ let cancelled_status = match intent_status {
+ IntentStatus::Failed => IntentStatus::Cancelled,
+ IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => {
+ IntentStatus::CancelledPostCapture
+ }
+ IntentStatus::Succeeded
+ | IntentStatus::Cancelled
+ | IntentStatus::CancelledPostCapture
+ | IntentStatus::Processing
+ | IntentStatus::PartiallyCapturedAndProcessing
+ | IntentStatus::RequiresCustomerAction
+ | IntentStatus::RequiresMerchantAction
+ | IntentStatus::RequiresPaymentMethod
+ | IntentStatus::RequiresConfirmation
+ | IntentStatus::RequiresCapture
+ | IntentStatus::PartiallyAuthorizedAndRequiresCapture
+ | IntentStatus::Conflicted
+ | IntentStatus::Expired
+ | IntentStatus::Review => {
+ return Err(CancelInvoiceRefusal::IntentNotCancellable(intent_status))
+ }
+ };
+
+ let is_running = |task: Option<&ProcessTrackerStorage>| {
+ task.is_some_and(|task| {
+ matches!(
+ task.status,
+ ProcessTrackerStatus::ProcessStarted | ProcessTrackerStatus::Processing
+ )
+ })
+ };
+
+ if is_running(calculate) || is_running(execute) {
+ Err(CancelInvoiceRefusal::RetryInProgress)
+ } else if calculate.is_some_and(|task| is_terminal_calculate_status(&task.business_status)) {
+ Err(CancelInvoiceRefusal::AlreadyTerminal)
+ } else {
+ Ok(cancelled_status)
+ }
+}
+
+/// Stop the recovery workflow of a cancelled invoice.
+///
+/// When [`decide_invoice_cancellation`] allows it, finishes the CALCULATE task as `CANCELLED`
+/// and the EXECUTE task as `FAILED_EXECUTE_TASK`, then moves the payment intent to the status
+/// the decision returned and returns it. Otherwise returns the refusal without changing anything.
+pub async fn cancel_invoice_workflows(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: common_enums::MerchantStorageScheme,
+ payment_intent: PaymentIntent,
+) -> CustomResult<Result<PaymentIntent, CancelInvoiceRefusal>, errors::RevenueRecoveryError> {
+ let db = &*state.store;
+
+ let (calculate_workflow, execute_workflow) = get_workflow_entries(state, &payment_intent.id)
+ .await
+ .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
+ .attach_printable("failed to fetch recovery workflow tasks for invoice cancellation")?;
+
+ let cancelled_status = match decide_invoice_cancellation(
+ payment_intent.status,
+ calculate_workflow.as_ref(),
+ execute_workflow.as_ref(),
+ ) {
+ Ok(cancelled_status) => cancelled_status,
+ Err(refusal) => {
+ logger::info!(
+ "Invoice {} not cancelled: {refusal}",
+ payment_intent.id.get_string_repr()
+ );
+ return Ok(Err(refusal));
+ }
+ };
+
+ for (task, status) in [
+ (calculate_workflow, business_status::CANCELLED),
+ (execute_workflow, business_status::EXECUTE_WORKFLOW_FAILURE),
+ ] {
+ if let Some(task) = task {
+ db.finish_process_with_business_status(task, status)
+ .await
+ .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
+ .attach_printable_lazy(|| format!("failed to finish recovery task as {status}"))?;
+ }
+ }
+
+ let intent_update = PaymentIntentUpdate::VoidUpdate {
+ status: cancelled_status,
+ updated_by: storage_scheme.to_string(),
+ };
+ let cancelled_intent = db
+ .update_payment_intent(payment_intent, intent_update, key_store, storage_scheme)
+ .await
+ .change_context(errors::RevenueRecoveryError::PaymentIntentUpdateFailed)
+ .attach_printable_lazy(|| {
+ format!("failed to move the payment intent to {cancelled_status}")
+ })?;
+
+ Ok(Ok(cancelled_intent))
+}
+
fn determine_recovery_status_from_workflows(
calculate_business_status: Option<String>,
calculate_process_tracker_status: Option<String>,
@@ -1926,12 +2062,7 @@ fn determine_recovery_status_from_workflows(
}
// 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 =>
- {
+ (Some(cal_biz_status), _, _, _) if is_terminal_calculate_status(&cal_biz_status) => {
RecoveryStatus::Terminated
}
@@ -2066,3 +2197,122 @@ pub fn map_to_recovery_payment_item(
last_attempt_at: payment_attempt.as_ref().map(|p| p.created_at),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn task(business_status: &str, status: ProcessTrackerStatus) -> ProcessTrackerStorage {
+ let now = common_utils::date_time::now();
+ ProcessTrackerStorage {
+ id: "test_task".to_string(),
+ name: None,
+ tag: Vec::new(),
+ runner: None,
+ retry_count: 0,
+ schedule_time: None,
+ rule: String::new(),
+ tracking_data: serde_json::Value::Null,
+ business_status: business_status.to_string(),
+ status,
+ event: Vec::new(),
+ created_at: now,
+ updated_at: now,
+ version: common_enums::ApiVersion::V2,
+ application_source: None,
+ }
+ }
+
+ #[test]
+ fn failed_invoice_is_cancelled() {
+ assert_eq!(
+ decide_invoice_cancellation(IntentStatus::Failed, None, None),
+ Ok(IntentStatus::Cancelled)
+ );
+ }
+
+ #[test]
+ fn partially_charged_invoice_is_cancelled_post_capture() {
+ for status in [
+ IntentStatus::PartiallyCaptured,
+ IntentStatus::PartiallyCapturedAndCapturable,
+ ] {
+ assert_eq!(
+ decide_invoice_cancellation(status, None, None),
+ Ok(IntentStatus::CancelledPostCapture)
+ );
+ }
+ }
+
+ #[test]
+ fn scheduled_workflow_is_cancellable() {
+ let calculate = task(
+ business_status::CALCULATE_WORKFLOW_SCHEDULED,
+ ProcessTrackerStatus::Finish,
+ );
+ let execute = task(business_status::PENDING, ProcessTrackerStatus::Pending);
+
+ assert_eq!(
+ decide_invoice_cancellation(IntentStatus::Failed, Some(&calculate), Some(&execute)),
+ Ok(IntentStatus::Cancelled)
+ );
+ }
+
+ #[test]
+ fn invoice_outside_recovery_cannot_be_cancelled() {
+ for status in [
+ IntentStatus::Succeeded,
+ IntentStatus::Processing,
+ IntentStatus::PartiallyCapturedAndProcessing,
+ IntentStatus::Cancelled,
+ IntentStatus::RequiresPaymentMethod,
+ ] {
+ assert_eq!(
+ decide_invoice_cancellation(status, None, None),
+ Err(CancelInvoiceRefusal::IntentNotCancellable(status))
+ );
+ }
+ }
+
+ #[test]
+ fn running_retry_blocks_cancellation() {
+ for status in [
+ ProcessTrackerStatus::ProcessStarted,
+ ProcessTrackerStatus::Processing,
+ ] {
+ let execute = task(business_status::PENDING, status);
+ assert_eq!(
+ decide_invoice_cancellation(IntentStatus::Failed, None, Some(&execute)),
+ Err(CancelInvoiceRefusal::RetryInProgress)
+ );
+ }
+ }
+
+ #[test]
+ fn terminal_workflow_cannot_be_cancelled_again() {
+ for terminal_status in [
+ business_status::RETRIES_EXCEEDED,
+ business_status::CALCULATE_WORKFLOW_FINISH,
+ business_status::CANCELLED,
+ ] {
+ let calculate = task(terminal_status, ProcessTrackerStatus::Finish);
+ assert_eq!(
+ decide_invoice_cancellation(IntentStatus::Failed, Some(&calculate), None),
+ Err(CancelInvoiceRefusal::AlreadyTerminal)
+ );
+ }
+ }
+
+ #[test]
+ fn cancelled_calculate_workflow_reports_terminated() {
+ let recovery_status = determine_recovery_status_from_workflows(
+ Some(business_status::CANCELLED.to_string()),
+ Some(ProcessTrackerStatus::Finish.to_string().to_uppercase()),
+ Some(business_status::EXECUTE_WORKFLOW_FAILURE.to_string()),
+ Some(ProcessTrackerStatus::Finish.to_string().to_uppercase()),
+ || RecoveryStatus::Monitoring,
+ );
+
+ assert_eq!(recovery_status, RecoveryStatus::Terminated);
+ }
+}
diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs
index b8c1bc5559..e96d50246b 100644
--- a/crates/router/src/core/revenue_recovery/api.rs
+++ b/crates/router/src/core/revenue_recovery/api.rs
@@ -397,3 +397,50 @@ pub async fn custom_revenue_recovery_core(
response,
))
}
+
+/// Cancel the revenue recovery workflow of the invoice identified by `merchant_reference_id`
+/// within `profile`.
+pub async fn cancel_revenue_recovery_core(
+ state: SessionState,
+ platform: Platform,
+ profile: domain::Profile,
+ merchant_reference_id: id_type::PaymentReferenceId,
+) -> RouterResponse<api_payments::RecoveryPaymentsResponse> {
+ let db = &*state.store;
+ let storage_scheme = platform.get_processor().get_account().storage_scheme;
+
+ let payment_intent = db
+ .find_payment_intent_by_merchant_reference_id_profile_id(
+ &merchant_reference_id,
+ profile.get_id(),
+ platform.get_processor().get_key_store(),
+ &storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let cancelled_intent = super::cancel_invoice_workflows(
+ &state,
+ platform.get_processor().get_key_store(),
+ storage_scheme,
+ payment_intent,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to cancel the revenue recovery workflow")?
+ .map_err(|refusal| {
+ report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: refusal.to_string(),
+ })
+ })?;
+
+ let response = api_payments::RecoveryPaymentsResponse {
+ id: cancelled_intent.id,
+ intent_status: cancelled_intent.status,
+ merchant_reference_id: cancelled_intent.merchant_reference_id,
+ };
+
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ response,
+ ))
+}
diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs
index 9a1d5e4f8d..6ad9034bfc 100644
--- a/crates/router/src/core/revenue_recovery/types.rs
+++ b/crates/router/src/core/revenue_recovery/types.rs
@@ -1410,6 +1410,14 @@ pub async fn reopen_calculate_workflow_on_payment_failure(
.attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?;
match calculate_process {
+ Some(process) if process.business_status == business_status::CANCELLED => {
+ logger::info!(
+ payment_id = %id.get_string_repr(),
+ process_tracker_id = %process_tracker_id,
+ current_status = %process.business_status,
+ "CALCULATE_WORKFLOW was cancelled, not reopening it on payment failure"
+ );
+ }
Some(process) => {
logger::info!(
payment_id = %id.get_string_repr(),
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index 4d6967b978..9c48eaa37d 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -1663,7 +1663,38 @@ impl RecoveryAction {
),
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
match self.action {
- common_types::payments::RecoveryAction::CancelInvoice => todo!(),
+ common_types::payments::RecoveryAction::CancelInvoice => {
+ let (_, recovery_intent) = recovery_tuple;
+ let key_store = platform.get_processor().get_key_store();
+ let storage_scheme = platform.get_processor().get_account().storage_scheme;
+ let payment_intent = state
+ .store
+ .find_payment_intent_by_id(
+ &recovery_intent.payment_id,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
+ .attach_printable("failed to fetch the payment intent to cancel")?;
+ let cancelled = core::revenue_recovery::cancel_invoice_workflows(
+ state,
+ key_store,
+ storage_scheme,
+ payment_intent,
+ )
+ .await?;
+ match cancelled {
+ Ok(updated_intent) => Ok(webhooks::WebhookResponseTracker::Payment {
+ payment_id: updated_intent.id,
+ status: updated_intent.status,
+ }),
+ Err(refusal) => {
+ logger::info!("Invoice cancel webhook took no recovery action: {refusal}");
+ Ok(webhooks::WebhookResponseTracker::NoEffect)
+ }
+ }
+ }
common_types::payments::RecoveryAction::ScheduleFailedPayment => {
let recovery_algorithm_type = business_profile
.revenue_recovery_retry_algorithm_type
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 7a4be1125f..193f1b7063 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -49,6 +49,8 @@ pub mod profile_acquirer;
pub mod profiles;
pub mod refunds;
#[cfg(feature = "v2")]
+pub mod revenue_recovery;
+#[cfg(feature = "v2")]
pub mod revenue_recovery_data_backfill;
#[cfg(feature = "v2")]
pub mod revenue_recovery_redis;
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ff8482a00c..b545c14be0 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -3540,10 +3540,16 @@ pub struct RevenueRecovery;
#[cfg(feature = "v2")]
impl RevenueRecovery {
pub fn server(state: AppState) -> Scope {
- use super::{payments, revenue_recovery_data_backfill, revenue_recovery_redis};
+ use super::{
+ payments, revenue_recovery, revenue_recovery_data_backfill, revenue_recovery_redis,
+ };
web::scope("/v2/recovery")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(payments::recovery_payments_create)))
+ .service(
+ web::resource("/{merchant_reference_id}/cancel")
+ .route(web::post().to(revenue_recovery::revenue_recovery_cancel)),
+ )
.service(
web::scope("/data-backfill")
.service(
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 82c8b38aa0..208addfacd 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -420,7 +420,8 @@ impl From<Flow> for ApiIdentifier {
Flow::RecoveryDataBackfill
| Flow::RecoveryRetryStatsMigration
- | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery,
+ | Flow::RevenueRecoveryRedis
+ | Flow::RevenueRecoveryCancel => Self::RecoveryRecovery,
Flow::GetSuperpositionSdkConfig
| Flow::SuperpositionListContexts
| Flow::SuperpositionListDefaultConfigs
diff --git a/crates/router/src/routes/revenue_recovery.rs b/crates/router/src/routes/revenue_recovery.rs
new file mode 100644
index 0000000000..c8f144e6b5
--- /dev/null
+++ b/crates/router/src/routes/revenue_recovery.rs
@@ -0,0 +1,39 @@
+use actix_web::{web, HttpRequest, Responder};
+use router_env::{instrument, tracing, Flow};
+
+use crate::{
+ core::{api_locking, revenue_recovery::api as revenue_recovery_api},
+ routes::AppState,
+ services::{api, authentication as auth},
+};
+
+#[instrument(skip_all, fields(flow = ?Flow::RevenueRecoveryCancel))]
+pub async fn revenue_recovery_cancel(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<common_utils::id_type::PaymentReferenceId>,
+) -> impl Responder {
+ let flow = Flow::RevenueRecoveryCancel;
+ let merchant_reference_id = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ revenue_recovery_api::cancel_revenue_recovery_core(
+ state,
+ auth.platform,
+ auth.profile,
+ merchant_reference_id.clone(),
+ )
+ },
+ &auth::V2ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 76af3450a6..58dd305b36 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -744,6 +744,8 @@ pub enum Flow {
RevenueRecoveryRetrieve,
/// Process Tracker Revenue Recovery Workflow Resume
RevenueRecoveryResume,
+ /// Revenue Recovery invoice cancel
+ RevenueRecoveryCancel,
/// Tokenization flow
TokenizationCreate,
/// Tokenization retrieve flow