get_param('id'); $this->job_executor->pauseJob($job_id); $job = $this->job_manager->getJob($job_id); if (!$job) { return $this->jobGoneError(); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => __('Job paused successfully', 'ai-product-tools') ]); } catch (\Exception $e) { return $this->actionFailure($e, 'Job pause failed', 'job_pause_error', __('The job could not be paused.', 'ai-product-tools'), 400, $request); } } /** * Resume job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function resume_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $paused_job = $this->job_manager->getJob($job_id); $switched_job = null; if ($paused_job) { $publish_directly = 'published' === $request->get_param('contentStatus') && 'paused' === $paused_job->status && 'draft' === JobEntitlementGuard::contentStatus($paused_job->settings); $job_to_resume = $paused_job; if ($publish_directly) { $job_to_resume = clone $paused_job; $job_to_resume->settings = JobEntitlementGuard::withContentStatus($paused_job->settings, 'published'); } $entitlement_error = $this->runEntitlementError($job_to_resume); if (is_wp_error($entitlement_error)) { return $entitlement_error; } if (JobScheduler::isRecurringCycleDue($job_to_resume)) { $recurring_block = JobEntitlementGuard::recurringBlock(JobEntitlementGuard::CONTEXT_RUN); if (null !== $recurring_block) { return JobEntitlementGuard::restError($recurring_block); } } if ($publish_directly) { if (!$this->job_manager->updateJobSettings((int) $paused_job->id, $job_to_resume->settings)) { return new WP_Error( 'job_resume_error', __('The job could not be switched to Replace Live Content, so it stays paused.', 'ai-product-tools'), ['status' => 500] ); } $this->logger->info((int) $paused_job->id, 'Switched to Replace Live Content on resume: results now replace live product content without a review step'); $switched_job = $paused_job; } } try { $this->job_executor->resumeJob($job_id); } catch (\Exception $e) { if (null !== $switched_job) { $this->undoResumeSwitch($switched_job); } throw $e; } $job = $this->job_manager->getJob($job_id); if (!$job) { return $this->jobGoneError(); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => __('Job resumed successfully', 'ai-product-tools') ]); } catch (\Exception $e) { return $this->actionFailure($e, 'Job resume failed', 'job_resume_error', __('The job could not be resumed.', 'ai-product-tools'), 400, $request); } } /** * Put back the settings resume_job() switched for a resume the executor * then refused. JobExecutor::resumeJob() refuses before its status write, * so the job is still paused and keeps sending its results to To review. * * @param AutomationJob $job The job as read before the switch. */ private function undoResumeSwitch(AutomationJob $job): void { $settings = is_array($job->settings) ? $job->settings : []; if ($this->job_manager->updateJobSettings((int) $job->id, $settings)) { $this->logger->info((int) $job->id, 'Switch to Replace Live Content undone: the job was not resumed and keeps sending its results to To review'); return; } $this->logger->error((int) $job->id, 'Switch to Replace Live Content could not be undone after the refused resume: the job stays set to Replace Live Content'); } /** * Stop job (cancel execution) * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function stop_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $this->job_executor->cancelJob($job_id); $job = $this->job_manager->getJob($job_id); if (!$job) { return $this->jobGoneError(); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => __('Job stopped successfully', 'ai-product-tools') ]); } catch (\Exception $e) { return $this->actionFailure($e, 'Job stop failed', 'job_stop_error', __('The job could not be stopped.', 'ai-product-tools'), 400, $request); } } /** * Manually trigger a job for testing * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response object */ public function trigger_job(WP_REST_Request $request) { try { $job_id = (int) $request->get_param('id'); $rl = $this->check_automation_rate_limit('trigger_job_' . $job_id, AutomationConstants::RATE_LIMIT_TRIGGER_JOB); if (is_wp_error($rl)) { return $rl; } $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404] ); } if (in_array($job->status, ['completed'], true)) { return new WP_Error( 'trigger_invalid_state', sprintf( /* translators: %s: current job status. */ __('Cannot trigger job in status: %s', 'ai-product-tools'), $job->status ), ['status' => 400] ); } $entitlement_error = $this->runEntitlementError($job); if (is_wp_error($entitlement_error)) { return $entitlement_error; } if ('running' !== $job->status && $this->job_manager->isAtConcurrentJobCap()) { return new WP_Error( 'max_concurrent_jobs', sprintf( /* translators: %d: maximum number of automation jobs that may run at once. */ __('%d automation jobs are already running, the maximum allowed at once. Please try again in a few minutes.', 'ai-product-tools'), AutomationConstants::MAX_CONCURRENT_JOBS ), ['status' => 429] ); } $starts_recurring_cycle = in_array($job->status, ['ready', 'failed'], true) && JobEntitlementGuard::isRecurring($job->schedule_config) && (empty($job->started_at) || 0 === $this->job_manager->countOpenJobProducts($job_id)); $awaits_first_cycle_pool = 'preparing' === $job->status && JobEntitlementGuard::isRecurring($job->schedule_config) && empty($job->started_at); if ($starts_recurring_cycle || $awaits_first_cycle_pool) { $recurring_block = JobEntitlementGuard::recurringBlock(JobEntitlementGuard::CONTEXT_RUN); if (null !== $recurring_block) { return JobEntitlementGuard::restError($recurring_block); } } if ($job->status === 'failed') { if (! $this->acquireJobCountLock()) { return $this->jobCountLockBusyError(); } try { $cap_error = $this->enforceJobCountCap(); if (is_wp_error($cap_error)) { return $cap_error; } if (! $this->jobCountLockStillHeld()) { return $this->jobCountLockBusyError(); } $revived = $this->job_manager->transitionJobStatus((int) $job_id, 'ready', ['failed', 'ready']); if (AutomationJobManager::TRANSITION_LOST === $revived) { return new WP_Error( 'aipt_job_changed', __('The job changed while you were starting it. Reload it and try again.', 'ai-product-tools'), ['status' => 409] ); } if (AutomationJobManager::TRANSITION_ERROR === $revived) { return new WP_Error( 'trigger_failed', __('The job could not be started.', 'ai-product-tools'), ['status' => 500] ); } } finally { $this->releaseJobCountLock(); } $job = $this->job_manager->getJob($job_id); if (!$job) { return $this->jobGoneError(); } } if ($starts_recurring_cycle || $awaits_first_cycle_pool) { /** * Make a waiting recurring job's next cycle due now (a manual Start). * * The Premium RecurringCycleService is the sole registrant. * * @since 2.8.0 * * @param int $job_id Job ID. */ do_action('aipt_automation_trigger_recurring_cycle', $job_id); } if (! JobEntitlementGuard::isRecurring($job->schedule_config) && ! $this->job_manager->setJobNextRun($job_id, gmdate('Y-m-d H:i:s')) ) { return new WP_Error( 'trigger_failed', __('The job could not be marked to run now.', 'ai-product-tools'), ['status' => 500] ); } $hook = JobRunHook::HOOK; $base = time() + AutomationConstants::TRIGGER_EXECUTION_DELAY; $scheduled_ts = null; for ($i = 0; $i < AutomationConstants::TRIGGER_EXECUTION_ATTEMPTS; $i++) { $ts = $base + $i; $ok = JobRunHook::schedule((int) $job_id, $ts); if ($ok) { $scheduled_ts = $ts; break; } } if ($scheduled_ts === null) { $existing = JobRunHook::next_run((int) $job_id); if ($existing) { $unscheduled = JobRunHook::unschedule((int) $job_id, (int) $existing); $this->logger->info($job_id, 'Trigger: unscheduled existing event to requeue earlier', [ 'existing' => gmdate('Y-m-d H:i:s', $existing), 'unscheduled' => (bool) $unscheduled, ]); for ($i = 0; $i < AutomationConstants::TRIGGER_EXECUTION_ATTEMPTS; $i++) { $ts = time() + AutomationConstants::TRIGGER_EXECUTION_DELAY + $i; $ok = JobRunHook::schedule((int) $job_id, $ts); if ($ok) { $scheduled_ts = $ts; break; } } } } if ($scheduled_ts === null) { return new WP_Error( 'trigger_failed', __('The job run could not be scheduled.', 'ai-product-tools'), ['status' => 500] ); } if (defined('AIPT_DEV_SYNC_EXECUTION') && AIPT_DEV_SYNC_EXECUTION) { try { \AIPT\Api\AutomationJobs\JobExecutionHandler::execute_job_callback($job_id); } catch (\Exception $e) { Logger::error('automation', 'Dev synchronous execution failed', ['job_id' => (int) $job_id, 'error' => $e->getMessage()]); } } JobScheduler::spawnDueCron(); if ($awaits_first_cycle_pool) { return new WP_REST_Response([ 'success' => true, 'pool_pending' => true, 'message' => __('The product list is still being built. This job will start as soon as it is ready.', 'ai-product-tools'), 'job_id' => $job_id, 'hook' => $hook, 'scheduled_time' => gmdate('Y-m-d H:i:s', $scheduled_ts) ]); } return new WP_REST_Response([ 'success' => true, 'scheduled_only' => ! (defined('AIPT_DEV_SYNC_EXECUTION') && AIPT_DEV_SYNC_EXECUTION), 'message' => __('Job scheduled for background execution', 'ai-product-tools'), 'job_id' => $job_id, 'hook' => $hook, 'scheduled_time' => gmdate('Y-m-d H:i:s', $scheduled_ts) ]); } catch (\Exception $e) { return $this->failure($e, 'Job trigger failed', 'trigger_error', __('The job could not be started.', 'ai-product-tools'), 500, ['job_id' => (int) $request->get_param('id')]); } } /** * Create a new job that retries only the failed products from the source job. * * Copies the source job's settings, tool_type and schedule_config, overrides * the product filter to target only the failed product IDs, then creates and * schedules the new job through the standard creation pipeline. * * @param WP_REST_Request $request Request object containing source job ID * @return WP_REST_Response|WP_Error New job data or error */ public function retry_failed_products(WP_REST_Request $request) { $rl = $this->check_automation_rate_limit('retry_failed', AutomationConstants::RATE_LIMIT_RETRY_FAILED); if (is_wp_error($rl)) { return $rl; } if (! $this->acquireJobCountLock()) { return $this->jobCountLockBusyError(); } try { $cap_error = $this->enforceJobCountCap(); if (is_wp_error($cap_error)) { return $cap_error; } global $wpdb; $source_job_id = (int) $request->get_param('id'); $source_job = $this->job_manager->getJob($source_job_id); if (!$source_job) { return new WP_Error( 'job_not_found', __('Source job not found', 'ai-product-tools'), ['status' => 404] ); } $terminalStatuses = array( 'completed', 'failed' ); $jobStatus = $source_job->status; if ( ! in_array( $jobStatus, $terminalStatuses, true ) ) { return new WP_Error( 'job_not_terminal', sprintf( /* translators: %s: current job status. */ __('Cannot retry job in "%s" status. Job must be completed or failed.', 'ai-product-tools'), $jobStatus ), array( 'status' => 400 ) ); } $failed_ids = $this->job_manager->getFailedProductIdsByJobId($source_job_id); if (empty($failed_ids)) { return new WP_Error( 'no_failed_products', __('No failed products found in this job', 'ai-product-tools'), ['status' => 400] ); } $settings = is_array($source_job->settings) ? $source_job->settings : []; $retry_filter = ['includeIds' => implode(',', array_map('absint', $failed_ids))]; $source_filter = is_array($source_job->product_filter) ? $source_job->product_filter : []; $source_status = JobEntitlementGuard::productStatus($source_filter); if (JobEntitlementGuard::DEFAULT_PRODUCT_STATUS !== $source_status) { $retry_filter['status'] = $source_status; } $job_data = [ 'name' => sanitize_text_field($source_job->name) . ' (Retry)', 'description' => sprintf('Retry of %d failed products from job #%d', count($failed_ids), $source_job_id), 'tool_type' => $source_job->tool_type, 'settings' => $settings, 'schedule_config' => ['type' => 'once'], 'product_filter' => $retry_filter, 'total_products' => count($failed_ids), 'created_by' => get_current_user_id(), ]; $job = new AutomationJob($job_data); $capability_block = $this->customPromptsCapabilityBlock(is_array($job->settings) ? $job->settings : [], null); if (is_wp_error($capability_block)) { return $capability_block; } $entitlement_error = $this->runEntitlementError($job); if (is_wp_error($entitlement_error)) { return $entitlement_error; } $validation_errors = $job->validate(); if (!empty($validation_errors)) { return new WP_Error( 'job_validation_failed', __('The retry job could not be created because its settings are not valid.', 'ai-product-tools'), ['status' => 400, 'errors' => $validation_errors] ); } if (! $this->jobCountLockStillHeld()) { return $this->jobCountLockBusyError(); } $new_job_id = $this->job_manager->createJob($job); if (!$new_job_id) { return new WP_Error( 'job_creation_failed', __('Failed to create retry job', 'ai-product-tools'), ['status' => 500] ); } $persisted_job = $this->job_manager->getJob($new_job_id); if (!$persisted_job) { return new WP_Error( 'job_creation_failed', __('Failed to load the created job', 'ai-product-tools'), ['status' => 500] ); } $this->job_scheduler->scheduleJob($persisted_job); $created_job = $this->job_manager->getJob($new_job_id); if (!$created_job) { return $this->jobGoneError(true); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($created_job), 'message' => sprintf( /* translators: %d: number of failed products. */ __('Retry job created with %d failed products', 'ai-product-tools'), count($failed_ids) ), 'source_job_id' => $source_job_id, 'failed_count' => count($failed_ids), ], 201); } catch (\Exception $e) { if ($e instanceof JobValidationException) { return $this->validationFailure($e, __('The retry job could not be created because its settings are not valid.', 'ai-product-tools')); } return $this->failure($e, 'Retry of failed products failed', 'retry_failed_error', __('The retry job could not be created.', 'ai-product-tools'), 500, ['source_job_id' => (int) $request->get_param('id')]); } finally { $this->releaseJobCountLock(); } } }