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

97.4 KB
Raw Blame
pub mod api;
pub mod card_selection;
pub(crate) mod external_triggers;
pub mod retry_stats;
pub mod schedule;
pub mod transformers;
mod trigger_model;
pub mod types;
use std::marker::PhantomData;

use api_models::{
    enums,
    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};
use hyperswitch_domain_models::{
    payments::{
        payment_intent::PaymentIntentUpdate, PaymentIntent, PaymentIntentData, PaymentStatusData,
    },
    platform, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor,
};
use hyperswitch_masking::{PeekInterface, Secret};
use scheduler::errors as sch_errors;

use crate::{
    core::{
        errors::{self, RouterResponse, RouterResult, StorageErrorExt},
        payments::{
            self,
            operations::{GetTrackerResponse, Operation},
            transformers::GenerateResponse,
        },
        revenue_recovery::types::{
            reopen_calculate_workflow_on_payment_failure, RevenueRecoveryOutgoingWebhook,
        },
        revenue_recovery_data_backfill::unlock_connector_customer_status_handler,
    },
    db::StorageInterface,
    logger,
    routes::{app::ReqState, metrics, SessionState},
    services::ApplicationResponse,
    types::{
        api as router_api_types, domain,
        storage::{
            self, revenue_recovery as pcr, PaymentAttempt, ProcessTracker as ProcessTrackerStorage,
        },
        transformers::{ForeignFrom, ForeignInto},
    },
    utils,
    workflows::revenue_recovery as revenue_recovery_workflow,
};
pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW";
pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW";
pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW";
/// Task of the recovery request workflow, which processes one transaction the merchant reported.
pub const EXTERNAL_TRIGGER_HANDLER: &str = "EXTERNAL_TRIGGER_HANDLER";
use common_enums::enums::ProcessTrackerStatus;

#[cfg(feature = "v1")]
use crate::types::common_enums;

/// Resolves the retry implementation this invoice should use from the A/B configuration and
/// records it on the intent, so every later retry replays the same one.
pub async fn assign_and_record_ab_routing(
    state: &SessionState,
    payment_id: &GlobalPaymentId,
    feature_metadata: Option<api_payments::FeatureMetadata>,
    merchant_context: pcr::RecoveryMerchantContext<'_>,
    dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
) -> common_enums::RevenueRecoveryABAlgorithm {
    let assigned_algorithm = dimensions
        .get_revenue_recovery_ab_algorithm(
            state.store.as_ref(),
            state.superposition_service.as_ref(),
            Some(payment_id),
        )
        .await;

    let updated_feature_metadata = feature_metadata.and_then(|mut feature_metadata| {
        feature_metadata
            .revenue_recovery
            .as_mut()
            .map(|revenue_recovery_metadata| {
                revenue_recovery_metadata.revenue_recovery_ab_routing = Some(assigned_algorithm);
            })
            .map(|_| feature_metadata)
    });

    match updated_feature_metadata {
        Some(feature_metadata) => {
            let payment_update_req =
                api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
                    feature_metadata,
                    enums::UpdateActiveAttempt::NoAction,
                );

            match Box::pin(api::update_payment_intent_api(
                state,
                payment_id.clone(),
                merchant_context,
                payment_update_req,
            ))
            .await
            {
                Ok(_) => router_env::logger::info!(
                    payment_id = %payment_id.get_string_repr(),
                    algorithm = %assigned_algorithm,
                    "A/B routing assigned a retry implementation to this invoice"
                ),
                Err(error) => router_env::logger::error!(
                    ?error,
                    payment_id = %payment_id.get_string_repr(),
                    algorithm = %assigned_algorithm,
                    "Failed to record the A/B routing assignment on the invoice"
                ),
            }
        }
        None => router_env::logger::warn!(
            payment_id = %payment_id.get_string_repr(),
            "Cannot record an A/B routing assignment: the invoice has no revenue \
             recovery metadata"
        ),
    }

    assigned_algorithm
}

#[allow(clippy::too_many_arguments)]
pub async fn upsert_calculate_pcr_task(
    billing_connector_account: &domain::MerchantConnectorAccount,
    state: &SessionState,
    platform: &domain::Platform,
    recovery_intent_from_payment_intent: &domain_revenue_recovery::RecoveryPaymentIntent,
    business_profile: &domain::Profile,
    intent_retry_count: u16,
    payment_attempt_id: Option<id_type::GlobalAttemptId>,
    prev_attempt_error_code: Option<common_enums::StandardisedCode>,
    runner: storage::ProcessTrackerRunner,
    revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
    router_env::logger::info!("Starting calculate_job...");

    let task = "CALCULATE_WORKFLOW";

    let db = &*state.store;
    let payment_id = &recovery_intent_from_payment_intent.payment_id;

    // Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id}
    let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr());

    // Scheduled time is now because this will be the first entry in
    // process tracker and we dont want to wait
    let schedule_time = common_utils::date_time::now();

    let payment_attempt_id = payment_attempt_id
        .ok_or(error_stack::report!(
            errors::RevenueRecoveryError::PaymentAttemptIdNotFound
        ))
        .attach_printable("payment attempt id is required for calculate workflow tracking")?;

    // Check if a process tracker entry already exists for this payment intent
    let existing_entry = db
        .as_scheduler()
        .find_process_by_id(&process_tracker_id)
        .await
        .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
        .attach_printable(
            "Failed to check for existing calculate workflow process tracker entry",
        )?;

    match existing_entry {
        Some(existing_process) => {
            router_env::logger::error!(
                "Found existing CALCULATE_WORKFLOW task with  id: {}",
                existing_process.id
            );
        }
        None => {
            // No entry exists - create a new one
            router_env::logger::info!(
                "No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now",
                payment_id.get_string_repr()
            );

            let dimensions = crate::core::configs::dimension_state::Dimensions::new()
                .with_processor_merchant_id(
                    recovery_intent_from_payment_intent
                        .merchant_id
                        .clone()
                        .into(),
                )
                .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
                .with_profile_id(business_profile.get_id().clone());
            let max_hybrid_cascading_retry_count = dimensions
                .get_recovery_max_hybrid_cascading_retry_count(
                    state.store.as_ref(),
                    state.superposition_service.as_ref(),
                    None,
                )
                .await;

            // Create tracking data
            let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
                billing_mca_id: billing_connector_account.get_id(),
                global_payment_id: payment_id.clone(),
                merchant_id: platform.get_processor().get_account().get_id().to_owned(),
                profile_id: business_profile.get_id().to_owned(),
                prev_attempt_error_code,
                payment_attempt_id,
                revenue_recovery_retry,
                invoice_scheduled_time: None,
                static_ladder_progress: Some(schedule::StaticLadderProgress::seed_for_new_invoice(
                    intent_retry_count,
                    max_hybrid_cascading_retry_count,
                )),
                payment_processor_token: None,
            };

            let tag = ["PCR"];
            let task = "CALCULATE_WORKFLOW";
            let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;

            // The ladder is indexed by attempts already made on the invoice, so seeding it with
            // anything else replays the slots the billing connector already consumed.
            let attempts_already_made = i32::from(intent_retry_count);

            router_env::logger::info!(
                payment_id = %payment_id.get_string_repr(),
                attempts_already_made,
                "Seeding CALCULATE_WORKFLOW retry count from attempts already made"
            );

            let process_tracker_entry = storage::ProcessTrackerNew::new(
                process_tracker_id,
                task,
                runner,
                tag,
                calculate_workflow_tracking_data,
                Some(attempts_already_made),
                schedule_time,
                common_types::consts::API_VERSION,
                state.conf.application_source,
            )
            .change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError)
            .attach_printable("Failed to construct calculate workflow process tracker entry")?;

            // Insert into process tracker with status New
            db.as_scheduler()
                .insert_process(process_tracker_entry)
                .await
                .change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
                .attach_printable(
                    "Failed to enter calculate workflow process_tracker_entry in DB",
                )?;

            router_env::logger::info!(
                "Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}",
                payment_id.get_string_repr()
            );

            metrics::TASKS_ADDED_COUNT.add(
                1,
                router_env::metric_attributes!(("flow", "CalculateWorkflow")),
            );

            // A/B routing normally assigns the invoice its retry implementation here, once. The
            // CALCULATE workflow repeats the assignment only for an invoice that reaches it
            // without one, which means this write did not land.
            let dimensions = crate::core::configs::dimension_state::Dimensions::new()
                .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())
                .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
                .with_organization_id(
                    platform
                        .get_processor()
                        .get_account()
                        .organization_id
                        .clone(),
                )
                .with_profile_id(business_profile.get_id().clone());

            if dimensions
                .get_revenue_recovery_ab_enabled(
                    state.store.as_ref(),
                    state.superposition_service.as_ref(),
                    None,
                )
                .await
            {
                Box::pin(assign_and_record_ab_routing(
                    state,
                    payment_id,
                    recovery_intent_from_payment_intent.feature_metadata.clone(),
                    pcr::RecoveryMerchantContext {
                        merchant_account: platform.get_processor().get_account(),
                        key_store: platform.get_processor().get_key_store().inner(),
                        profile: business_profile,
                    },
                    &dimensions,
                ))
                .await;
            }
        }
    }

    Ok(webhooks::WebhookResponseTracker::Payment {
        payment_id: payment_id.clone(),
        status: recovery_intent_from_payment_intent.status,
    })
}

#[allow(clippy::too_many_arguments)]
pub async fn record_internal_attempt_and_execute_payment(
    state: &SessionState,
    execute_task_process: &storage::ProcessTracker,
    profile: &domain::Profile,
    platform: domain::Platform,
    tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    payment_intent: &PaymentIntent,
    payment_processor_token: &storage::revenue_recovery_redis_operation::PaymentProcessorTokenStatus,
    revenue_recovery_metadata: &mut api_models::payments::PaymentRevenueRecoveryMetadata,
) -> Result<(), sch_errors::ProcessTrackerError> {
    let db = &*state.store;

    // Standardised error code for the attempt whose failure triggered this execute task,
    let prev_attempt_error_code = tracking_data.prev_attempt_error_code;

    let card_info = api_models::payments::AdditionalCardInfo::foreign_from(payment_processor_token);

    // record attempt call
    let record_attempt = api::record_internal_attempt_api(
        state,
        payment_intent,
        revenue_recovery_payment_data,
        revenue_recovery_metadata,
        card_info,
        &payment_processor_token
            .payment_processor_token_details
            .payment_processor_token,
    )
    .await;

    match record_attempt {
        Ok(record_attempt_response) => {
            let action = Box::pin(types::Action::execute_payment(
                state,
                revenue_recovery_payment_data.merchant_account.get_id(),
                payment_intent,
                execute_task_process,
                profile,
                platform,
                revenue_recovery_payment_data,
                revenue_recovery_metadata,
                &record_attempt_response.id,
                payment_processor_token,
            ))
            .await?;
            Box::pin(action.execute_payment_task_response_handler(
                state,
                payment_intent,
                execute_task_process,
                revenue_recovery_payment_data,
                revenue_recovery_metadata,
                prev_attempt_error_code,
            ))
            .await?;
        }
        Err(err) => {
            logger::error!("Error while recording attempt: {:?}", err);
            let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
                status: ProcessTrackerStatus::Pending,
                business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
            };
            db.as_scheduler()
                .update_process(execute_task_process.clone(), pt_update)
                .await?;
        }
    }
    Ok(())
}

pub async fn perform_execute_payment(
    state: &SessionState,
    execute_task_process: &storage::ProcessTracker,
    profile: &domain::Profile,
    platform: domain::Platform,
    tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    payment_intent: &PaymentIntent,
) -> Result<(), sch_errors::ProcessTrackerError> {
    let db = &*state.store;

    let mut revenue_recovery_metadata = payment_intent
        .feature_metadata
        .as_ref()
        .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
        .get_required_value("Payment Revenue Recovery Metadata")?
        .convert_back();

    let decision = types::Decision::get_decision_based_on_params(
        state,
        payment_intent.status,
        revenue_recovery_metadata
            .payment_connector_transmission
            .unwrap_or_default(),
        payment_intent.active_attempt_id.as_ref(),
        revenue_recovery_payment_data,
        &tracking_data.global_payment_id,
    )
    .await?;

    // TODO decide if its a global failure or is it requeueable error
    match decision {
        types::Decision::Execute => {
            let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id();

            let processor_token = match tracking_data.payment_processor_token.as_ref() {
                // Calculate records the card it picked on the task, so the payment is made with
                // exactly that card
                Some(payment_processor_token) => {
                    storage::revenue_recovery_redis_operation::RedisTokenManager::get_retryable_token_using_token_id(
                        state,
                        &connector_customer_id,
                        payment_processor_token.peek(),
                    )
                    .await
                }

                // Queued before calculate recorded its pick, so the card is resolved the way it was
                // when the task was queued
                None => {
                    let last_token_used =
                        revenue_recovery_workflow::get_invoice_payment_processor_token(
                            payment_intent,
                        );

                    // Same dimensions calculate resolves the flag on
                    let adaptive_retry_enabled =
                        crate::core::configs::dimension_state::Dimensions::new()
                            .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
                            .with_connector(revenue_recovery_payment_data.billing_mca.connector_name)
                            .get_adaptive_retry_enabled(
                                state.store.as_ref(),
                                state.superposition_service.as_ref(),
                                None,
                            )
                            .await;

                    // Same dimensions calculate resolves the flag on
                    let ab_enabled = crate::core::configs::dimension_state::Dimensions::new()
                        .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
                        .with_provider_merchant_id(
                            platform.get_provider().get_provider_merchant_id(),
                        )
                        .with_organization_id(payment_intent.organization_id.clone())
                        .with_profile_id(payment_intent.profile_id.clone())
                        .get_revenue_recovery_ab_enabled(
                            state.store.as_ref(),
                            state.superposition_service.as_ref(),
                            None,
                        )
                        .await;

                    // Calculate schedules the invoice's own token on both the A/B and adaptive
                    // paths, and hands the invoice to the decider only when neither is on.
                    let smart_retry_uses_invoice_token = ab_enabled || adaptive_retry_enabled;

                    storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
                        state,
                        &connector_customer_id,
                        tracking_data.revenue_recovery_retry,
                        last_token_used.as_deref(),
                        smart_retry_uses_invoice_token,
                    )
                    .await
                }
            }
            .change_context(errors::ApiErrorResponse::GenericNotFoundError {
                message: "Failed to fetch token details from redis".to_string(),
            })?;

            match processor_token {
                None => {
                    logger::info!("No Token fetched from redis");

                    // Close the job if there is no token available
                    db.as_scheduler()
                        .finish_process_with_business_status(
                            execute_task_process.clone(),
                            business_status::EXECUTE_WORKFLOW_FAILURE,
                        )
                        .await?;

                    Box::pin(reopen_calculate_workflow_on_payment_failure(
                        state,
                        execute_task_process,
                        profile,
                        platform,
                        payment_intent,
                        revenue_recovery_payment_data,
                        &tracking_data.payment_attempt_id,
                        // No new attempt was made (no token), so the chain's failed attempt
                        // is unchanged — carry its already-resolved code forward.
                        tracking_data.prev_attempt_error_code,
                    ))
                    .await?;
                    // Unlock the customer status only if all tokens are hard declined and payment intent is in Failed status
                    let _unlocked = match payment_intent.status {
                        IntentStatus::Failed => {
                            storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
                                state,
                                &connector_customer_id,
                                &payment_intent.id,
                            )
                            .await?
                        }
                        _ => false,
                    };
                }

                Some(payment_processor_token) => {
                    logger::info!("Token fetched from redis success");

                    record_internal_attempt_and_execute_payment(
                        state,
                        execute_task_process,
                        profile,
                        platform,
                        tracking_data,
                        revenue_recovery_payment_data,
                        payment_intent,
                        &payment_processor_token,
                        &mut revenue_recovery_metadata,
                    )
                    .await?;
                }
            };
        }
        types::Decision::Psync(intent_status, attempt_id) => {
            // find if a psync task is already present
            let task = PSYNC_WORKFLOW;
            let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
            let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner);
            let psync_process = db.find_process_by_id(&process_tracker_id).await?;

            match psync_process {
                Some(_) => {
                    let pcr_status: types::RevenueRecoveryPaymentIntentStatus =
                        intent_status.foreign_into();

                    pcr_status
                        .update_pt_status_based_on_intent_status_for_execute_payment(
                            db,
                            execute_task_process,
                        )
                        .await?;
                }

                None => {
                    // insert new psync task
                    insert_psync_pcr_task_to_pt(
                        revenue_recovery_payment_data.billing_mca.get_id().clone(),
                        db,
                        revenue_recovery_payment_data
                            .merchant_account
                            .get_id()
                            .clone(),
                        payment_intent.get_id().clone(),
                        revenue_recovery_payment_data.profile.get_id().clone(),
                        attempt_id.clone(),
                        tracking_data.prev_attempt_error_code,
                        storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
                        tracking_data.revenue_recovery_retry,
                        state.conf.application_source,
                        tracking_data.static_ladder_progress.clone(),
                    )
                    .await?;

                    // finish the current task
                    db.as_scheduler()
                        .finish_process_with_business_status(
                            execute_task_process.clone(),
                            business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
                        )
                        .await?;
                }
            };
        }
        types::Decision::ReviewForSuccessfulPayment => {
            // Finish the current task since the payment was a success
            // And mark it as review as it might have happened through the external system
            db.finish_process_with_business_status(
                execute_task_process.clone(),
                business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,
            )
            .await?;
        }
        types::Decision::ReviewForFailedPayment(triggered_by) => {
            match triggered_by {
                enums::TriggeredBy::Internal => {
                    // requeue the current tasks to update the fields for rescheduling a payment
                    let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
                        status: ProcessTrackerStatus::Pending,
                        business_status: Some(String::from(
                            business_status::EXECUTE_WORKFLOW_REQUEUE,
                        )),
                    };
                    db.as_scheduler()
                        .update_process(execute_task_process.clone(), pt_update)
                        .await?;
                }
                enums::TriggeredBy::External => {
                    logger::debug!("Failed Payment Attempt Triggered By External");
                    // Finish the current task since the payment was a failure by an external source
                    db.as_scheduler()
                        .finish_process_with_business_status(
                            execute_task_process.clone(),
                            business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,
                        )
                        .await?;
                }
            };
        }
        types::Decision::InvalidDecision => {
            db.finish_process_with_business_status(
                execute_task_process.clone(),
                business_status::EXECUTE_WORKFLOW_COMPLETE,
            )
            .await?;
            logger::warn!("Abnormal State Identified")
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn insert_psync_pcr_task_to_pt(
    billing_mca_id: id_type::MerchantConnectorAccountId,
    db: &dyn StorageInterface,
    merchant_id: id_type::MerchantId,
    payment_id: GlobalPaymentId,
    profile_id: id_type::ProfileId,
    payment_attempt_id: id_type::GlobalAttemptId,
    prev_attempt_error_code: Option<common_enums::StandardisedCode>,
    runner: storage::ProcessTrackerRunner,
    revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
    application_source: common_enums::ApplicationSource,
    static_ladder_progress: Option<schedule::StaticLadderProgress>,
) -> RouterResult<storage::ProcessTracker> {
    let task = PSYNC_WORKFLOW;
    let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner);
    let schedule_time = common_utils::date_time::now();
    let psync_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
        billing_mca_id,
        global_payment_id: payment_id,
        merchant_id,
        profile_id,
        payment_attempt_id,
        prev_attempt_error_code,
        revenue_recovery_retry,
        invoice_scheduled_time: Some(schedule_time),
        static_ladder_progress,
        payment_processor_token: None,
    };
    let tag = ["REVENUE_RECOVERY"];
    let process_tracker_entry = storage::ProcessTrackerNew::new(
        process_tracker_id,
        task,
        runner,
        tag,
        psync_workflow_tracking_data,
        None,
        schedule_time,
        common_types::consts::API_VERSION,
        application_source,
    )
    .change_context(errors::ApiErrorResponse::InternalServerError)
    .attach_printable("Failed to construct delete tokenized data process tracker task")?;

    let response = db
        .insert_process(process_tracker_entry)
        .await
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("Failed to construct delete tokenized data process tracker task")?;
    metrics::TASKS_ADDED_COUNT.add(
        1,
        router_env::metric_attributes!(("flow", "RevenueRecoveryPsync")),
    );

    Ok(response)
}

pub async fn perform_payments_sync(
    state: &SessionState,
    process: &storage::ProcessTracker,
    profile: &domain::Profile,
    platform: domain::Platform,
    tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    payment_intent: &PaymentIntent,
) -> Result<(), errors::ProcessTrackerError> {
    // Standardised error code for the failed attempt that motivated this retry chain,
    let prev_attempt_error_code = tracking_data.prev_attempt_error_code;

    let psync_data = api::call_psync_api(
        state,
        &tracking_data.global_payment_id,
        revenue_recovery_payment_data,
        true,
        true,
    )
    .await?;

    let payment_attempt = psync_data.payment_attempt.clone();
    let mut revenue_recovery_metadata = payment_intent
        .feature_metadata
        .as_ref()
        .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
        .get_required_value("Payment Revenue Recovery Metadata")?
        .convert_back();
    let pcr_status: types::RevenueRecoveryPaymentIntentStatus =
        payment_intent.status.foreign_into();

    let new_revenue_recovery_payment_data = &pcr::RevenueRecoveryPaymentData {
        psync_data: Some(psync_data),
        ..revenue_recovery_payment_data.clone()
    };

    Box::pin(
        pcr_status.update_pt_status_based_on_attempt_status_for_payments_sync(
            state,
            payment_intent,
            process.clone(),
            profile,
            platform,
            new_revenue_recovery_payment_data,
            payment_attempt,
            &mut revenue_recovery_metadata,
            prev_attempt_error_code,
        ),
    )
    .await?;

    Ok(())
}

/// Counts an invoice whose grace window could not be established. Every caller is terminal, and
/// they fail for unrelated reasons — the invoice carries no billing start date, the configured
/// period pushes the end date past what a timestamp holds, or the days left do not fit the model's
/// day count — so `reason` is what separates them.
fn record_grace_window_unresolved(reason: &'static str) {
    metrics::REVENUE_RECOVERY_GRACE_WINDOW_UNRESOLVED
        .add(1, router_env::metric_attributes!(("reason", reason)));
}

/// When the invoice's recovery grace window closes: its billing start plus the configured grace
/// period.
fn get_recovery_grace_window_end(
    payment_intent: &PaymentIntent,
    grace_period_days: u16,
) -> CustomResult<time::PrimitiveDateTime, errors::RecoveryError> {
    let grace_period_days = i64::from(grace_period_days);

    let grace_window_start = payment_intent
        .get_revenue_recovery_metadata()
        .and_then(|revenue_recovery_metadata| {
            revenue_recovery_metadata.invoice_billing_started_at_time
        })
        .ok_or_else(|| {
            record_grace_window_unresolved("missing_billing_start_time");
            errors::RecoveryError::ValueNotFound
        })
        .attach_printable(
            "Cannot bound the invoice by its grace window: the intent has no billing start time",
        )?;

    grace_window_start
        .checked_add(time::Duration::days(grace_period_days))
        .ok_or_else(|| {
            record_grace_window_unresolved("grace_window_end_overflow");
            errors::RecoveryError::ValueNotFound
        })
        .attach_printable("The end of the grace window does not fit a timestamp")
}

/// `retries_already_made` is the invoice's retries so far, not counting its first attempt, so
/// retries stop once it reaches `max_retry_count`.
fn is_retry_budget_exhausted(retries_already_made: u16, max_retry_count: u16) -> bool {
    retries_already_made >= max_retry_count
}

pub async fn perform_calculate_workflow(
    state: &SessionState,
    process: &storage::ProcessTracker,
    profile: &domain::Profile,
    platform: domain::Platform,
    tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    payment_intent: &PaymentIntent,
) -> Result<(), sch_errors::ProcessTrackerError> {
    let db = &*state.store;
    let merchant_id = revenue_recovery_payment_data.merchant_account.get_id();
    let profile_id = revenue_recovery_payment_data.profile.get_id();
    let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id();

    let mut event_type: Option<common_enums::EventType> = None;

    logger::info!(
        process_id = %process.id,
        payment_id = %tracking_data.global_payment_id.get_string_repr(),
        "Starting CALCULATE_WORKFLOW..."
    );

    // 1. Extract connector_customer_id and token_list from tracking_data
    let connector_customer_id = payment_intent
        .extract_connector_customer_id_from_payment_intent()
        .change_context(errors::RecoveryError::ValueNotFound)
        .attach_printable("Failed to extract customer ID from payment intent")?;

    let platform_from_revenue_recovery_payment_data = domain::Platform::new(
        revenue_recovery_payment_data.merchant_account.clone(),
        revenue_recovery_payment_data.key_store.clone(),
        revenue_recovery_payment_data.merchant_account.clone(),
        revenue_recovery_payment_data.key_store.clone(),
        None,
    );

    let retry_algorithm_type = match profile
        .revenue_recovery_retry_algorithm_type
        .filter(|retry_type|
             *retry_type != common_enums::RevenueRecoveryAlgorithmType::Monitoring) // ignore Monitoring in profile
        .unwrap_or(tracking_data.revenue_recovery_retry)                                                                  // fallback to tracking_data
    {
        common_enums::RevenueRecoveryAlgorithmType::Smart => common_enums::RevenueRecoveryAlgorithmType::Smart,
        common_enums::RevenueRecoveryAlgorithmType::Cascading => common_enums::RevenueRecoveryAlgorithmType::Cascading,
        common_enums::RevenueRecoveryAlgorithmType::Monitoring => {
            return Err(sch_errors::ProcessTrackerError::ProcessUpdateFailed);
        }
    };

    // External Payments which enter the calculate workflow for the first time will have active attempt id as None
    // Then we dont need to send an webhook to the merchant as its not a failure from our side.
    // Thus we dont need to a payment get call for such payments.
    let active_payment_attempt_id = payment_intent.active_attempt_id.as_ref();

    let payments_response = get_payment_response_using_payment_get_operation(
        state,
        &tracking_data.global_payment_id,
        revenue_recovery_payment_data,
        &platform_from_revenue_recovery_payment_data,
        active_payment_attempt_id,
    )
    .await?;

    let total_retry_count = payment_intent
        .get_revenue_recovery_retry_count()
        .ok_or(errors::RecoveryError::ValueNotFound)
        .attach_printable(
            "Failed to get the retry count from the payment intent's revenue recovery metadata",
        )?;

    let static_ladder_progress = match tracking_data.static_ladder_progress.clone() {
        Some(static_ladder_progress) => static_ladder_progress,
        None => {
            let dimensions = crate::core::configs::dimension_state::Dimensions::new()
                .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
                .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
                .with_profile_id(payment_intent.profile_id.clone());
            let max_hybrid_cascading_retry_count = dimensions
                .get_recovery_max_hybrid_cascading_retry_count(
                    state.store.as_ref(),
                    state.superposition_service.as_ref(),
                    None,
                )
                .await;
            schedule::StaticLadderProgress::seed_for_existing_invoice(
                total_retry_count,
                max_hybrid_cascading_retry_count,
            )
        }
    };

    // 2. Bound the invoice by the merchant's ceiling, independently of the retry ladder.
    let max_retry_count = revenue_recovery_payment_data
        .billing_mca
        .get_max_retry_count()
        .ok_or(errors::RecoveryError::ValueNotFound)
        .attach_printable(
            "Failed to get max retry count from billing merchant connector account",
        )?;

    let retry_budget_exhausted = is_retry_budget_exhausted(total_retry_count, max_retry_count);

    // 2b. Bound the invoice by its grace window as well as its retry count.
    let grace_window_end = if retry_budget_exhausted {
        None
    } else {
        let grace_period_days = revenue_recovery_payment_data
            .billing_mca
            .get_grace_period_days()
            .ok_or(errors::RecoveryError::ValueNotFound)
            .attach_printable(
                "Failed to get grace period days from billing merchant connector account",
            )?;
        Some(get_recovery_grace_window_end(
            payment_intent,
            grace_period_days,
        )?)
    };

    let grace_window_elapsed = grace_window_end
        .is_some_and(|grace_window_end| grace_window_end <= common_utils::date_time::now());

    let (payment_processor_token_response, next_static_ladder_progress) = if retry_budget_exhausted
    {
        logger::info!(
            process_id = %process.id,
            retry_count = total_retry_count,
            ?max_retry_count,
            "Invoice reached the retry ceiling configured on the billing MCA"
        );
        (
            revenue_recovery_workflow::PaymentProcessorTokenResponse::RetriesExhausted,
            None,
        )
    } else if grace_window_elapsed {
        logger::info!(
            process_id = %process.id,
            retry_count = total_retry_count,
            ?grace_window_end,
            "Invoice is past its recovery grace window"
        );
        (
            revenue_recovery_workflow::PaymentProcessorTokenResponse::GraceWindowExpired,
            None,
        )
    } else {
        // The allowances the retry model needs, derived once here from the window established
        // above and handed to whichever arm runs. Both arms read the same pair, so enrolling an
        // invoice in A/B routing cannot change the budget its model is working against.
        // Unreachable as `None`: this arm is only taken when retries remain, and the window is
        // computed — or errored — above.
        let grace_window_end = grace_window_end
            .ok_or(errors::RecoveryError::ValueNotFound)
            .attach_printable("Cannot derive the recovery allowances: the grace window is unset")?;

        let remaining_grace_days = u32::try_from(
            (grace_window_end - common_utils::date_time::now())
                .whole_days()
                .max(0),
        )
        .inspect_err(|_| record_grace_window_unresolved("grace_days_out_of_range"))
        .change_context(errors::RecoveryError::ValueNotFound)
        .attach_printable("The days left in the grace window do not fit a day count")?;

        // Saturating so an invoice already past its ceiling reads as no budget left rather
        // than wrapping to an enormous one.
        let remaining_budget = u32::from(max_retry_count.saturating_sub(total_retry_count));

        // 3. Get best available token
        match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(
            state,
            &connector_customer_id,
            payment_intent,
            revenue_recovery_payment_data.billing_mca.connector_name,
            retry_algorithm_type,
            u32::from(total_retry_count),
            tracking_data,
            &static_ladder_progress,
            platform.get_provider().get_provider_merchant_id(),
            remaining_grace_days,
            remaining_budget,
            revenue_recovery_payment_data,
        )
        .await
        {
            Ok(token_and_schedule) => token_and_schedule,
            Err(e) => {
                logger::error!(
                    error = ?e,
                    connector_customer_id = %connector_customer_id,
                    "Failed to get best PSP token"
                );
                (
                    revenue_recovery_workflow::PaymentProcessorTokenResponse::None,
                    None,
                )
            }
        }
    };

    // Counted here rather than where each outcome is produced, because this is the only point all
    // six pass through: the retry-ceiling and grace-window checks above short-circuit the workflow
    // entirely, and the ladder-exhausted case returns early inside it. Four of the six mean the
    // invoice is not retried; the two that schedule something are counted as well, since a drop
    // rate is only readable against a denominator.
    metrics::REVENUE_RECOVERY_CALCULATE_OUTCOME.add(
        1,
        router_env::metric_attributes!(
            ("outcome", payment_processor_token_response.as_str()),
            ("algorithm", retry_algorithm_type.to_string())
        ),
    );

    match payment_processor_token_response {
        revenue_recovery_workflow::PaymentProcessorTokenResponse::ScheduledTime {
            scheduled_time,
            payment_processor_token,
        } => {
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "Found best available token, creating EXECUTE_WORKFLOW task"
            );

            // reset active attmept id and payment connector transmission before going to execute workflow
            let  _ = Box::pin(reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow(
            state,
            payment_intent,
            revenue_recovery_payment_data,
            active_payment_attempt_id
        )).await?;

            // 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW
            insert_execute_pcr_task_to_pt(
                &tracking_data.billing_mca_id,
                state,
                &tracking_data.merchant_id,
                payment_intent,
                &tracking_data.profile_id,
                &tracking_data.payment_attempt_id,
                tracking_data.prev_attempt_error_code,
                storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
                retry_algorithm_type,
                scheduled_time,
                next_static_ladder_progress.clone(),
                payment_processor_token,
            )
            .await?;

            finish_calculate_workflow_with_progress(db, process, next_static_ladder_progress)
                .await?;

            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "CALCULATE_WORKFLOW completed successfully"
            );
        }

        revenue_recovery_workflow::PaymentProcessorTokenResponse::NextAvailableTime {
            next_available_time,
        } => {
            // Update scheduled time to next_available_time + Buffer
            // here next_available_time is the wait time
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "No token but time available, rescheduling for scheduled time "
            );

            update_calculate_job_schedule_time(
                db,
                process,
                time::Duration::seconds(
                    state
                        .conf
                        .revenue_recovery
                        .recovery_timestamp
                        .job_schedule_buffer_time_in_seconds,
                ),
                Some(next_available_time),
                &connector_customer_id,
                retry_algorithm_type,
            )
            .await?;
        }
        revenue_recovery_workflow::PaymentProcessorTokenResponse::None => {
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "Hard decline flag is false, rescheduling after job_schedule_buffer_time_in_seconds"
            );

            update_calculate_job_schedule_time(
                db,
                process,
                time::Duration::seconds(
                    state
                        .conf
                        .revenue_recovery
                        .recovery_timestamp
                        .job_schedule_buffer_time_in_seconds,
                ),
                Some(common_utils::date_time::now()),
                &connector_customer_id,
                retry_algorithm_type,
            )
            .await?;
        }
        revenue_recovery_workflow::PaymentProcessorTokenResponse::RetriesExhausted => {
            // Rescheduling here would keep the job alive forever without ever retrying a payment.
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                retry_count = total_retry_count,
                "Retry ladder exhausted, finishing CALCULATE_WORKFLOW"
            );

            db.as_scheduler()
                .finish_process_with_business_status(
                    process.clone(),
                    business_status::RETRIES_EXCEEDED,
                )
                .await
                .map_err(|e| {
                    logger::error!(
                        process_id = %process.id,
                        error = ?e,
                        "Failed to finish CALCULATE_WORKFLOW after exhausting retries"
                    );
                    sch_errors::ProcessTrackerError::ProcessUpdateFailed
                })?;

            event_type = Some(common_enums::EventType::PaymentFailed);
        }
        revenue_recovery_workflow::PaymentProcessorTokenResponse::GraceWindowExpired => {
            // Terminal for the same reason as an exhausted ladder — rescheduling would keep the job
            // alive forever — but recorded under its own business status so the two reasons stay
            // distinguishable after the fact.
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                retry_count = total_retry_count,
                "Grace window expired, finishing CALCULATE_WORKFLOW"
            );

            db.as_scheduler()
                .finish_process_with_business_status(
                    process.clone(),
                    business_status::GRACE_WINDOW_EXPIRED,
                )
                .await
                .map_err(|e| {
                    logger::error!(
                        process_id = %process.id,
                        error = ?e,
                        "Failed to finish CALCULATE_WORKFLOW after the grace window expired"
                    );
                    sch_errors::ProcessTrackerError::ProcessUpdateFailed
                })?;

            event_type = Some(common_enums::EventType::PaymentFailed);
        }
        revenue_recovery_workflow::PaymentProcessorTokenResponse::HardDecline => {
            // Finish calculate workflow with CALCULATE_WORKFLOW_FINISH
            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "Token/Tokens is/are Hard decline, finishing CALCULATE_WORKFLOW"
            );

            db.as_scheduler()
                .finish_process_with_business_status(
                    process.clone(),
                    business_status::CALCULATE_WORKFLOW_FINISH,
                )
                .await
                .map_err(|e| {
                    logger::error!(
                        process_id = %process.id,
                        error = ?e,
                        "Failed to finish CALCULATE_WORKFLOW"
                    );
                    sch_errors::ProcessTrackerError::ProcessUpdateFailed
                })?;

            event_type = Some(common_enums::EventType::PaymentFailed);

            logger::info!(
                process_id = %process.id,
                connector_customer_id = %connector_customer_id,
                "CALCULATE_WORKFLOW finished successfully"
            );
        }
    }

    let _outgoing_webhook = event_type.and_then(|event_kind| {
        payments_response.map(|resp| Some((event_kind, resp)))
    })
    .flatten()
    .async_map(|(event_kind, response)| async move {
        let _ = Box::pin(RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
            state,
            common_enums::EventClass::Payments,
            event_kind,
            payment_intent,
            &platform,
            profile,
            tracking_data.payment_attempt_id.get_string_repr().to_string(),
            response
        ))
        .await
        .map_err(|e| {
            logger::error!(
                error = ?e,
                "Failed to send outgoing webhook"
            );
            e
        })
        .ok();
    }
    ).await;

    Ok(())
}

/// Finish the CALCULATE_WORKFLOW row, carrying any supplied ladder scheduling state.
async fn finish_calculate_workflow_with_progress(
    db: &dyn StorageInterface,
    process: &storage::ProcessTracker,
    next_static_ladder_progress: Option<schedule::StaticLadderProgress>,
) -> Result<(), sch_errors::ProcessTrackerError> {
    let pt_update = match next_static_ladder_progress {
        // A ladder position was supplied, so it and the finish go out in one write rather than
        // leaving a window where one landed without the other.
        Some(static_ladder_progress) => {
            let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
                serde_json::from_value(process.tracking_data.clone())
                    .change_context(errors::RecoveryError::ValueNotFound)
                    .attach_printable(
                        "Failed to deserialize the tracking data from process tracker",
                    )?;

            tracking_data.static_ladder_progress = Some(static_ladder_progress);

            let tracking_data = serde_json::to_value(tracking_data)
                .change_context(errors::RecoveryError::ValueNotFound)
                .attach_printable("Failed to serialize the tracking data for process tracker")?;

            storage::ProcessTrackerUpdate::Update {
                name: None,
                retry_count: None,
                schedule_time: None,
                tracking_data: Some(tracking_data),
                business_status: Some(String::from(business_status::CALCULATE_WORKFLOW_SCHEDULED)),
                status: Some(ProcessTrackerStatus::Finish),
                updated_at: Some(common_utils::date_time::now()),
            }
        }
        // Nothing to persist - the same status-only write this row has always taken.
        None => storage::ProcessTrackerUpdate::StatusUpdate {
            status: ProcessTrackerStatus::Finish,
            business_status: Some(String::from(business_status::CALCULATE_WORKFLOW_SCHEDULED)),
        },
    };

    db.as_scheduler()
        .finish_process_with_update(process.clone(), pt_update)
        .await
        .map_err(|error| {
            logger::error!(
                process_id = %process.id,
                error = ?error,
                "Failed to update CALCULATE_WORKFLOW status to complete"
            );
            sch_errors::ProcessTrackerError::ProcessUpdateFailed
        })
}

/// Update the schedule time for a CALCULATE_WORKFLOW process tracker
async fn update_calculate_job_schedule_time(
    db: &dyn StorageInterface,
    process: &storage::ProcessTracker,
    additional_time: time::Duration,
    base_time: Option<time::PrimitiveDateTime>,
    connector_customer_id: &str,
    retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
) -> Result<(), sch_errors::ProcessTrackerError> {
    let now = common_utils::date_time::now();

    let new_schedule_time = base_time.filter(|&t| t > now).unwrap_or(now) + additional_time;
    logger::info!(
        new_schedule_time = %new_schedule_time,
        process_id = %process.id,
        connector_customer_id = %connector_customer_id,
        "Rescheduling Calculate Job at "
    );
    let mut old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
        serde_json::from_value(process.tracking_data.clone())
            .change_context(errors::RecoveryError::ValueNotFound)
            .attach_printable("Failed to deserialize the tracking data from process tracker")?;

    old_tracking_data.revenue_recovery_retry = retry_algorithm_type;

    let tracking_data = serde_json::to_value(old_tracking_data)
        .change_context(errors::RecoveryError::ValueNotFound)
        .attach_printable("Failed to serialize the tracking data for process tracker")?;

    let pt_update = storage::ProcessTrackerUpdate::Update {
        name: Some("CALCULATE_WORKFLOW".to_string()),
        retry_count: Some(process.clone().retry_count),
        schedule_time: Some(new_schedule_time),
        tracking_data: Some(tracking_data),
        business_status: Some(String::from(business_status::PENDING)),
        status: Some(ProcessTrackerStatus::Pending),
        updated_at: Some(common_utils::date_time::now()),
    };

    db.as_scheduler()
        .update_process(process.clone(), pt_update)
        .await
        .map_err(|e| {
            logger::error!(
                process_id = %process.id,
                error = ?e,
                "Failed to reschedule CALCULATE_WORKFLOW"
            );
            sch_errors::ProcessTrackerError::ProcessUpdateFailed
        })?;

    logger::info!(
        process_id = %process.id,
        connector_customer_id = %connector_customer_id,
        new_schedule_time = %new_schedule_time,
        additional_time = ?additional_time,
        "CALCULATE_WORKFLOW rescheduled successfully"
    );

    Ok(())
}

/// Insert Execute PCR Task to Process Tracker
#[allow(clippy::too_many_arguments)]
async fn insert_execute_pcr_task_to_pt(
    billing_mca_id: &id_type::MerchantConnectorAccountId,
    state: &SessionState,
    merchant_id: &id_type::MerchantId,
    payment_intent: &PaymentIntent,
    profile_id: &id_type::ProfileId,
    payment_attempt_id: &id_type::GlobalAttemptId,
    prev_attempt_error_code: Option<common_enums::StandardisedCode>,
    runner: storage::ProcessTrackerRunner,
    revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
    schedule_time: time::PrimitiveDateTime,
    static_ladder_progress: Option<schedule::StaticLadderProgress>,
    payment_processor_token: String,
) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> {
    let task = "EXECUTE_WORKFLOW";

    let payment_id = payment_intent.id.clone();

    let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr());

    // Check if a process tracker entry already exists for this payment intent
    let existing_entry = state
        .store
        .find_process_by_id(&process_tracker_id)
        .await
        .map_err(|e| {
            logger::error!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %process_tracker_id,
                error = ?e,
                "Failed to check for existing execute workflow process tracker entry"
            );
            sch_errors::ProcessTrackerError::ProcessUpdateFailed
        })?;

    match existing_entry {
        Some(existing_process)
            if existing_process.business_status == business_status::EXECUTE_WORKFLOW_FAILURE
                || existing_process.business_status
                    == business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC =>
        {
            // Entry exists with EXECUTE_WORKFLOW_COMPLETE status - update it
            logger::info!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %process_tracker_id,
                current_retry_count = %existing_process.retry_count,
                "Found existing EXECUTE_WORKFLOW task with COMPLETE status, updating to PENDING with incremented retry count"
            );

            let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
                serde_json::from_value(existing_process.tracking_data.clone())
                    .change_context(errors::RecoveryError::ValueNotFound)
                    .attach_printable(
                        "Failed to deserialize the tracking data from process tracker",
                    )?;

            tracking_data.revenue_recovery_retry = revenue_recovery_retry;
            tracking_data.static_ladder_progress = static_ladder_progress;
            tracking_data.prev_attempt_error_code = prev_attempt_error_code;
            tracking_data.payment_processor_token = Some(Secret::new(payment_processor_token));

            let tracking_data_json = serde_json::to_value(&tracking_data)
                .change_context(errors::RecoveryError::ValueNotFound)
                .attach_printable("Failed to serialize the tracking data to json")?;

            let pt_update = storage::ProcessTrackerUpdate::Update {
                name: Some(task.to_string()),
                retry_count: Some(existing_process.clone().retry_count + 1),
                schedule_time: Some(schedule_time),
                tracking_data: Some(tracking_data_json),
                business_status: Some(String::from(business_status::PENDING)),
                status: Some(ProcessTrackerStatus::Pending),
                updated_at: Some(common_utils::date_time::now()),
            };

            let updated_process = state
                .store
                .update_process(existing_process, pt_update)
                .await
                .map_err(|e| {
                    logger::error!(
                        payment_id = %payment_id.get_string_repr(),
                        process_tracker_id = %process_tracker_id,
                        error = ?e,
                        "Failed to update existing execute workflow process tracker entry"
                    );
                    sch_errors::ProcessTrackerError::ProcessUpdateFailed
                })?;

            logger::info!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %process_tracker_id,
                new_retry_count = %updated_process.retry_count,
                "Successfully updated existing EXECUTE_WORKFLOW task"
            );

            Ok(updated_process)
        }
        Some(existing_process) => {
            // Entry exists but business status is not EXECUTE_WORKFLOW_COMPLETE
            logger::info!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %process_tracker_id,
                current_business_status = %existing_process.business_status,
            );

            Ok(existing_process)
        }
        None => {
            // No entry exists - create a new one
            logger::info!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %process_tracker_id,
                "No existing EXECUTE_WORKFLOW task found, creating new entry"
            );

            let execute_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
                billing_mca_id: billing_mca_id.clone(),
                global_payment_id: payment_id.clone(),
                merchant_id: merchant_id.clone(),
                profile_id: profile_id.clone(),
                payment_attempt_id: payment_attempt_id.clone(),
                prev_attempt_error_code,
                revenue_recovery_retry,
                invoice_scheduled_time: Some(schedule_time),
                static_ladder_progress,
                payment_processor_token: Some(Secret::new(payment_processor_token)),
            };

            let tag = ["PCR"];
            let process_tracker_entry = storage::ProcessTrackerNew::new(
                process_tracker_id.clone(),
                task,
                runner,
                tag,
                execute_workflow_tracking_data,
                Some(1),
                schedule_time,
                common_types::consts::API_VERSION,
                state.conf.application_source,
            )
            .map_err(|e| {
                logger::error!(
                    payment_id = %payment_id.get_string_repr(),
                    error = ?e,
                    "Failed to construct execute workflow process tracker entry"
                );
                sch_errors::ProcessTrackerError::ProcessUpdateFailed
            })?;

            let response = state
                .store
                .insert_process(process_tracker_entry)
                .await
                .map_err(|e| {
                    logger::error!(
                        payment_id = %payment_id.get_string_repr(),
                        error = ?e,
                        "Failed to insert execute workflow process tracker entry"
                    );
                    sch_errors::ProcessTrackerError::ProcessUpdateFailed
                })?;

            metrics::TASKS_ADDED_COUNT.add(
                1,
                router_env::metric_attributes!(("flow", "RevenueRecoveryExecute")),
            );

            logger::info!(
                payment_id = %payment_id.get_string_repr(),
                process_tracker_id = %response.id,
                "Successfully created new EXECUTE_WORKFLOW task"
            );

            Ok(response)
        }
    }
}

pub async fn retrieve_revenue_recovery_process_tracker(
    state: SessionState,
    platform: domain::Platform,
    profile: domain::Profile,
    id: GlobalPaymentId,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
    let db = &*state.store;
    let task = EXECUTE_WORKFLOW;
    let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
    let process_tracker_id = id.get_execute_revenue_recovery_id(task, runner);

    let process_tracker = db
        .find_process_by_id(&process_tracker_id)
        .await
        .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
        .attach_printable("error retrieving the process tracker id")?
        .get_required_value("Process Tracker")
        .change_context(errors::ApiErrorResponse::GenericNotFoundError {
            message: "Entry For the following id doesn't exists".to_owned(),
        })?;

    let tracking_data = process_tracker
        .tracking_data
        .clone()
        .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData")
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("unable to deserialize  Pcr Workflow Tracking Data")?;

    // The process tracker is looked up by payment id alone, so make sure it belongs to the caller
    if !utils::is_owned_by_merchant_and_profile(
        &platform,
        &profile,
        &tracking_data.merchant_id,
        &tracking_data.profile_id,
    ) {
        return Err(report!(errors::ApiErrorResponse::GenericNotFoundError {
            message: "Entry For the following id doesn't exists".to_owned(),
        }));
    }

    let psync_task = PSYNC_WORKFLOW;

    let process_tracker_id_for_psync = tracking_data
        .payment_attempt_id
        .get_psync_revenue_recovery_id(psync_task, runner);

    let process_tracker_for_psync = db
        .find_process_by_id(&process_tracker_id_for_psync)
        .await
        .map_err(|e| {
            logger::error!("Error while retrieving psync task : {:?}", e);
        })
        .ok()
        .flatten();

    let schedule_time_for_psync = process_tracker_for_psync.and_then(|pt| pt.schedule_time);

    let response = revenue_recovery::RevenueRecoveryResponse {
        id: process_tracker.id,
        name: process_tracker.name,
        schedule_time_for_payment: process_tracker.schedule_time,
        schedule_time_for_psync,
        status: process_tracker.status,
        business_status: process_tracker.business_status,
    };
    Ok(ApplicationResponse::Json(response))
}

pub async fn resume_revenue_recovery_process_tracker(
    state: SessionState,
    id: GlobalPaymentId,
    request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
    let db = &*state.store;
    let task = request_retrigger.revenue_recovery_task;
    let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
    let process_tracker_id = id.get_execute_revenue_recovery_id(&task, runner);

    let process_tracker = db
        .find_process_by_id(&process_tracker_id)
        .await
        .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
        .attach_printable("error retrieving the process tracker id")?
        .get_required_value("Process Tracker")
        .change_context(errors::ApiErrorResponse::GenericNotFoundError {
            message: "Entry For the following id doesn't exists".to_owned(),
        })?;

    let tracking_data = process_tracker
        .tracking_data
        .clone()
        .parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData")
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("unable to deserialize  Pcr Workflow Tracking Data")?;

    //Call payment intent to check the status
    let request = PaymentsGetIntentRequest { id: id.clone() };
    let revenue_recovery_payment_data =
        revenue_recovery_workflow::extract_data_and_perform_action(&state, &tracking_data)
            .await
            .change_context(errors::ApiErrorResponse::GenericNotFoundError {
                message: "Failed to extract the revenue recovery data".to_owned(),
            })?;
    let platform_from_revenue_recovery_payment_data = domain::Platform::new(
        revenue_recovery_payment_data.merchant_account.clone(),
        revenue_recovery_payment_data.key_store.clone(),
        revenue_recovery_payment_data.merchant_account.clone(),
        revenue_recovery_payment_data.key_store.clone(),
        None,
    );
    let create_intent_response = Box::pin(payments::payments_intent_core::<
        router_api_types::PaymentGetIntent,
        router_api_types::payments::PaymentsIntentResponse,
        _,
        _,
        PaymentIntentData<router_api_types::PaymentGetIntent>,
    >(
        state.clone(),
        state.get_req_state(),
        platform_from_revenue_recovery_payment_data,
        revenue_recovery_payment_data.profile.clone(),
        payments::operations::PaymentGetIntent,
        request,
        tracking_data.global_payment_id.clone(),
        hyperswitch_domain_models::payments::HeaderPayload::default(),
    ))
    .await?;

    let response = create_intent_response
        .get_json_body()
        .change_context(errors::ApiErrorResponse::InternalServerError)
        .attach_printable("Unexpected response from payments core")?;

    match response.status {
        IntentStatus::Failed => {
            let pt_update = storage::ProcessTrackerUpdate::Update {
                name: process_tracker.name.clone(),
                tracking_data: Some(process_tracker.tracking_data.clone()),
                // For business_status and status, use the values from the request
                // if provided, otherwise retain the existing values on the task
                // (None leaves the column unchanged).
                business_status: request_retrigger.business_status.clone(),
                status: request_retrigger.status,
                updated_at: Some(common_utils::date_time::now()),
                // Use the retry count from the request if provided, otherwise
                // retain the existing retry count on the task.
                retry_count: Some(
                    request_retrigger
                        .retry_count
                        .unwrap_or(process_tracker.retry_count),
                ),
                // Use the schedule time from the request if provided, otherwise
                // retain the existing schedule time on the task.
                schedule_time: request_retrigger.schedule_time,
            };
            let updated_pt = db
                .update_process(process_tracker, pt_update)
                .await
                .change_context(errors::ApiErrorResponse::GenericNotFoundError {
                    message: "Failed to update the process tracker".to_owned(),
                })?;
            let response = revenue_recovery::RevenueRecoveryResponse {
                id: updated_pt.id,
                name: updated_pt.name,
                schedule_time_for_payment: updated_pt.schedule_time,
                schedule_time_for_psync: None,
                status: updated_pt.status,
                business_status: updated_pt.business_status,
            };
            Ok(ApplicationResponse::Json(response))
        }
        // Payment already charged, but the record-back to the billing connector may have failed
        // (e.g. `site_not_found`). PSYNC only *syncs* the existing attempt (no re-charge) and, on
        // `SuccessfulPayment`, re-runs `record_back_to_billing_connector`. So (re)enqueue a PSYNC
        // task for the executed attempt to retry the record-back.
        IntentStatus::Succeeded => {
            // Sync the intent's *active* (charged) attempt, NOT tracking_data's attempt — the latter
            // is the original failed attempt; the successful retry lives on `active_attempt_id`.
            let processor_account = domain::ProcessorMerchantAccount::from_untagged(
                revenue_recovery_payment_data.merchant_account.clone(),
            );
            let processor_key_store = domain::ProcessorKeyStore::from_untagged(
                revenue_recovery_payment_data.key_store.clone(),
            );
            let payment_intent = db
                .find_payment_intent_by_id(
                    &id,
                    &processor_key_store,
                    processor_account.get_storage_scheme(),
                )
                .await
                .change_context(errors::ApiErrorResponse::PaymentNotFound)
                .attach_printable("failed to fetch payment intent to resolve the active attempt")?;
            let active_attempt_id = payment_intent.active_attempt_id.clone().ok_or(report!(
                errors::ApiErrorResponse::GenericNotFoundError {
                    message: "Succeeded recovery intent has no active attempt to sync".to_owned(),
                }
            ))?;

            let psync_task = PSYNC_WORKFLOW;
            let psync_process_tracker_id =
                active_attempt_id.get_psync_revenue_recovery_id(psync_task, runner);

            let psync_pt = match db
                .find_process_by_id(&psync_process_tracker_id)
                .await
                .change_context(errors::ApiErrorResponse::InternalServerError)
                .attach_printable("error retrieving the psync process tracker id")?
            {
                // PSYNC task already present -> reset it so the consumer re-runs it.
                Some(existing_psync) => {
                    let pt_update = storage::ProcessTrackerUpdate::Update {
                        name: existing_psync.name.clone(),
                        tracking_data: Some(existing_psync.tracking_data.clone()),
                        // For business_status and status, use the values from the
                        // request if provided, otherwise retain the existing values
                        // on the task. Note: to re-run a finished PSYNC task the
                        // caller must pass a runnable status explicitly.
                        business_status: request_retrigger.business_status.clone(),
                        status: request_retrigger.status,
                        updated_at: Some(common_utils::date_time::now()),
                        retry_count: Some(existing_psync.retry_count + 1),
                        // Use the schedule time from the request if provided,
                        // otherwise retain the existing schedule time on the task.
                        schedule_time: request_retrigger.schedule_time,
                    };
                    db.update_process(existing_psync, pt_update)
                        .await
                        .change_context(errors::ApiErrorResponse::GenericNotFoundError {
                            message: "Failed to update the psync process tracker".to_owned(),
                        })?
                }
                // No PSYNC task (record-back originally failed inside EXECUTE) -> insert one.
                None => {
                    insert_psync_pcr_task_to_pt(
                        tracking_data.billing_mca_id.clone(),
                        db,
                        tracking_data.merchant_id.clone(),
                        tracking_data.global_payment_id.clone(),
                        tracking_data.profile_id.clone(),
                        active_attempt_id.clone(),
                        tracking_data.prev_attempt_error_code,
                        runner,
                        tracking_data.revenue_recovery_retry,
                        state.conf.application_source,
                        tracking_data.static_ladder_progress.clone(),
                    )
                    .await?
                }
            };

            let response = revenue_recovery::RevenueRecoveryResponse {
                id: psync_pt.id,
                name: psync_pt.name,
                schedule_time_for_payment: None,
                schedule_time_for_psync: psync_pt.schedule_time,
                status: psync_pt.status,
                business_status: psync_pt.business_status,
            };
            Ok(ApplicationResponse::Json(response))
        }
        IntentStatus::Cancelled
        | IntentStatus::CancelledPostCapture
        | IntentStatus::Processing
        | IntentStatus::RequiresCustomerAction
        | IntentStatus::RequiresMerchantAction
        | IntentStatus::RequiresPaymentMethod
        | IntentStatus::RequiresConfirmation
        | IntentStatus::RequiresCapture
        | IntentStatus::PartiallyCaptured
        | IntentStatus::PartiallyCapturedAndCapturable
        | IntentStatus::PartiallyAuthorizedAndRequiresCapture
        | IntentStatus::PartiallyCapturedAndProcessing
        | IntentStatus::Conflicted
        | IntentStatus::Expired
        | IntentStatus::Review => 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: &GlobalPaymentId,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    platform: &domain::Platform,
    active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
) -> Result<Option<ApplicationResponse<PaymentsResponse>>, sch_errors::ProcessTrackerError> {
    match active_payment_attempt_id {
        Some(_) => {
            let payment_response = api::call_psync_api(
                state,
                payment_intent_id,
                revenue_recovery_payment_data,
                false,
                false,
            )
            .await?;
            let payments_response = payment_response.generate_response(
                state,
                None,
                None,
                None,
                platform,
                &revenue_recovery_payment_data.profile,
                None,
            )?;

            Ok(Some(payments_response))
        }
        None => Ok(None),
    }
}

// This function can be implemented to reset the connector transmission and active attempt ID
// before pushing to the execute workflow.
pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow(
    state: &SessionState,
    payment_intent: &PaymentIntent,
    revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
    active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
) -> Result<Option<()>, sch_errors::ProcessTrackerError> {
    let mut revenue_recovery_metadata = payment_intent
        .feature_metadata
        .as_ref()
        .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
        .get_required_value("Payment Revenue Recovery Metadata")?
        .convert_back();
    match (active_payment_attempt_id, &payment_intent.status) {
        // No active attempt OR status is PartiallyCaptured - return None
        (None, _) | (Some(_), IntentStatus::PartiallyCaptured) => Ok(None),

        // Has active attempt and status is not PartiallyCaptured - proceed with update
        (Some(_), _) => {
            // update the connector payment transmission field to Unsuccessful and unset active attempt id
            revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
                enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
            );

            let payment_update_req =
            api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
                payment_intent
                    .feature_metadata
                    .clone()
                    .unwrap_or_default()
                    .convert_back()
                    .set_payment_revenue_recovery_metadata_using_api(
                        revenue_recovery_metadata.clone(),
                    ),
                enums::UpdateActiveAttempt::Unset,
            );
            logger::info!(
                "Call made to payments update intent api , with the request body {:?}",
                payment_update_req
            );
            Box::pin(api::update_payment_intent_api(
                state,
                payment_intent.id.clone(),
                revenue_recovery_payment_data.get_merchant_context(),
                payment_update_req,
            ))
            .await
            .change_context(errors::RecoveryError::PaymentCallFailed)?;

            Ok(Some(()))
        }
    }
}

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))
}

/// 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::ProcessorKeyStore,
    storage_scheme: domain::ProcessorStorageScheme,
    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.inner().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>,
    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 is_terminal_calculate_status(&cal_biz_status) => {
            RecoveryStatus::Terminated
        }

        // Default fallback
        _ => default_fallback(),
    }
}

/// The recovery status of an invoice whose retries the merchant triggers. No job tracks it, so
/// what the merchant was last told says where it stands.
fn map_external_trigger_recovery_status(
    next_retry: common_types::payments::RecoveryNextRetry,
) -> RecoveryStatus {
    use common_types::payments::RecoveryNoRetryReason;

    match next_retry.reason {
        None => RecoveryStatus::Scheduled,
        Some(reason) => match reason {
            RecoveryNoRetryReason::Recovered => RecoveryStatus::Recovered,
            RecoveryNoRetryReason::Monitoring | RecoveryNoRetryReason::BelowRetryThreshold => {
                RecoveryStatus::Monitoring
            }
            RecoveryNoRetryReason::RetriesExhausted
            | RecoveryNoRetryReason::GracePeriodExpired
            | RecoveryNoRetryReason::HardDeclined
            | RecoveryNoRetryReason::Cancelled => RecoveryStatus::Terminated,
        },
    }
}

pub fn map_recovery_status(
    intent_status: IntentStatus,
    calculate_workflow: Option<&ProcessTrackerStorage>,
    execute_workflow: Option<&ProcessTrackerStorage>,
    attempt_count: i16,
    max_retry_threshold: i16,
    external_trigger_next_retry: Option<common_types::payments::RecoveryNextRetry>,
) -> 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,
            || match external_trigger_next_retry {
                Some(next_retry) => map_external_trigger_recovery_status(next_retry),
                None if attempt_count > max_retry_threshold => RecoveryStatus::Terminated,
                None => 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::Succeeded,
        IntentStatus::Processing | IntentStatus::PartiallyCapturedAndProcessing => {
            RecoveryStatus::Processing
        }
        IntentStatus::Cancelled => RecoveryStatus::Cancelled,
        IntentStatus::CancelledPostCapture
        | IntentStatus::Conflicted
        | IntentStatus::Expired
        | IntentStatus::Review => RecoveryStatus::Terminated,

        IntentStatus::RequiresCustomerAction
        | IntentStatus::RequiresMerchantAction
        | IntentStatus::RequiresPaymentMethod
        | IntentStatus::RequiresConfirmation
        | IntentStatus::RequiresCapture
        | IntentStatus::PartiallyAuthorizedAndRequiresCapture => RecoveryStatus::Monitoring,
    }
}

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,
        payment_intent.get_external_trigger_next_retry(),
    );

    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),
        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),
    }
}

#[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);
    }

    #[test]
    fn recovery_status_without_workflows_follows_the_intent() {
        for (intent_status, attempt_count, expected) in [
            (IntentStatus::Succeeded, 1, "succeeded"),
            (IntentStatus::Cancelled, 1, "cancelled"),
            (IntentStatus::CancelledPostCapture, 1, "terminated"),
            (IntentStatus::RequiresPaymentMethod, 1, "monitoring"),
            (IntentStatus::Failed, 3, "monitoring"),
            (IntentStatus::Failed, 4, "terminated"),
        ] {
            let recovery_status =
                map_recovery_status(intent_status, None, None, attempt_count, 3, None);

            assert_eq!(
                serde_json::to_value(recovery_status).ok(),
                Some(serde_json::json!(expected)),
                "{intent_status:?} with {attempt_count} attempts"
            );
        }
    }
}