job_manager = $job_manager; $this->job_executor = $job_executor; $this->job_scheduler = $job_scheduler; $this->logger = $logger; } /** * Register REST API routes */ public function register_routes() { register_rest_route($this->namespace, '/' . $this->rest_base, [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'create_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => $this->get_create_job_args() ]); register_rest_route($this->namespace, '/' . $this->rest_base, [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_jobs'], 'permission_callback' => [$this, 'check_permissions'], 'args' => $this->get_list_jobs_args() ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_job'], 'permission_callback' => [$this, 'check_permissions'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)', [ 'methods' => WP_REST_Server::EDITABLE, 'callback' => [$this, 'update_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => $this->get_update_job_args() ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)', [ 'methods' => WP_REST_Server::DELETABLE, 'callback' => [$this, 'delete_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/pause', [ 'methods' => WP_REST_Server::EDITABLE, 'callback' => [$this, 'pause_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/resume', [ 'methods' => WP_REST_Server::EDITABLE, 'callback' => [$this, 'resume_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/stop', [ 'methods' => WP_REST_Server::EDITABLE, 'callback' => [$this, 'stop_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/logs', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_job_logs'], 'permission_callback' => [$this, 'check_permissions'], 'args' => $this->get_job_logs_args() ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/filter-options', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_filter_options'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/test', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'test_endpoint'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/estimate-products', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'estimate_products'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'filters' => [ 'type' => 'object', 'required' => false, 'default' => [], ], 'use_saved_settings' => [ 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ], ], ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/trigger', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'trigger_job'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'force' => [ 'type' => 'boolean', 'default' => false, 'required' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ], ], ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\d+)/retry-failed', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'retry_failed_products'], 'permission_callback' => [$this, 'check_permissions_write'] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\\d+)/monitor', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_job_monitor'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P\\d+)/products', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'get_job_products'], 'permission_callback' => [$this, 'check_permissions'] ]); register_rest_route($this->namespace, '/' . $this->rest_base . '/process', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'process_jobs'], 'permission_callback' => [$this, 'check_permissions_write'] ]); } /** * Free-scope job-count cap (G9): enforced UNCONDITIONALLY, with NO license * check. The premium JobQuotaService raises the filter; on a free build it * is unregistered so FREE_MAX_JOBS (1) stands. Grandfathered sites keep * their existing jobs (T4.4 preserves them) but new creation is still * capped — a 3-job legacy site cannot add a 4th. Returns a 403 carrying * applied_free_defaults so the UI can show the "Business plan adds multiple * jobs" teaser (Guideline 9), or null when creation may proceed. * * Shared by create_job() and retry_failed_products(): both create a job, * so both must honour the cap. * * @return WP_Error|null */ private function enforceJobCountCap() { $max_jobs = (int) apply_filters('aipt_max_automation_jobs', self::FREE_MAX_JOBS); $active_jobs = (int) $this->job_manager->getJobCount([ 'status' => array_values(array_diff(AutomationJob::VALID_STATUSES, ['completed', 'failed'])), ]); if ($max_jobs > 0 && $active_jobs >= $max_jobs) { return PlanDenial::error( 'multipleJobs', PlanDenial::PLAN_BUSINESS, sprintf( /* translators: %d: number of automation jobs the current plan allows. */ _n( 'Your plan includes %d automation job. Business plan adds more jobs.', 'Your plan includes %d automation jobs. Business plan adds more jobs.', $max_jobs, 'ai-product-tools' ), $max_jobs ), 'aipt_job_limit_reached', [ 'applied_free_defaults' => true, 'max_jobs' => $max_jobs, ] ); } return null; } /** * Acquire the job-count-cap lock. Callers must hold this for the whole * count-check + insert critical section and release it in a `finally` * block regardless of outcome — the count-then-create race this closes * (two concurrent requests both reading $active_jobs below the cap * before either inserts) only disappears if the actual `createJob()` * call happens while the lock is held, not just the count read. * * Uses add_option() for atomicity (CodeRabbit finding, Round 3): the * prior get_transient()+set_transient() pair was itself a * check-then-act race — two concurrent requests could both read "no * lock" before either wrote one, defeating the very lock this method * exists to provide. add_option() is a single atomic INSERT guarded by * the options table's UNIQUE key on option_name (the same primitive * acquireBrowserLock() above uses), so exactly one concurrent caller * wins. * * @return bool True when the lock was acquired. */ private function acquireJobCountLock(): bool { $expires_at = time() + self::JOB_COUNT_LOCK_TTL; if (add_option(self::JOB_COUNT_LOCK_KEY, $expires_at, '', 'no')) { return true; } $existing_expiry = (int) get_option(self::JOB_COUNT_LOCK_KEY); if ($existing_expiry > 0 && $existing_expiry < time()) { delete_option(self::JOB_COUNT_LOCK_KEY); return add_option(self::JOB_COUNT_LOCK_KEY, $expires_at, '', 'no'); } return false; } /** * Release the job-count-cap lock. * * @return void */ private function releaseJobCountLock(): void { delete_option(self::JOB_COUNT_LOCK_KEY); } /** * Apply the draft-review gate to a content settings payload. * * A newly requested 'draft' without draft-review access is rejected with a * reason-aware denial instead of being rewritten to 'published'. A stored * status the update did not change is left alone. Only a missing status * with a definitive plan denial falls back to the Free default, flagged * with _draft_coerced. * * @param array $content_settings Raw content settings. * @param string|null $stored_status Stored status on update, null on create. * @return array|WP_Error Content settings with a canonical status, or the rejection. */ private function withDraftReviewStatus(array $content_settings, ?string $stored_status = null) { return JobEntitlementGuard::resolveDraftStatusWrite($content_settings, $stored_status); } /** * Coerce a recurring cadence to a single run when the current plan * cannot actually run it. * * daily/weekly/monthly next-runs are owned by the Business-only * RecurringScheduleService. `has_filter('aipt_calculate_next_run')` is * NOT the right gate here: RecurringScheduleService::init() registers * that filter for ANY premium build (Pro included), while * RecurringScheduleService::calculate() itself gates the Business-only * `recurringSchedule` entitlement and returns the untouched value (null) * for Pro. A grandfathered-Pro-only site would therefore pass this * has_filter() check, skip coercion, and save a daily/weekly/monthly * cadence that can never compute a next_run — the job silently never * re-arms. Use the G9 filter-bridge instead (false default; Premium * registers the real entitlement-aware answer), so this check reflects * effective access, not mere filter registration. * * A newly selected recurring cadence without that access is rejected with a * reason-aware denial instead of being rewritten to 'once'; a stored * cadence the update did not change is left alone (it simply does not * re-arm while the entitlement is missing). * * @param array $schedule_config Raw schedule config from the request. * @param array|null $stored Stored schedule config on update, null on create. * @return array|WP_Error Schedule config, or the rejection. */ private function coerceUnsupportedCadence(array $schedule_config, ?array $stored = null) { $block = JobEntitlementGuard::recurringWriteBlock($schedule_config, $stored); return null === $block ? $schedule_config : JobEntitlementGuard::restError($block); } /** * Whether a job's settings select the "Custom prompts (Advanced)" * structure choice. * * @param array $settings Job settings. * @return bool */ private static function isAdvancedMode(array $settings): bool { return isset($settings['blueprint']['mode']) && 'advanced' === $settings['blueprint']['mode']; } /** * The four legacy flat prompt-override keys a pre-content-structure * client, or a job saved before prompts moved to the nested shape, * may still submit or store, alongside (never both at once in * practice) the nested settings.prompts.{short,full} shape. * OptionsTranslator::translate() (around lines 316-338, pre-existing) * still converts these into real prompts for Description 'advanced' * jobs at run time, so every method in this file that needs to know * "does this job carry a raw prompt override" must recognize both * shapes — see hasNonEmptyPrompts(). * * @var string[] */ private const LEGACY_FLAT_PROMPT_KEYS = [ 'short_system_prompt', 'short_user_prompt', 'full_system_prompt', 'full_user_prompt', ]; /** * Whether settings carry any non-empty raw prompt override text, in * EITHER shape a job's settings may hold it: the nested shape * (settings.prompts.{short,full}.custom_prompt (2.8.1), or a carried- * over system_prompt/user_prompt pair — the same shape and definition * OptionsTranslator::hasLegacyPrompts() reads at run time via * CustomPrompts::runOverride(), duplicated here rather than called * since that method is private), OR the four legacy flat keys * (self::LEGACY_FLAT_PROMPT_KEYS). This is the SINGLE canonical * "does this job carry a raw prompt override" check for this * controller: the write gate (customPromptsCapabilityBlock(), and in * turn create_job(), update_job(), retry_failed_products()), * samePrompts(), isStoredAdvanced() and redactPromptsForResponse() all * call this one helper rather than re-deriving either shape * themselves. * * @param array $settings Job settings. * @return bool */ private static function hasNonEmptyPrompts(array $settings): bool { $prompts = isset($settings['prompts']) && is_array($settings['prompts']) ? $settings['prompts'] : null; foreach (CustomPrompts::types() as $type) { if (null !== CustomPrompts::runOverride($prompts, $type)) { return true; } } foreach (self::LEGACY_FLAT_PROMPT_KEYS as $flat_key) { if ('' !== trim((string) ($settings[$flat_key] ?? ''))) { return true; } } return false; } /** * Whether two settings arrays carry the same raw prompt text (trimmed), * ignoring everything else about either shape — covers the nested * shape (including its 2.8.1 custom_prompt field) AND the four legacy * flat keys (self::LEGACY_FLAT_PROMPT_KEYS), so a change to any of * them counts as a change. * * @param array $a Settings. * @param array $b Settings. * @return bool */ private static function samePrompts(array $a, array $b): bool { $normalize = static function (array $settings): array { $prompts = isset($settings['prompts']) && is_array($settings['prompts']) ? $settings['prompts'] : []; $normalized = []; foreach (['short', 'full'] as $key) { $pair = isset($prompts[$key]) && is_array($prompts[$key]) ? $prompts[$key] : []; $normalized[$key] = [ 'custom_prompt' => trim((string) ($pair['custom_prompt'] ?? '')), 'system_prompt' => trim((string) ($pair['system_prompt'] ?? '')), 'user_prompt' => trim((string) ($pair['user_prompt'] ?? '')), ]; } foreach (self::LEGACY_FLAT_PROMPT_KEYS as $flat_key) { $normalized[$flat_key] = trim((string) ($settings[$flat_key] ?? '')); } return $normalized; }; return $normalize($a) === $normalize($b); } /** * Re-assert a stored key that a capability-limited user's request must * not actually change: copies it from $source, or removes it from * $target when $source never had it either. * * @param array $target Settings about to be stored. * @param array $source Settings to preserve the key from (the job's * settings BEFORE this write). * @param string $key Key to preserve. * @return array $target with $key re-asserted from $source. */ private static function withPreservedKey(array $target, array $source, string $key): array { if (array_key_exists($key, $source)) { $target[$key] = $source[$key]; } else { unset($target[$key]); } return $target; } /** * Whether STORED job settings are "stored-advanced": already running * on raw custom prompts rather than content structure, so a user * without manage_aipt_settings must not be allowed to switch this job * onto the Blueprint path either — that switch needs the same * capability as switching a job INTO custom prompts. * * stored-advanced = settings.blueprint.mode is 'advanced', OR there is * no settings.blueprint key at all and the settings carry a raw * prompt override in either shape (nested or * self::LEGACY_FLAT_PROMPT_KEYS). A job that predates content * structure has no blueprint key and keeps running on whatever custom * prompts it has (BlueprintIntegration::executionPath()'s * legacyPrompts fallback); this mirrors that run-time fallback here so * the write gate cannot be bypassed on a job content structure never * touched. * * @param array $stored_settings The job's settings BEFORE this write. * @return bool */ private static function isStoredAdvanced(array $stored_settings): bool { if (self::isAdvancedMode($stored_settings)) { return true; } if (array_key_exists('blueprint', $stored_settings)) { return false; } return self::hasNonEmptyPrompts($stored_settings); } /** * Capability gate for Automation's "Custom prompts (Advanced)" per-job * choice. Every sibling Advanced doorway in the * plugin (BlueprintChip's advancedPromptsUrl, PromptSettingsNavButton) * already requires manage_aipt_settings; this brings the job wizard in * line. A user holding manage_aipt_settings keeps today's behavior * exactly — this returns null immediately for them. * * @param array $settings Candidate settings about to be * stored (create and any * duplicate/clone/import path: the * new job's settings; update: the * request's replacement settings). * @param array|null $stored_settings Null on create and on any * duplicate/clone/import path (no * prior job to compare against); * the job's settings BEFORE this * write on update, so a stored * custom-prompts job resubmitted * unchanged (e.g. this user only * edited its schedule) is left * alone — mirroring * coerceUnsupportedCadence() and * JobEntitlementGuard's write * guards elsewhere in this file. * @return WP_Error|null */ private function customPromptsCapabilityBlock(array $settings, ?array $stored_settings) { if (current_user_can('manage_aipt_settings')) { return null; } $requested_advanced = self::isAdvancedMode($settings); $requested_has_prompts = self::hasNonEmptyPrompts($settings); if (null === $stored_settings) { return ($requested_advanced || $requested_has_prompts) ? self::customPromptsCapabilityError() : null; } $stored_advanced = self::isStoredAdvanced($stored_settings); $blueprint_requested = array_key_exists('blueprint', $settings); $mode_changed = $blueprint_requested && ($requested_advanced !== $stored_advanced); $prompts_changed = $requested_has_prompts && !self::samePrompts($settings, $stored_settings); return ($mode_changed || $prompts_changed) ? self::customPromptsCapabilityError() : null; } /** * @return WP_Error */ private static function customPromptsCapabilityError(): WP_Error { return new WP_Error( 'rest_forbidden', __('Only users who can manage AI Product Tools settings can use custom prompts in a job.', 'ai-product-tools'), ['status' => 403] ); } /** * Redact a job's raw prompt text for a user without manage_aipt_settings * (same gate as customPromptsCapabilityBlock()). Every sibling Advanced * doorway already hides its raw prompt fields from a user who lacks * this capability; Automation's job responses now match. Strips BOTH * prompt shapes — the nested `prompts` key and the four legacy flat * keys (self::LEGACY_FLAT_PROMPT_KEYS) — so neither can read through. * The `hasCustomPrompts` boolean (reflecting either shape, via * hasNonEmptyPrompts()) lets the UI show a locked note without the * text itself. * * @param array $settings Stored job settings. * @return array Settings safe to send to the current user. */ private static function redactPromptsForResponse(array $settings): array { if (current_user_can('manage_aipt_settings')) { return $settings; } $settings['hasCustomPrompts'] = self::hasNonEmptyPrompts($settings); unset($settings['prompts']); foreach (self::LEGACY_FLAT_PROMPT_KEYS as $flat_key) { unset($settings[$flat_key]); } return $settings; } /** * Strip the response-only `hasCustomPrompts` marker from incoming * settings before anything is stored. redactPromptsForResponse() adds * this boolean to a GET response for a user without * manage_aipt_settings so the UI can show a locked note without the * prompt text itself; the job wizard seeds its component state from * that GET response and later sends the whole settings object back on * create/update (and Duplicate, which reuses create_job()), so * without this the marker would round-trip into storage as if it were * real job data. Stripped unconditionally, for every user — it is * never legitimate input. * * @param array $settings Candidate settings from the request. * @return array $settings without the marker. */ private static function withoutHasCustomPromptsMarker(array $settings): array { unset($settings['hasCustomPrompts']); return $settings; } /** * Keep a product filter's status only when it is a paid product status * (draft, pending review, private). Anything else, including the legacy * 'all' the job form used to send, means published products and is left * out, so every stored filter has one shape for the same selection. * JobEntitlementGuard::filterWriteBlock() has already refused a paid * status this plan cannot honor. * * Applied after construction so the model has already resolved * product_filter into a real array (it nullifies empty arrays, which * would break the array response contract). * * @param mixed $product_filter Product filter. * @return mixed The filter with its canonical status. */ private static function withCanonicalProductStatus($product_filter) { if (!is_array($product_filter) || !array_key_exists('status', $product_filter)) { return $product_filter; } $status = JobEntitlementGuard::productStatus($product_filter); unset($product_filter['status']); if (JobEntitlementGuard::DEFAULT_PRODUCT_STATUS !== $status) { $product_filter['status'] = $status; } return $product_filter; } /** * Whether a job is still waiting for its first run: its product pool * is built (or building) and nothing has been processed from it yet. * * @param AutomationJob $job Job. * @return bool */ private static function isWaitingForFirstRun(AutomationJob $job): bool { return in_array($job->status, ['ready', 'preparing'], true) && 0 === (int) $job->processed_products + (int) $job->failed_products; } /** * Create a new job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function create_job(WP_REST_Request $request) { $rl = $this->check_automation_rate_limit('create_job', AutomationConstants::RATE_LIMIT_CREATE_JOB); if (is_wp_error($rl)) { return $rl; } if (! $this->acquireJobCountLock()) { return new WP_Error( 'aipt_job_limit_check_busy', __('Another job operation is in progress. Please try again.', 'ai-product-tools'), ['status' => 409] ); } try { $cap_error = $this->enforceJobCountCap(); if (is_wp_error($cap_error)) { return $cap_error; } $request_data = $request->get_json_params(); $job_data = [ 'name' => $request_data['name'] ?? '', 'description' => $request_data['description'] ?? '', 'tool_type' => $request_data['toolType'] ?? $request_data['tool_type'] ?? '', 'settings' => $request_data['settings'] ?? [], 'schedule_config' => $request_data['schedule'] ?? $request_data['schedule_config'] ?? [], 'product_filter' => $request_data['productFilter'] ?? $request_data['product_filter'] ?? [], 'total_products' => $request_data['totalProducts'] ?? $request_data['total_products'] ?? 0, 'created_by' => get_current_user_id() ]; if (is_array($job_data['settings'])) { $job_data['settings'] = self::withoutHasCustomPromptsMarker($job_data['settings']); } if (is_array($job_data['settings'])) { $content_settings = $request_data['contentSettings'] ?? $request_data['content_settings'] ?? $job_data['settings']['contentSettings'] ?? []; $resolved_content_settings = $this->withDraftReviewStatus( is_array($content_settings) ? $content_settings : [] ); if (is_wp_error($resolved_content_settings)) { return $resolved_content_settings; } $job_data['settings']['contentSettings'] = $resolved_content_settings; } if (is_array($job_data['settings'])) { $job_data['settings'] = $this->withSkipProcessedSetting($job_data['settings']); } if (is_array($job_data['settings'])) { $capability_block = $this->customPromptsCapabilityBlock($job_data['settings'], null); if (is_wp_error($capability_block)) { return $capability_block; } } if (is_array($job_data['schedule_config'])) { $job_data['schedule_config'] = $this->coerceUnsupportedCadence($job_data['schedule_config']); if (is_wp_error($job_data['schedule_config'])) { return $job_data['schedule_config']; } } if (is_array($job_data['product_filter'])) { $filter_block = JobEntitlementGuard::filterWriteBlock($job_data['product_filter'], null); if (null !== $filter_block) { return JobEntitlementGuard::restError($filter_block); } $id_list_error = self::invalidProductIdListError($job_data['product_filter']); if (null !== $id_list_error) { return $id_list_error; } } $job = new AutomationJob($job_data); if (is_array($job->settings) && isset($job->settings['blueprint'])) { $resolved_blueprint_settings = BlueprintJobPinning::resolveForJob( (string) $job->tool_type, $job->settings, get_current_user_id() ); if (is_wp_error($resolved_blueprint_settings)) { return $resolved_blueprint_settings; } $job->settings = $resolved_blueprint_settings; } $job->product_filter = self::withCanonicalProductStatus($job->product_filter); $job_data['total_products'] = $this->calculateTotalProducts($job->product_filter ?? []); $job->total_products = $job_data['total_products']; $validation_errors = $job->validate(); if (!empty($validation_errors)) { return new WP_Error( 'job_validation_failed', 'Job validation failed', [ 'status' => 400, 'errors' => $validation_errors ] ); } $job_id = $this->job_manager->createJob($job); if (!$job_id) { return new WP_Error( 'job_creation_failed', 'Failed to create job', ['status' => 500] ); } $persisted_job = $this->job_manager->getJob($job_id); if (!$persisted_job) { return new WP_Error( 'job_creation_failed', 'Failed to load the created job', ['status' => 500] ); } $this->job_scheduler->scheduleJob($persisted_job); $created_job = $this->job_manager->getJob($job_id); return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($created_job), 'message' => 'Job created successfully' ], 201); } catch (\Exception $e) { return new WP_Error( 'job_creation_error', $e->getMessage(), ['status' => 400] ); } finally { $this->releaseJobCountLock(); } } /** * Get jobs list * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response object */ public function get_jobs(WP_REST_Request $request) { try { $filters = []; if ($request->get_param('status')) { $statuses = array_filter(array_map('trim', explode(',', (string) $request->get_param('status')))); $filters['status'] = count($statuses) > 1 ? array_values($statuses) : reset($statuses); } if ($request->get_param('tool_type')) { $filters['tool_type'] = $request->get_param('tool_type'); } if ($request->get_param('created_by')) { $filters['created_by'] = $request->get_param('created_by'); } $per_page = $request->get_param('per_page') ?: 20; $page = $request->get_param('page') ?: 1; $offset = ($page - 1) * $per_page; $jobs = $this->job_manager->getJobs($filters, $per_page, $offset); $total = $this->job_manager->getJobCount($filters); $prepared_jobs = []; foreach ($jobs as $job) { $prepared_jobs[] = $this->prepare_job_for_response($job); } $response = new WP_REST_Response([ 'success' => true, 'data' => $prepared_jobs, 'pagination' => [ 'total' => $total, 'per_page' => $per_page, 'current_page' => $page, 'total_pages' => ceil($total / $per_page) ] ]); $response->header('X-WP-Total', $total); $response->header('X-WP-TotalPages', ceil($total / $per_page)); return $response; } catch (\Exception $e) { return new WP_Error( 'jobs_fetch_error', $e->getMessage(), ['status' => 500] ); } } /** * Get specific job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function get_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', 'Job not found', ['status' => 404] ); } $current_user_id = get_current_user_id(); if ((int) $job->created_by !== (int) $current_user_id && !current_user_can('manage_woocommerce')) { return new WP_Error( 'rest_forbidden', __('You do not own this job.', 'ai-product-tools'), ['status' => 403] ); } $job_data = $this->prepare_job_for_response($job); $job_data['progress_details'] = $this->job_executor->getJobProgress($job_id); $job_data['log_statistics'] = $this->logger->getLogStatistics($job_id); return new WP_REST_Response([ 'success' => true, 'data' => $job_data ]); } catch (\Exception $e) { return new WP_Error( 'job_fetch_error', $e->getMessage(), ['status' => 500] ); } } /** * Update job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function update_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', 'Job not found', ['status' => 404] ); } if ($job->isActive()) { return new WP_Error( 'job_cannot_be_updated', 'Cannot update active job', ['status' => 400] ); } if ($job->status === 'completed') { return new WP_Error( 'job_completed_not_editable', 'Cannot update a completed job', ['status' => 400] ); } $previous_settings = is_array($job->settings) ? $job->settings : []; if ($request->get_param('name')) { $job->name = $request->get_param('name'); } $tool_type = $request->get_param('tool_type'); if (!$tool_type && $request->get_param('toolType')) { $tool_type = $request->get_param('toolType'); } if ($tool_type) { $job->tool_type = sanitize_text_field($tool_type); } if ($request->get_param('description')) { $job->description = $request->get_param('description'); } if ($request->get_param('settings')) { $updated_settings = $request->get_param('settings'); if (is_array($updated_settings)) { $updated_settings = self::withoutHasCustomPromptsMarker($updated_settings); $capability_block = $this->customPromptsCapabilityBlock($updated_settings, $previous_settings); if (is_wp_error($capability_block)) { return $capability_block; } if (!current_user_can('manage_aipt_settings')) { foreach (array_merge(['prompts'], self::LEGACY_FLAT_PROMPT_KEYS) as $preserved_key) { $updated_settings = self::withPreservedKey($updated_settings, $previous_settings, $preserved_key); } } $updated_settings = $this->withSkipProcessedSetting($updated_settings); $content_settings = $updated_settings['contentSettings'] ?? []; $resolved_content_settings = $this->withDraftReviewStatus( is_array($content_settings) ? $content_settings : [], $this->storedContentStatus($job) ); if (is_wp_error($resolved_content_settings)) { return $resolved_content_settings; } $updated_settings['contentSettings'] = $resolved_content_settings; } $job->settings = $updated_settings; if (is_array($updated_settings) && isset($updated_settings['blueprint'])) { $resolved_blueprint_settings = BlueprintJobPinning::resolveForJob( (string) $job->tool_type, $job->settings, get_current_user_id(), $previous_settings ); if (is_wp_error($resolved_blueprint_settings)) { return $resolved_blueprint_settings; } $job->settings = $resolved_blueprint_settings; } } if ($request->get_param('product_filter')) { $requested_filter = $request->get_param('product_filter'); if (is_array($requested_filter)) { $filter_block = JobEntitlementGuard::filterWriteBlock( $requested_filter, is_array($job->product_filter) ? $job->product_filter : [] ); if (null !== $filter_block) { return JobEntitlementGuard::restError($filter_block); } $id_list_error = self::invalidProductIdListError($requested_filter); if (null !== $id_list_error) { return $id_list_error; } } } if ($request->get_param('schedule_config')) { $schedule_config = $request->get_param('schedule_config'); if (is_array($schedule_config)) { $schedule_config = $this->coerceUnsupportedCadence( $schedule_config, is_array($job->schedule_config) ? $job->schedule_config : [] ); if (is_wp_error($schedule_config)) { return $schedule_config; } } $job->schedule_config = $schedule_config; $this->job_scheduler->rescheduleJob($job); } $rebuild_pool = false; if ($request->get_param('product_filter')) { $stored_filter = self::withCanonicalProductStatus($job->product_filter); $job->product_filter = self::withCanonicalProductStatus($request->get_param('product_filter')); $rebuild_pool = $stored_filter != $job->product_filter && self::isWaitingForFirstRun($job); } $this->job_manager->updateJob($job); if ($rebuild_pool) { $this->job_manager->rebuildPool($job); $job = $this->job_manager->getJob($job->id) ?? $job; } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => 'Job updated successfully' ]); } catch (\Exception $e) { return new WP_Error( 'job_update_error', $e->getMessage(), ['status' => 400] ); } } /** * Delete job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function delete_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', 'Job not found', ['status' => 404] ); } if ($job->isActive() || in_array($job->status, ['preparing', 'ready'], true)) { $this->job_executor->cancelJob($job_id); } $this->job_scheduler->unscheduleJob($job_id); \AIPT\Core\Database\OrphanCleaner::on_job_deleted((int) $job_id); $this->job_manager->deleteJob($job_id); return new WP_REST_Response([ 'success' => true, 'message' => 'Job deleted successfully' ]); } catch (\Exception $e) { return new WP_Error( 'job_delete_error', $e->getMessage(), ['status' => 500] ); } } /** * Pause job * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function pause_job(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $this->job_executor->pauseJob($job_id); $job = $this->job_manager->getJob($job_id); return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => 'Job paused successfully' ]); } catch (\Exception $e) { return new WP_Error( 'job_pause_error', $e->getMessage(), ['status' => 400] ); } } /** * 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); if ($paused_job) { $entitlement_error = $this->runEntitlementError($paused_job); if (is_wp_error($entitlement_error)) { return $entitlement_error; } if (JobScheduler::isRecurringCycleDue($paused_job)) { $recurring_block = JobEntitlementGuard::recurringBlock(JobEntitlementGuard::CONTEXT_RUN); if (null !== $recurring_block) { return JobEntitlementGuard::restError($recurring_block); } } } $this->job_executor->resumeJob($job_id); $job = $this->job_manager->getJob($job_id); return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => 'Job resumed successfully' ]); } catch (\Exception $e) { return new WP_Error( 'job_resume_error', $e->getMessage(), ['status' => 400] ); } } /** * Get job logs * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function get_job_logs(WP_REST_Request $request) { try { $job_id = $request->get_param('id'); $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error( 'job_not_found', 'Job not found', ['status' => 404] ); } $current_user_id = get_current_user_id(); if ((int) $job->created_by !== (int) $current_user_id && !current_user_can('manage_woocommerce')) { return new WP_Error( 'rest_forbidden', __('You do not own this job.', 'ai-product-tools'), ['status' => 403] ); } $filters = []; if ($request->get_param('level')) { $filters['level'] = $request->get_param('level'); } elseif (!rest_sanitize_boolean($request->get_param('details'))) { $filters['exclude_level'] = 'debug'; } if ($request->get_param('type')) { $filters['type'] = $request->get_param('type'); } $filters['limit'] = $request->get_param('per_page') ?: 50; $filters['offset'] = (($request->get_param('page') ?: 1) - 1) * $filters['limit']; $logs = $this->logger->getJobLogs($job_id, $filters); $product_ids = []; foreach ($logs as $log) { if (is_array($log->context) && isset($log->context['product_id'])) { $product_ids[] = (int) $log->context['product_id']; } } $viewable_product_ids = array_values(array_filter( array_unique($product_ids), static function ($product_id) { return current_user_can('edit_post', $product_id); } )); $product_names = empty($viewable_product_ids) ? [] : (new ProductIdentityResolver())->resolve($viewable_product_ids); $prepared_logs = []; foreach ($logs as $log) { $context = is_array($log->context) ? JobLogger::redactSensitiveContext($log->context) : $log->context; if (is_array($context) && isset($context['product_id'])) { $name = $product_names[(int) $context['product_id']]['name'] ?? ''; if ($name !== '') { $context['product_name'] = $name; } } $prepared_logs[] = [ 'id' => $log->id, 'level' => $log->level, 'message' => $log->message, 'context' => $context, 'created_at' => UtcTimestamp::fromStored($log->created_at, true) ]; } return new WP_REST_Response([ 'success' => true, 'data' => $prepared_logs, 'statistics' => $this->logger->getLogStatistics($job_id) ]); } catch (\Exception $e) { return new WP_Error( 'logs_fetch_error', $e->getMessage(), ['status' => 500] ); } } /** * Get filter options for job creation * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response object */ public function get_filter_options(WP_REST_Request $request) { try { $categories = get_terms([ 'taxonomy' => 'product_cat', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 10 ]); $formatted_categories = []; foreach ($categories as $category) { $formatted_categories[] = [ 'id' => $category->term_id, 'name' => $category->name, 'count' => $category->count ]; } $tags = get_terms([ 'taxonomy' => 'product_tag', 'hide_empty' => true, 'orderby' => 'count', 'order' => 'DESC', 'number' => 10 ]); $formatted_tags = []; foreach ($tags as $tag) { $formatted_tags[] = [ 'id' => $tag->term_id, 'name' => $tag->name, 'count' => $tag->count ]; } $product_types = [ ['id' => 'simple', 'name' => 'Simple Product'], ['id' => 'variable', 'name' => 'Variable Product'], ['id' => 'grouped', 'name' => 'Grouped Product'], ['id' => 'external', 'name' => 'External/Affiliate Product'] ]; $stock_statuses = [ ['id' => 'all', 'name' => 'All Stock Statuses'], ['id' => 'instock', 'name' => 'In Stock'], ['id' => 'outofstock', 'name' => 'Out of Stock'], ['id' => 'onbackorder', 'name' => 'On Backorder'] ]; $product_statuses = [ ['id' => 'publish', 'name' => __('Published', 'ai-product-tools')], ['id' => 'draft', 'name' => __('Draft', 'ai-product-tools')], ['id' => 'pending', 'name' => __('Pending review', 'ai-product-tools')], ['id' => 'private', 'name' => __('Private', 'ai-product-tools')] ]; return new WP_REST_Response([ 'success' => true, 'data' => [ 'categories' => $formatted_categories, 'tags' => $formatted_tags, 'product_types' => $product_types, 'stock_statuses' => $stock_statuses, 'product_statuses' => $product_statuses ] ]); } catch (\Exception $e) { return new WP_Error( 'filter_options_error', $e->getMessage(), ['status' => 500] ); } } /** * Check permissions (read-only endpoints) * Requires manage_woocommerce capability. * * @return bool Permission status */ public function check_permissions() { return current_user_can('manage_woocommerce'); } /** * Check permissions for write operations. * Requires manage_woocommerce and a valid REST nonce. * * @param WP_REST_Request $request * @return bool|WP_Error */ public function check_permissions_write($request) { if (!current_user_can('manage_woocommerce')) { return new WP_Error('rest_forbidden', __('You do not have permission to manage automation jobs.', 'ai-product-tools'), ['status' => 403]); } if (\AIPT\Utils\RestNonceGuard::isCookieAuthenticated()) { $nonce = $request instanceof \WP_REST_Request ? $request->get_header('X-WP-Nonce') : ''; if (empty($nonce) && $request instanceof \WP_REST_Request) { $nonce = $request->get_param('_wpnonce'); } if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) { return new WP_Error('rest_invalid_nonce', __('Invalid or missing security nonce.', 'ai-product-tools'), ['status' => 403]); } } $job_id = (int) ($request instanceof \WP_REST_Request ? $request->get_param('id') : 0); if ($job_id > 0) { $job = $this->job_manager->getJob($job_id); if (!$job) { return new WP_Error('job_not_found', __('Job not found', 'ai-product-tools'), ['status' => 404]); } $current_user_id = get_current_user_id(); if ((int) $job->created_by !== (int) $current_user_id && !current_user_can('manage_woocommerce')) { return new WP_Error('rest_forbidden', __('You do not own this job.', 'ai-product-tools'), ['status' => 403]); } } return true; } /** * Check the shared fixed-window rate limiter for Automation endpoints. * Returns true on success or WP_Error 429 if exceeded. */ private function check_automation_rate_limit(string $scope, int $limit_per_minute) { $rate_check = $this->checkRateLimit((int) get_current_user_id(), $scope, $limit_per_minute, 60); return $rate_check['allowed'] ? true : $this->rateLimitResponse($rate_check); } /** * Prepare job for response * * @param AutomationJob $job Job object * @return array Prepared job data */ private function prepare_job_for_response(AutomationJob $job) { return [ 'id' => $job->id, 'name' => $job->name, 'description' => $job->description, 'tool_type' => $job->tool_type, 'status' => $job->status, 'progress' => $job->progress, 'total_products' => $job->total_products, 'processed_products' => $job->processed_products, 'failed_products' => $job->failed_products, 'settings' => self::redactPromptsForResponse(is_array($job->settings) ? $job->settings : []), 'schedule_config' => $job->schedule_config, 'product_filter' => $job->product_filter, 'next_run' => UtcTimestamp::fromStored($job->next_run, false), 'started_at' => UtcTimestamp::fromStored($job->started_at, true), 'completed_at' => UtcTimestamp::fromStored($job->completed_at, true), 'error_message' => $job->error_message, 'created_by' => $job->created_by, 'created_at' => UtcTimestamp::fromStored($job->created_at, true), 'updated_at' => UtcTimestamp::fromStored($job->updated_at, true), 'waiting_for_next_cycle' => JobScheduler::isWaitingForRecurringCycle($job, $this->job_manager), ]; } /** * Normalize + persist the `skipProcessed` automation setting. * * Canonicalizes the flag through rest_sanitize_boolean (the codebase's * boolean-canonicalization convention) and writes it back into the job * settings array so it is stored as a real boolean in the * aipt_automation_jobs.settings JSON. Defaults to false when absent. * * @param array $settings Raw job settings. * @return array Settings with a canonical `skipProcessed` boolean. */ private function withSkipProcessedSetting(array $settings): array { return AutomationJob::withSkipProcessedSetting($settings); } /** * Stored raw content status of a job, or null when none is stored. * * @param AutomationJob $job Stored job. * @return string|null */ private function storedContentStatus(AutomationJob $job): ?string { $settings = is_array($job->settings) ? $job->settings : []; $content_settings = isset($settings['contentSettings']) && is_array($settings['contentSettings']) ? $settings['contentSettings'] : []; return isset($content_settings['status']) && is_scalar($content_settings['status']) ? (string) $content_settings['status'] : null; } /** * Reason-aware denial when a job cannot run with its paid behavior, used * before resume, trigger and retry make a job runnable again. * * A saved filter only matters when the pool still has to be built. * * @param AutomationJob $job Job about to become runnable. * @return WP_Error|null */ private function runEntitlementError(AutomationJob $job) { if ((int) $job->total_products <= 0 && is_array($job->product_filter)) { $filter_block = JobEntitlementGuard::filterBlock($job->product_filter, JobEntitlementGuard::CONTEXT_RUN); if (null !== $filter_block) { return JobEntitlementGuard::restError($filter_block); } } $settings = is_array($job->settings) ? $job->settings : []; $translated = (new OptionsTranslator())->translate($settings, (string) $job->tool_type); $assessment = JobEntitlementGuard::assessRun($job, $translated); return null === $assessment['block'] ? null : JobEntitlementGuard::restError($assessment['block']); } /** * Get create job arguments * * @return array Arguments schema */ private function get_create_job_args() { return [ 'name' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field' ], 'description' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field' ], 'toolType' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field' ], 'tool_type' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field' ], 'settings' => [ 'required' => false, 'type' => 'object' ], 'contentSettings' => [ 'required' => false, 'type' => 'object' ], 'content_settings' => [ 'required' => false, 'type' => 'object' ], 'schedule' => [ 'required' => false, 'type' => 'object' ], 'schedule_config' => [ 'required' => false, 'type' => 'object' ], 'productFilter' => [ 'required' => false, 'type' => 'object' ], 'product_filter' => [ 'required' => false, 'type' => 'object' ], 'totalProducts' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'total_products' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint' ] ]; } /** * Get list jobs arguments * * @return array Arguments schema */ private function get_list_jobs_args() { return [ 'status' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ($param) { $statuses = array_filter(array_map('trim', explode(',', (string) $param))); if (empty($statuses)) { return false; } foreach ($statuses as $status) { if (!in_array($status, AutomationJob::VALID_STATUSES, true)) { return false; } } return true; } ], 'tool_type' => [ 'required' => false, 'type' => 'string', 'enum' => AutomationJob::VALID_TOOL_TYPES, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg' ], 'created_by' => [ 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'per_page' => [ 'required' => false, 'type' => 'integer', 'default' => 20, 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ], 'page' => [ 'required' => false, 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ] ]; } /** * Get update job arguments * * @return array Arguments schema */ private function get_update_job_args() { return [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'name' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function($param) { return empty($param) || strlen($param) <= 255; } ], 'tool_type' => [ 'required' => false, 'type' => 'string', 'enum' => AutomationJob::VALID_TOOL_TYPES, 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg' ], 'description' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field' ], 'settings' => [ 'required' => false, 'type' => 'object' ], 'schedule_config' => [ 'required' => false, 'type' => 'object' ], 'product_filter' => [ 'required' => false, 'type' => 'object' ] ]; } /** * Get job logs arguments * * @return array Arguments schema */ private function get_job_logs_args() { return [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint' ], 'level' => [ 'required' => false, 'type' => 'string', 'enum' => ['info', 'warning', 'error', 'debug'], 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg' ], 'details' => [ 'required' => false, 'type' => 'boolean', 'default' => false, 'description' => 'Include debug-level log lines when no level filter is given.', 'sanitize_callback' => 'rest_sanitize_boolean' ], 'type' => [ 'required' => false, 'type' => 'string', 'description' => 'Logical error category (AI_PROVIDER, WC_UPDATE, NETWORK, AUTH, RATE_LIMIT, VALIDATION, DB, SYSTEM)', 'sanitize_callback' => 'sanitize_text_field' ], 'per_page' => [ 'required' => false, 'type' => 'integer', 'default' => 50, 'minimum' => 1, 'maximum' => 1000, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ], 'page' => [ 'required' => false, 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg' ] ]; } /** * Calculate total products based on filter * * @param array $product_filter Product filter configuration * @return int Total products count */ private function calculateTotalProducts($product_filter) { global $wpdb; try { $pf = is_array($product_filter) ? $product_filter : []; if (!empty(JobEntitlementGuard::unhonoredFilterKeys($pf))) { return 0; } $categories = !empty($pf['categories']) && is_array($pf['categories']) ? array_values(array_filter(array_map('absint', $pf['categories']))) : []; $tags = !empty($pf['tags']) && is_array($pf['tags']) ? array_values(array_filter(array_map('absint', $pf['tags']))) : []; $include_ids_requested = ProductIdListFilter::wasRequested($pf['includeIds'] ?? null); $include_ids = ProductIdListFilter::parse($pf['includeIds'] ?? null); if ($include_ids_requested && empty($include_ids)) { return 0; } $exclude_ids_requested = ProductIdListFilter::wasRequested($pf['excludeIds'] ?? null); $exclude_ids = ProductIdListFilter::parse($pf['excludeIds'] ?? null); if ($exclude_ids_requested && empty($exclude_ids)) { return 0; } $allowed_stock = ['instock','outofstock','onbackorder']; $stock_status = !empty($pf['stockStatus']) && in_array($pf['stockStatus'], $allowed_stock, true) ? $pf['stockStatus'] : 'all'; $product_status = JobEntitlementGuard::productStatus($pf); $min_price = (isset($pf['priceRange']['min']) && $pf['priceRange']['min'] !== '' && is_numeric($pf['priceRange']['min'])) ? (float) $pf['priceRange']['min'] : null; $max_price = (isset($pf['priceRange']['max']) && $pf['priceRange']['max'] !== '' && is_numeric($pf['priceRange']['max'])) ? (float) $pf['priceRange']['max'] : null; $description_filter_conditions = $this->getDescriptionFilterConditions($pf); $default_filter_options = array( 'categories' => array(), 'tags' => array(), 'stock_status' => 'all', 'product_status' => JobEntitlementGuard::DEFAULT_PRODUCT_STATUS, ); /** * Filter automation job filter options. * * Premium module can hook here to enable advanced filtering * (categories, tags, stock status, product status) when a valid * license is present. * * @since 2.5.0 * @since 2.8.0 Added the product status. * @param array $default_filter_options Default free filter options. * @param array $categories Requested categories from filter. * @param array $tags Requested tags from filter. * @param string $stock_status Requested stock status from filter. * @param string $product_status Requested product status from filter. */ $filtered_options = apply_filters( 'aipt_automation_filter_options', $default_filter_options, $categories, $tags, $stock_status, $product_status ); $categories = is_array($filtered_options['categories'] ?? null) ? $filtered_options['categories'] : []; $tags = is_array($filtered_options['tags'] ?? null) ? $filtered_options['tags'] : []; $stock_status = is_string($filtered_options['stock_status'] ?? null) ? $filtered_options['stock_status'] : 'all'; $product_status = JobEntitlementGuard::productStatus(['status' => $filtered_options['product_status'] ?? null]); $paid_conditions = PaidFilterConditions::forGranted($categories, $tags, $stock_status); if (empty($paid_conditions['where']) && empty($include_ids) && empty($exclude_ids) && ($min_price === null) && ($max_price === null) && empty($description_filter_conditions)) { $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = %s", $product_status)); return (int) $count; } $cache_key = 'aipt_calc_total_' . md5(wp_json_encode([$paid_conditions, $include_ids, $exclude_ids, $min_price, $max_price, $description_filter_conditions, $product_status])); $cached = wp_cache_get($cache_key, 'aipt_automation_jobs'); if ($cached !== false) { return (int) $cached; } $query = " SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p WHERE p.post_type = 'product' AND p.post_status = %s "; $params = [$product_status]; foreach ($paid_conditions['where'] as $condition) { $query .= " AND {$condition}"; } $params = array_merge($params, $paid_conditions['params']); if ($min_price !== null || $max_price !== null) { $conditions = []; if ($min_price !== null) { $conditions[] = "CAST(pm.meta_value AS DECIMAL(10,2)) >= %f"; $params[] = $min_price; } if ($max_price !== null) { $conditions[] = "CAST(pm.meta_value AS DECIMAL(10,2)) <= %f"; $params[] = $max_price; } $query .= " AND p.ID IN ( SELECT post_id FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_price' AND " . implode(' AND ', $conditions) . " )"; } if (!empty($description_filter_conditions)) { $query .= ' AND (' . implode(' OR ', $description_filter_conditions) . ')'; } if (!empty($include_ids)) { $placeholders = implode(',', array_fill(0, count($include_ids), '%d')); $query .= " AND p.ID IN ({$placeholders})"; $params = array_merge($params, $include_ids); } if (!empty($exclude_ids)) { $placeholders = implode(',', array_fill(0, count($exclude_ids), '%d')); $query .= " AND p.ID NOT IN ({$placeholders})"; $params = array_merge($params, $exclude_ids); } $count = !empty($params) ? $wpdb->get_var($wpdb->prepare($query, $params)) : $wpdb->get_var($query); wp_cache_set($cache_key, (int) $count, 'aipt_automation_jobs', 300); return (int) $count; } catch (\Exception $e) { return 10; } } /** * A REST-boundary error when includeIds or excludeIds was filled in but * sanitizes to zero valid numeric product ids (e.g. a pasted SKU * instead of a numeric id). An include-only restriction with nothing * valid to include must never silently widen to the whole catalog, and * an exclusion with nothing valid to exclude matches no product at all * (it never falls through to the excluded products); either way the * caller deserves a specific, actionable error instead of discovering it * later as "0 products matched". * * @param array $product_filter Request's product_filter. * @return WP_Error|null Null when both lists are absent, blank, or sanitize to at least one id. */ private static function invalidProductIdListError(array $product_filter) { $raw = $product_filter['includeIds'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_include_ids', __('Include Only These Product IDs must contain at least one numeric product ID.', 'ai-product-tools'), ['status' => 400] ); } $raw = $product_filter['excludeIds'] ?? null; if (ProductIdListFilter::wasRequested($raw) && empty(ProductIdListFilter::parse($raw))) { return new WP_Error( 'invalid_exclude_ids', __('Exclude These Product IDs must contain at least one numeric product ID.', 'ai-product-tools'), ['status' => 400] ); } return null; } private function getDescriptionFilterConditions(array $filter): array { $raw_filters = []; if (isset($filter['descriptionFilters'])) { $raw_filters = is_array($filter['descriptionFilters']) ? $filter['descriptionFilters'] : explode(',', (string) $filter['descriptionFilters']); } elseif (isset($filter['descriptionFilter'])) { $raw_filters = is_array($filter['descriptionFilter']) ? $filter['descriptionFilter'] : explode(',', (string) $filter['descriptionFilter']); } $conditions = []; foreach ($raw_filters as $raw_filter) { $condition = ProductFilterBuilder::getContentFilterWherePart(sanitize_text_field((string) $raw_filter), 'p'); if ($condition !== '') { $conditions[] = '(' . $condition . ')'; } } return $conditions; } /** * Test endpoint to verify API is working * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response object */ /** * Estimate total products for given product filters * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response */ public function estimate_products(WP_REST_Request $request) { try { $product_filter = $request->get_param('productFilter'); if (empty($product_filter)) { $product_filter = $request->get_param('product_filter'); } if (!is_array($product_filter)) { $product_filter = []; } foreach (['categories', 'tags'] as $arr_key) { if (!empty($product_filter[$arr_key]) && is_array($product_filter[$arr_key])) { $product_filter[$arr_key] = array_map('absint', $product_filter[$arr_key]); } } $filter_block = JobEntitlementGuard::filterBlock($product_filter, JobEntitlementGuard::CONTEXT_RUN); $data = [ 'count' => null === $filter_block ? (int) $this->calculateTotalProducts($product_filter) : 0 ]; if (null !== $filter_block) { $data['unavailable_filters'] = $filter_block['keys']; $data['unavailable_filters_reason'] = $filter_block['reason']; } return new WP_REST_Response([ 'success' => true, 'data' => $data, ]); } catch (\Exception $e) { return new WP_REST_Response([ 'success' => false, 'message' => 'Failed to estimate products', ], 500); } } public function test_endpoint(WP_REST_Request $request) { return new WP_REST_Response([ 'success' => true, 'message' => 'Automation Jobs API is working!', 'timestamp' => current_time('mysql'), 'user_id' => get_current_user_id(), 'can_manage_woocommerce' => current_user_can('manage_woocommerce'), 'can_edit_posts' => current_user_can('edit_posts') ]); } /** * 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', ['status' => 404] ); } if (in_array($job->status, ['completed'], true)) { return new WP_Error( 'trigger_invalid_state', sprintf('Cannot trigger job in status: %s', $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 new WP_Error( 'aipt_job_limit_check_busy', __('Another job operation is in progress. Please try again.', 'ai-product-tools'), ['status' => 409] ); } try { $cap_error = $this->enforceJobCountCap(); if (is_wp_error($cap_error)) { return $cap_error; } $this->job_manager->updateJobStatus($job_id, 'ready'); } finally { $this->releaseJobCountLock(); } $job = $this->job_manager->getJob($job_id); } 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] ); } \AIPT\Api\AutomationJobs\JobExecutionHandler::register_job_hook($job_id); $hook = 'aipt_execute_job_' . $job_id; $base = time() + AutomationConstants::TRIGGER_EXECUTION_DELAY; $scheduled_ts = null; for ($i = 0; $i < AutomationConstants::TRIGGER_EXECUTION_ATTEMPTS; $i++) { $ts = $base + $i; $ok = wp_schedule_single_event($ts, $hook, [$job_id]); if ($ok) { $scheduled_ts = $ts; break; } } if ($scheduled_ts === null) { $existing = wp_next_scheduled($hook, [$job_id]); if ($existing) { $unscheduled = wp_unschedule_event($existing, $hook, [$job_id]); $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 = wp_schedule_single_event($ts, $hook, [$job_id]); 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) { } } 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', 'job_id' => $job_id, 'hook' => $hook, 'scheduled_time' => gmdate('Y-m-d H:i:s', $scheduled_ts) ]); } catch (\Exception $e) { return new WP_Error( 'trigger_error', $e->getMessage(), ['status' => 500] ); } } /** * 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 new WP_Error( 'aipt_job_limit_check_busy', __('Another job operation is in progress. Please try again.', 'ai-product-tools'), ['status' => 409] ); } 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', ['status' => 404] ); } $terminalStatuses = array( 'completed', 'failed' ); $jobStatus = $source_job->status; if ( ! in_array( $jobStatus, $terminalStatuses, true ) ) { return new WP_Error( 'job_not_terminal', sprintf( 'Cannot retry job in "%s" status. Job must be completed or failed.', $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', ['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', 'Retry job validation failed', ['status' => 400, 'errors' => $validation_errors] ); } $new_job_id = $this->job_manager->createJob($job); if (!$new_job_id) { return new WP_Error( 'job_creation_failed', 'Failed to create retry job', ['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', ['status' => 500] ); } $this->job_scheduler->scheduleJob($persisted_job); $created_job = $this->job_manager->getJob($new_job_id); return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($created_job), 'message' => sprintf('Retry job created with %d failed products', count($failed_ids)), 'source_job_id' => $source_job_id, 'failed_count' => count($failed_ids), ], 201); } catch (\Exception $e) { return new WP_Error( 'retry_failed_error', $e->getMessage(), ['status' => 500] ); } finally { $this->releaseJobCountLock(); } } /** * Lightweight monitor endpoint for real-time job progress * - Cached for a few seconds to avoid DB pressure * - Returns progress, counts, time estimations and current processing items (up to 3) */ public function get_job_monitor(\WP_REST_Request $request) { try { global $wpdb; $job_id = (int) $request->get_param('id'); $rl = $this->check_automation_rate_limit('monitor_' . $job_id, AutomationConstants::RATE_LIMIT_MONITOR_WINDOW); if (is_wp_error($rl)) { return $rl; } $owner_id = (int) $wpdb->get_var( $wpdb->prepare("SELECT created_by FROM {$wpdb->prefix}aipt_automation_jobs WHERE id = %d", $job_id) ); if ($owner_id <= 0) { return new \WP_Error('job_not_found', 'Job not found', ['status' => 404]); } $current_user_id = get_current_user_id(); if ($owner_id !== (int) $current_user_id && !current_user_can('manage_woocommerce')) { return new \WP_Error('rest_forbidden', __('You do not own this job.', 'ai-product-tools'), ['status' => 403]); } $cache_key = 'aipt_job_monitor_' . $job_id; $cached = get_transient($cache_key); if ($cached !== false) { return new \WP_REST_Response(['success' => true, 'data' => $cached]); } $job = $this->job_manager->getJob($job_id); if (!$job) { return new \WP_Error('job_not_found', 'Job not found', ['status' => 404]); } if ($job->status !== 'running') { $data = [ 'id' => (int) $job->id, 'status' => $job->status, 'progress_percent' => (int) $job->progress, 'processed_products' => (int) $job->processed_products, 'total_products' => (int) $job->total_products, 'failed_products' => (int) $job->failed_products, 'started_at' => UtcTimestamp::fromStored($job->started_at, true), 'estimated_completion' => null, 'elapsed_seconds' => null, 'elapsed_human' => null, 'remaining_seconds' => null, 'remaining_human' => null, 'current_processing' => [ 'count' => 0, 'items' => [] ], 'updated_at' => gmdate('Y-m-d\TH:i:s\Z'), ]; set_transient($cache_key, $data, 5); return new \WP_REST_Response(['success' => true, 'data' => $data]); } $progress = $this->job_executor->getJobProgress($job_id); $started_at_ts = $job->started_at ? SiteTime::toTimestamp($job->started_at) : null; $now = time(); $elapsed_seconds = $started_at_ts ? max(0, $now - $started_at_ts) : null; $eta_str = $progress['estimated_completion'] ?? null; $eta_ts = $eta_str ? strtotime($eta_str) : null; $remaining_seconds = ($eta_ts && $eta_ts > $now) ? ($eta_ts - $now) : null; $human = function($seconds) { if ($seconds === null) return null; if ($seconds < 60) return '~' . $seconds . 's'; $m = floor($seconds / 60); if ($m < 60) return '~' . $m . ' min'; $h = floor($m / 60); $rm = $m % 60; return '~' . $h . 'h ' . ($rm ? $rm . 'm' : ''); }; $job_products_table = $wpdb->prefix . 'aipt_job_products'; $processing_rows = $wpdb->get_results( $wpdb->prepare( "SELECT product_id FROM {$job_products_table} WHERE job_id = %d AND status = 'processing' ORDER BY processing_started_at DESC, id DESC LIMIT 3", $job_id ) ); $current_items = []; if (!empty($processing_rows)) { foreach ($processing_rows as $row) { $pid = (int) $row->product_id; $title = get_the_title($pid); $current_items[] = [ 'product_id' => $pid, 'title' => is_string($title) ? $title : '' ]; } } $data = [ 'id' => (int) $job->id, 'status' => $job->status, 'progress_percent' => (int) ($progress['progress'] ?? $job->progress), 'processed_products' => (int) ($progress['processed_products'] ?? $job->processed_products), 'total_products' => (int) ($progress['total_products'] ?? $job->total_products), 'failed_products' => (int) ($progress['failed_products'] ?? $job->failed_products), 'started_at' => UtcTimestamp::fromStored($job->started_at, true), 'estimated_completion' => UtcTimestamp::fromStored($eta_str, false), 'elapsed_seconds' => $elapsed_seconds, 'elapsed_human' => $human($elapsed_seconds), 'remaining_seconds' => $remaining_seconds, 'remaining_human' => $human($remaining_seconds), 'current_processing' => [ 'count' => count($current_items), 'items' => $current_items ], 'updated_at' => gmdate('Y-m-d\TH:i:s\Z'), ]; set_transient($cache_key, $data, 5); return new \WP_REST_Response(['success' => true, 'data' => $data]); } catch (\Exception $e) { return new \WP_Error('monitor_error', $e->getMessage(), ['status' => 500]); } } /** * 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); return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => 'Job stopped successfully' ]); } catch (\Exception $e) { return new WP_Error( 'job_stop_error', $e->getMessage(), ['status' => 400] ); } } /** * Get paginated list of job products with statuses and titles (compact) * * @param WP_REST_Request $request * @return WP_REST_Response|WP_Error */ public function get_job_products(WP_REST_Request $request) { global $wpdb; try { $job_id = (int) $request->get_param('id'); $page = max(1, (int) $request->get_param('page')) ?: 1; $per_page = (int) $request->get_param('per_page'); if ($per_page <= 0) { $per_page = 50; } if ($per_page > 200) { $per_page = 200; } $offset = ($page - 1) * $per_page; $owner_id = (int) $wpdb->get_var( $wpdb->prepare("SELECT created_by FROM {$wpdb->prefix}aipt_automation_jobs WHERE id = %d", $job_id) ); if ($owner_id <= 0) { return new \WP_Error('job_not_found', 'Job not found', ['status' => 404]); } $current_user_id = get_current_user_id(); if ($owner_id !== (int) $current_user_id && !current_user_can('manage_woocommerce')) { return new \WP_Error('rest_forbidden', __('You do not own this job.', 'ai-product-tools'), ['status' => 403]); } $status = $request->get_param('status'); $allowed_status = ['pending','processing','completed','failed']; $where = " WHERE jp.job_id = %d"; $params = [$job_id]; if (is_string($status) && in_array($status, $allowed_status, true)) { $where .= " AND jp.status = %s"; $params[] = $status; } $job_products_table = $wpdb->prefix . 'aipt_job_products'; $count_sql = "SELECT COUNT(*) FROM {$job_products_table} jp" . $where; if (count($params) === 1) { $prepared_count = $wpdb->prepare($count_sql, $params[0]); } else { $prepared_count = $wpdb->prepare($count_sql, $params[0], $params[1]); } $total = (int) $wpdb->get_var($prepared_count); $results_params = array_merge($params, [$per_page, $offset]); $results_sql = "SELECT jp.product_id, jp.status, jp.result, jp.error_message, COALESCE(p.post_title, '') as title FROM {$job_products_table} jp LEFT JOIN {$wpdb->posts} p ON p.ID = jp.product_id " . $where . " ORDER BY jp.id ASC LIMIT %d OFFSET %d"; if (count($results_params) === 3) { $prepared_results = $wpdb->prepare($results_sql, $results_params[0], $results_params[1], $results_params[2]); } else { $prepared_results = $wpdb->prepare($results_sql, $results_params[0], $results_params[1], $results_params[2], $results_params[3]); } $rows = $wpdb->get_results($prepared_results, ARRAY_A); $items = []; if (!empty($rows)) { foreach ($rows as $r) { $decoded_result = json_decode((string) ($r['result'] ?? ''), true); $blueprint_summary = $this->blueprintItemSummary(is_array($decoded_result) ? $decoded_result : []); $items[] = [ 'product_id' => (int) $r['product_id'], 'status' => (string) $r['status'], 'title' => (string) $r['title'], 'needsReview' => $blueprint_summary['needsReview'], 'blueprint' => $blueprint_summary['blueprint'], 'heldBackMessage' => $blueprint_summary['heldBackMessage'], 'errorMessage' => isset($r['error_message']) && null !== $r['error_message'] && '' !== $r['error_message'] ? (string) $r['error_message'] : null, ]; } } $pages = $per_page > 0 ? (int) ceil($total / $per_page) : 1; return new \WP_REST_Response([ 'success' => true, 'data' => [ 'total' => $total, 'page' => $page, 'per_page' => $per_page, 'pages' => $pages, 'needsReviewCount' => $this->countBlueprintNeedsReview($job_id), 'items' => $items, ] ]); } catch (\Exception $e) { return new \WP_Error('job_products_error', $e->getMessage(), ['status' => 500]); } } /** * Derive a lightweight, display-only Blueprint summary from one job * product's decoded `result` payload. Returns inert defaults for a * legacy/advanced result (no `executionPath` key) or an undecodable * payload, so a legacy job's products list is unaffected. * * @param array $decoded Decoded `result` JSON, or [] when absent/invalid. * @return array{needsReview:bool,blueprint:array{id:int|null,name:string,revision:int|null}|null,heldBackMessage:?string} */ private function blueprintItemSummary(array $decoded): array { if ('blueprint' !== (string) ($decoded['executionPath'] ?? '')) { return ['needsReview' => false, 'blueprint' => null, 'heldBackMessage' => null]; } $eligibility = is_array($decoded['eligibility'] ?? null) ? $decoded['eligibility'] : []; $needs_review = ! empty($eligibility['requiresReview']) || (array_key_exists('canApply', $eligibility) && empty($eligibility['canApply'])); $blueprint = is_array($decoded['blueprint'] ?? null) ? $decoded['blueprint'] : []; return [ 'needsReview' => $needs_review, 'blueprint' => [ 'id' => isset($blueprint['id']) ? $blueprint['id'] : null, 'name' => (string) ($blueprint['name'] ?? ''), 'revision' => isset($blueprint['revision']) ? $blueprint['revision'] : null, ], 'heldBackMessage' => $needs_review ? BlueprintIntegration::heldBackMessage($decoded) : null, ]; } /** * Count job_products rows whose stored Blueprint result still needs * review. A best-effort display aggregate for the job detail panel: no * column indexes this, so it walks the rows with a non-empty `result` * payload in id-ordered chunks (bounded memory) and decodes each in PHP. * The total is cached briefly because the open details panel re-requests * the products list on every monitor progress change. Deliberately not * called from the high-frequency job monitor poll. * * @param int $job_id Job ID. * @return int */ private function countBlueprintNeedsReview(int $job_id): int { global $wpdb; $cache_key = 'aipt_job_needs_review_' . $job_id; $cached = get_transient($cache_key); if (false !== $cached) { return (int) $cached; } $job_products_table = $wpdb->prefix . 'aipt_job_products'; $chunk_size = 200; $last_id = 0; $count = 0; do { $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, result FROM {$job_products_table} WHERE job_id = %d AND id > %d AND result IS NOT NULL AND result <> '' ORDER BY id ASC LIMIT %d", $job_id, $last_id, $chunk_size ), ARRAY_A ); foreach ($rows as $row) { $last_id = (int) $row['id']; $decoded = json_decode((string) $row['result'], true); if (is_array($decoded) && $this->blueprintItemSummary($decoded)['needsReview']) { $count++; } } } while (count($rows) === $chunk_size); set_transient($cache_key, $count, 15); return $count; } /** * Process running/ready jobs - browser-based fallback for WP-Cron disabled environments * * This endpoint allows the frontend to trigger job execution when WP-Cron is disabled. * Similar to Store Index's /process endpoint, it processes a single tick of work. * * @param WP_REST_Request $request Request object * @return WP_REST_Response Response with processing status */ public function process_jobs(WP_REST_Request $request) { $rl = $this->check_automation_rate_limit('process_jobs', AutomationConstants::RATE_LIMIT_PROCESS_JOBS); if (is_wp_error($rl)) { return $rl; } $lock_key = 'aipt_browser_job_processing'; $lock_token = $this->acquireBrowserLock($lock_key); if ($lock_token === null) { return new WP_REST_Response([ 'success' => true, 'needs_manual_process' => true, 'processed_job_id' => null, 'processed_job_name' => null, 'execution_result' => null, 'active_jobs' => [], 'active_jobs_count' => 0, 'message' => 'Another process is running', ], 200); } try { global $wpdb; $jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; if (!$wpdb->get_var("SHOW TABLES LIKE '{$jobs_table}'")) { return new WP_REST_Response([ 'success' => false, 'message' => 'Automation jobs table not found', 'needs_manual_process' => false, ], 500); } $active_jobs = $this->getBrowserRunnableJobs($jobs_table); $processed_job_id = null; $processed_job_name = null; $execution_result = null; $execution_error = null; if (!empty($active_jobs)) { $job_to_process = $active_jobs[0]; $processed_job_id = (int) $job_to_process->id; $processed_job_name = $job_to_process->name; try { $execution_result = $this->job_executor->executeJob($processed_job_id); } catch (\Exception $e) { $this->logger->error($processed_job_id, 'Browser-based execution failed', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]); $execution_result = false; $execution_error = __('Job execution failed. Please check the logs for details.', 'ai-product-tools'); } } $remaining_jobs = $this->getBrowserRunnableJobs($jobs_table); $needs_manual_process = !empty($remaining_jobs); $jobs_summary = array_map(function($job) { return [ 'id' => (int) $job->id, 'name' => $job->name, 'status' => $job->status, 'progress' => (int) $job->progress, 'total_products' => (int) $job->total_products, 'processed_products' => (int) $job->processed_products, 'failed_products' => (int) $job->failed_products, ]; }, $remaining_jobs); return new WP_REST_Response([ 'success' => true, 'needs_manual_process' => $needs_manual_process, 'processed_job_id' => $processed_job_id, 'processed_job_name' => $processed_job_name, 'execution_result' => $execution_result, 'execution_error' => $execution_error, 'active_jobs' => $jobs_summary, 'active_jobs_count' => count($remaining_jobs), ], 200); } catch (\Exception $e) { return new WP_REST_Response([ 'success' => false, 'message' => $e->getMessage(), 'needs_manual_process' => false, ], 500); } finally { $this->releaseBrowserLock($lock_key, $lock_token); } } /** * Active jobs the browser runner has work for, least recently updated first. * * A recurring job that only waits for its next cycle is left out: running * it does nothing and leaves its row untouched, so it would be picked on * every call (starving the other jobs) and keep the browser polling. A * one-time job whose scheduled run time has not come yet is left out too. * * @param string $jobs_table Prefixed jobs table name. * @return array Job rows. */ private function getBrowserRunnableJobs(string $jobs_table): array { global $wpdb; $rows = $wpdb->get_results( "SELECT id, status, name, progress, total_products, processed_products, failed_products, schedule_config, next_run, started_at FROM {$jobs_table} WHERE status IN ('running', 'ready', 'preparing') ORDER BY updated_at ASC" ); if (!is_array($rows)) { return []; } $runnable = []; foreach ($rows as $row) { $job = new AutomationJob((array) $row); if (!JobScheduler::isWaitingForRecurringCycle($job, $this->job_manager) && !JobScheduler::isWaitingForScheduledRun($job)) { $runnable[] = $row; } } return $runnable; } /** * Atomically acquire a browser processing lock using wp_options. * * Uses add_option() which performs a single INSERT — atomic by DB constraint. * Falls back to force-acquire when the existing lock's TTL has expired. * * @param string $lock_key Option name to use as the lock. * @param int $ttl_seconds Lock TTL in seconds (default 120). * @return string|null UUID token on success; null if lock is held. */ private function acquireBrowserLock(string $lock_key, int $ttl_seconds = 120): ?string { $token = wp_generate_uuid4(); $expires_at = time() + $ttl_seconds; $value = wp_json_encode(['token' => $token, 'expires_at' => $expires_at]); $acquired = add_option($lock_key, $value, '', 'no'); if ($acquired) { return $token; } $existing = get_option($lock_key); $existing_data = json_decode((string) $existing, true); if (is_array($existing_data) && (int) $existing_data['expires_at'] < time()) { delete_option($lock_key); $acquired = add_option($lock_key, $value, '', 'no'); return $acquired ? $token : null; } return null; } /** * Release a browser processing lock only when the token matches. * * Token matching prevents a late-arriving process from releasing a lock * it never owned (e.g. after a force-acquire by an expired-lock path). * * @param string $lock_key Option name used as the lock. * @param string $token Token returned by acquireBrowserLock(). * @return bool True on successful release; false if token mismatch or key missing. */ private function releaseBrowserLock(string $lock_key, string $token): bool { $existing = get_option($lock_key); $existing_data = json_decode((string) $existing, true); if (is_array($existing_data) && ($existing_data['token'] ?? null) === $token) { return delete_option($lock_key); } return false; } }