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' ], 'contentStatus' => [ 'required' => false, 'type' => 'string', 'enum' => ['published'], ] ] ]); 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 . '/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', ], 'toolType' => [ 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_key', ], ], ]); 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'] ]); } /** * Log an exception and answer with a generic sentence for the action. * The exception text goes to the log only, never to the browser. * * @param \Throwable $e The caught exception. * @param string $action Log message naming what failed. * @param string $code REST error code. * @param string $message Translated sentence for the merchant. * @param int $status HTTP status. * @param array $context Extra log context such as the job id. * @return WP_Error */ private function failure(\Throwable $e, string $action, string $code, string $message, int $status, array $context = []): WP_Error { $context = array_merge($context, ['exception' => get_class($e), 'error' => $e->getMessage()]); $cause = $e->getPrevious(); if (null !== $cause) { $context['caused_by'] = get_class($cause) . ': ' . $cause->getMessage(); } Logger::error('automation', $action, $context); return new WP_Error($code, $message, ['status' => $status]); } /** * Like failure(), except a JobActionRefusedException or a * JobFinishedBeforeCancelException keeps its message: the executor wrote * that sentence for the merchant. * * @param \Throwable $e The caught exception. * @param string $action Log message naming what failed. * @param string $code REST error code. * @param string $message Generic translated sentence for any other exception. * @param int $status HTTP status. * @param WP_REST_Request $request The request, for the job id in the log. * @return WP_Error */ private function actionFailure(\Throwable $e, string $action, string $code, string $message, int $status, WP_REST_Request $request): WP_Error { $context = ['job_id' => (int) $request->get_param('id')]; if ($e instanceof JobActionRefusedException || $e instanceof JobFinishedBeforeCancelException) { Logger::warn('automation', $action, array_merge($context, ['reason' => $e->getMessage()])); return new WP_Error($code, $e->getMessage(), ['status' => $status]); } return $this->failure($e, $action, $code, $message, $status, $context); } /** * Answer a job that failed validation with its field errors as data. * * @param JobValidationException $e The validation failure. * @param string $message Translated sentence for the merchant. * @return WP_Error */ private function validationFailure(JobValidationException $e, string $message): WP_Error { return new WP_Error('job_validation_failed', $message, ['status' => 400, 'errors' => $e->getErrors()]); } /** * 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]); } } 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); } /** * The answer for a job another request deleted between the write and the read that builds the response. * * @param bool $created True when the job was just created, so the message does not claim it was never made. * @return WP_Error 404 job_not_found, the code and status of every other missing job. */ private function jobGoneError(bool $created = false): WP_Error { return new WP_Error( 'job_not_found', $created ? __('The job was created, but it could not be found afterwards. It may have been deleted. Reload the list to check.', 'ai-product-tools') : __('Job not found', 'ai-product-tools'), ['status' => 404] ); } /** * Prepare job for response * * @param AutomationJob $job Job object * @return array Prepared job data */ private function prepare_job_for_response(AutomationJob $job) { $waiting_for_next_cycle = JobScheduler::isWaitingForRecurringCycle($job, $this->job_manager); 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, false), 'completed_at' => UtcTimestamp::fromStored($job->completed_at, false), 'error_message' => $job->error_message, 'created_by' => $job->created_by, 'created_at' => UtcTimestamp::fromStored($job->created_at, false), 'updated_at' => UtcTimestamp::fromStored($job->updated_at, false), 'waiting_for_next_cycle' => $waiting_for_next_cycle, 'waiting_for_spend_limit' => !$waiting_for_next_cycle && in_array((string) $job->status, ['preparing', 'ready', 'running'], true) && $this->isSpendLimitReached(), ]; } /** * Whether the merchant's monthly spend limit is reached, read once per * request. * * @return bool */ private function isSpendLimitReached(): bool { if (null === $this->spend_limit_reached) { $this->spend_limit_reached = SpendLimit::isReached(); } return $this->spend_limit_reached; } /** * 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 = ProductIdListFilter::parse($pf['categories'] ?? null); $tags = ProductIdListFilter::parse($pf['tags'] ?? null); if ( (ProductIdListFilter::wasRequested($pf['categories'] ?? null) && empty($categories)) || (ProductIdListFilter::wasRequested($pf['tags'] ?? null) && empty($tags)) ) { return 0; } $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)) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct COUNT query on wp_posts for performance $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); } // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Query uses only WP core tables ($wpdb->posts, etc.) and dynamic values are already in $params array with placeholders; direct COUNT query for performance $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; } } 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; } /** * 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) { global $wpdb; 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 = []; } $filter_block = JobEntitlementGuard::filterBlock($product_filter, JobEntitlementGuard::CONTEXT_RUN); $data = [ 'count' => null === $filter_block ? (int) $this->calculateTotalProducts($product_filter) : 0, 'throughput_per_hour' => ThroughputEstimator::measure($wpdb, (string) $request->get_param('toolType')), ]; 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) { Logger::error('automation', 'Product estimate failed', ['exception' => get_class($e), 'error' => $e->getMessage()]); return new WP_REST_Response([ 'success' => false, 'message' => __('Failed to estimate products', 'ai-product-tools'), ], 500); } } }