wpdb = $wpdb; $this->jobs_table = $wpdb->prefix . 'aipt_automation_jobs'; $this->job_products_table = $wpdb->prefix . 'aipt_job_products'; } /** * Create a new job * * @param AutomationJob $job Job to create * @return int|false Job ID on success, false on failure * @throws JobValidationException When the job fails validation. * @throws \Exception On database errors */ public function createJob(AutomationJob $job) { $validation_errors = $job->validate(); if (!empty($validation_errors)) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Field errors travel as data to the REST layer, which never prints the exception text. throw new JobValidationException($validation_errors); } $job->created_at = JobTime::now(); $job->updated_at = JobTime::now(); $job->status = 'preparing'; $job->progress = 0; $data = $job->toArray(); unset($data['id']); $result = $this->wpdb->insert( $this->jobs_table, $data, [ '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s' ] ); if ($result === false) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception message for internal logging throw new \Exception('Failed to create job: ' . esc_html($this->wpdb->last_error)); } $job_id = $this->wpdb->insert_id; AutomationCronDemand::ensureScheduled(); try { \AIPT\Core\Services\UsageTracker::record_milestone( \AIPT\Core\Services\UsageTracker::MILESTONE_FIRST_AUTOMATION ); } catch (\Throwable $t) { } $this->buildPoolAndSetStatus((int) $job_id, $job, ['preparing']); return $job_id; } /** * Rebuild a job's product pool from its saved filter after an edit * changed that filter: the pool built from the old filter is dropped and * built again exactly like a new job's, product count and status * included. Only for a job that has not started (the caller checks). * * @param AutomationJob $job Saved job. * @return void */ public function rebuildPool(AutomationJob $job): void { $this->resetJobPool((int) $job->id); $this->buildPoolAndSetStatus((int) $job->id, $job, [(string) $job->status]); } /** * Build a job's product pool (a few chunks now, the rest on background * ticks) and move the job to 'ready', 'preparing' or 'completed' to * match, or pause it when its saved filter cannot be honored. * * The build takes seconds, so the status is written only while the job * is still in $from (the status the caller read): a pause or a cancel * that lands during the build is kept. * * @param int $job_id Job ID. * @param AutomationJob $job Job whose filter and settings drive the pool. * @param string[] $from Statuses the job must still be in. * @return void */ private function buildPoolAndSetStatus(int $job_id, AutomationJob $job, array $from): void { try { $pool_builder = new \AIPT\Api\AutomationJobs\PoolBuilder(); $filter = is_array($job->product_filter) ? $job->product_filter : []; $pool_options = AutomationJob::getPoolBuildOptions( (string) $job->tool_type, is_array($job->settings) ? $job->settings : [] ); $pool_result = $pool_builder->buildPool( $job_id, $filter, 2000, 5, $pool_options['skip_processed'], $pool_options['targeted_types'] ); if (!empty($pool_result['blocked'])) { $this->transitionJobStatus($job_id, 'paused', $from, (string) $pool_result['blocked']['message'], ['total_products' => 0]); return; } $target_total = isset($pool_result['total']) ? (int) $pool_result['total'] : 0; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $current_total = (int) $this->wpdb->get_var( $this->wpdb->prepare("SELECT COUNT(*) FROM {$this->job_products_table} WHERE job_id = %d", $job_id) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $extra = ['total_products' => $target_total]; if ($target_total === 0) { $status = 'completed'; $extra['progress'] = 100; } elseif ($current_total >= $target_total) { $status = 'ready'; } else { $status = 'preparing'; } $this->transitionJobStatus($job_id, $status, $from, null, $extra); } catch (\Exception $e) { Logger::error('automation', 'Job product pool could not be built', ['job_id' => (int) $job_id, 'error' => $e->getMessage()]); } } /** * Get a job by ID * * @param int $job_id Job ID * @return AutomationJob|null Job object or null if not found */ public function getJob($job_id) { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $result = $this->wpdb->get_row( $this->wpdb->prepare( "SELECT * FROM {$this->jobs_table} WHERE id = %d", $job_id ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if (!$result) { return null; } return new AutomationJob($result); } /** * Save the fields an edit may change, while the job still has the status * the edit read. * * Only the name, description, tool type, settings, schedule, product * filter and updated_at are written, in one UPDATE ... WHERE status = the * read status. Status, progress, counts, started_at, completed_at, * error_message and next_run belong to the run and are never written * here, so a start, a pause, a cancel or a tick that landed after the * edit read the job is kept, and so is the progress it made. * * @param AutomationJob $job Job carrying the edited fields. * @param string $expected_status Status the edit read. * @return string TRANSITION_APPLIED, TRANSITION_ALREADY (nothing to change), TRANSITION_LOST (the job left the status) or TRANSITION_ERROR. * @throws JobValidationException When the job fails validation. * @throws \Exception When the job has no ID. */ public function updateJob(AutomationJob $job, string $expected_status): string { if (empty($job->id)) { throw new \Exception('Job ID is required for update'); } $validation_errors = $job->validate(); if (!empty($validation_errors)) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Field errors travel as data to the REST layer, which never prints the exception text. throw new JobValidationException($validation_errors); } $job->updated_at = JobTime::now(); $data = $job->toArray(); $columns = ['name', 'description', 'tool_type', 'settings', 'schedule_config', 'product_filter', 'updated_at']; $assignments = []; $values = []; foreach ($columns as $column) { if (null === $data[$column]) { $assignments[] = "{$column} = NULL"; continue; } $assignments[] = $column . ' = %s'; $values[] = (string) $data[$column]; } $values[] = (int) $job->id; $values[] = $expected_status; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table and column names are the class's own; every value is a placeholder. $result = $this->wpdb->query( $this->wpdb->prepare( "UPDATE {$this->jobs_table} SET " . implode(', ', $assignments) . ' WHERE id = %d AND status = %s', $values ) ); if (false === $result) { Logger::error('automation', 'Job edit could not be saved', ['job_id' => (int) $job->id, 'error' => $this->wpdb->last_error]); return self::TRANSITION_ERROR; } if ((int) $result > 0) { AutomationCronDemand::ensureScheduled(); return self::TRANSITION_APPLIED; } $current = $this->wpdb->get_var( $this->wpdb->prepare("SELECT status FROM {$this->jobs_table} WHERE id = %d", (int) $job->id) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $expected_status === (string) $current ? self::TRANSITION_ALREADY : self::TRANSITION_LOST; } /** * Delete a job and all related data * * Deletes job record and all associated data from: * - aipt_draft_content (generated content awaiting review) * - aipt_job_logs (execution logs) * - aipt_job_products (product queue) * - aipt_automation_jobs (job record itself) * * @param int $job_id Job ID to delete * @return bool Success status * @throws \Exception On database errors */ public function deleteJob($job_id) { $job_id = absint($job_id); if ($job_id <= 0) { return false; } $this->wpdb->query('START TRANSACTION'); try { $draft_content_table = $this->wpdb->prefix . 'aipt_draft_content'; $this->wpdb->delete( $draft_content_table, ['job_id' => $job_id], ['%d'] ); $job_logs_table = $this->wpdb->prefix . 'aipt_job_logs'; $this->wpdb->delete( $job_logs_table, ['job_id' => $job_id], ['%d'] ); $this->wpdb->delete( $this->job_products_table, ['job_id' => $job_id], ['%d'] ); $result = $this->wpdb->delete( $this->jobs_table, ['id' => $job_id], ['%d'] ); if ($result === false) { throw new \Exception('Failed to delete job: ' . esc_html($this->wpdb->last_error)); } if ($this->wpdb->query('COMMIT') === false) { throw new \RuntimeException('COMMIT failed: ' . $this->wpdb->last_error); } return $result > 0; } catch (\Throwable $e) { $rollback = $this->wpdb->query('ROLLBACK'); if ($rollback === false) { Logger::error('automation', 'Rollback failed while deleting a job', ['job_id' => (int) $job_id, 'error' => (string) $this->wpdb->last_error]); } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception surfaces to REST layer which controls output escaping. throw new \Exception('Failed to delete job', 0, $e); } } /** * Get jobs with filters * * @param array $filters Filters (status, tool_type, created_by, etc.) * @param int $limit Limit * @param int $offset Offset * @param string $order_by Order by field * @param string $order Order direction (ASC/DESC) * @return array Jobs */ public function getJobs($filters = [], $limit = 20, $offset = 0, $order_by = 'created_at', $order = 'DESC') { $where_conditions = []; $where_values = []; if (!empty($filters['status'])) { if (is_array($filters['status'])) { $placeholders = implode(',', array_fill(0, count($filters['status']), '%s')); $where_conditions[] = "status IN ({$placeholders})"; $where_values = array_merge($where_values, $filters['status']); } else { $where_conditions[] = 'status = %s'; $where_values[] = $filters['status']; } } if (!empty($filters['tool_type'])) { $where_conditions[] = 'tool_type = %s'; $where_values[] = $filters['tool_type']; } if (!empty($filters['created_by'])) { $where_conditions[] = 'created_by = %d'; $where_values[] = $filters['created_by']; } $query = "SELECT * FROM {$this->jobs_table}"; if (!empty($where_conditions)) { $query .= ' WHERE ' . implode(' AND ', $where_conditions); } $allowed_order_by = ['id', 'name', 'status', 'tool_type', 'progress', 'created_at', 'updated_at', 'next_run']; if (!in_array($order_by, $allowed_order_by)) { $order_by = 'created_at'; } $order = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC'; $query .= " ORDER BY {$order_by} {$order}"; $query .= " LIMIT %d OFFSET %d"; $where_values[] = $limit; $where_values[] = $offset; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix, order/limit sanitized above if (!empty($where_values)) { $results = $this->wpdb->get_results( $this->wpdb->prepare($query, $where_values), ARRAY_A ); } else { $results = $this->wpdb->get_results($query, ARRAY_A); } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $jobs = []; foreach ($results as $result) { $jobs[] = new AutomationJob($result); } return $jobs; } /** * Whether AutomationConstants::MAX_CONCURRENT_JOBS jobs are already * status='running'. * * Shared by every path that can start a job running (the scheduler * poller, Trigger Now, Resume) so they all honor the same system-wide * cap through one mechanism, instead of each re-deriving and comparing * the running count itself. * * @return bool */ public function isAtConcurrentJobCap(): bool { return $this->getJobCount(['status' => 'running']) >= AutomationConstants::MAX_CONCURRENT_JOBS; } /** * Set $job_id running only while fewer than * AutomationConstants::MAX_CONCURRENT_JOBS jobs run. * * The running count and the status write happen under one MySQL * advisory lock, so two jobs starting at the same moment cannot both * take the last free slot. Both places a job starts running go through * here: the executor's tick start and Resume. A database that refuses * the lock query falls back to the same check without the lock rather * than never starting a job. * * With $from, the job starts only while it is still in one of those * statuses (the ones the caller read), so a pause or a cancel that * landed after that read is kept: START_LOST. * * @param int $job_id Job ID. * @param string[]|null $from Statuses the job must still be in. * @return string One of the START_* constants. */ public function startJobWithinConcurrentCap(int $job_id, ?array $from = null): string { $lock_name = $this->startLockName(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Prepared through $this->wpdb; MySQL advisory locks must not be cached. $locked = $this->wpdb->get_var($this->wpdb->prepare('SELECT GET_LOCK(%s, %d)', $lock_name, self::START_LOCK_WAIT_SECONDS)); if (null !== $locked && '1' !== (string) $locked) { return self::START_BUSY; } try { if ($this->isAtConcurrentJobCap()) { return self::START_CAP_FULL; } if (null === $from) { return $this->updateJobStatus($job_id, 'running') ? self::START_ADMITTED : self::START_WRITE_FAILED; } $transition = $this->transitionJobStatus($job_id, 'running', $from); if (self::TRANSITION_ERROR === $transition) { return self::START_WRITE_FAILED; } return self::TRANSITION_LOST === $transition ? self::START_LOST : self::START_ADMITTED; } finally { if ('1' === (string) $locked) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Prepared through $this->wpdb; MySQL advisory locks must not be cached. $this->wpdb->get_var($this->wpdb->prepare('SELECT RELEASE_LOCK(%s)', $lock_name)); } } } /** * Advisory lock name for job starts on this site's jobs table, within * MySQL's 64-character limit. * * @return string */ private function startLockName(): string { return 'aipt_job_start_' . sha1((defined('DB_NAME') ? (string) \DB_NAME : '') . ':' . $this->jobs_table); } /** * Get total job count with filters * * @param array $filters Filters * @return int Total count */ public function getJobCount($filters = []) { $where_conditions = []; $where_values = []; if (!empty($filters['status'])) { if (is_array($filters['status'])) { $placeholders = implode(',', array_fill(0, count($filters['status']), '%s')); $where_conditions[] = "status IN ({$placeholders})"; $where_values = array_merge($where_values, $filters['status']); } else { $where_conditions[] = 'status = %s'; $where_values[] = $filters['status']; } } if (!empty($filters['tool_type'])) { $where_conditions[] = 'tool_type = %s'; $where_values[] = $filters['tool_type']; } if (!empty($filters['created_by'])) { $where_conditions[] = 'created_by = %d'; $where_values[] = $filters['created_by']; } $query = "SELECT COUNT(*) FROM {$this->jobs_table}"; if (!empty($where_conditions)) { $query .= ' WHERE ' . implode(' AND ', $where_conditions); } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix if (!empty($where_values)) { return (int) $this->wpdb->get_var($this->wpdb->prepare($query, $where_values)); } else { return (int) $this->wpdb->get_var($query); } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared } /** * Every job whose settings choose this provider and model, in any status: * a paused, finished or failed job can run again, and it would then * quietly fall back to the provider default if the model were removed. * * @param string $provider AIPT provider id. * @param string $model Model id. * @return array|null Null when the jobs could not be read. */ public function findJobsUsingModel( string $provider, string $model ): ?array { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $rows = $this->wpdb->get_results( $this->wpdb->prepare( "SELECT id, name, settings FROM {$this->jobs_table} WHERE settings LIKE %s", '%' . $this->wpdb->esc_like( $model ) . '%' ), ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if ( ! is_array( $rows ) || '' !== (string) $this->wpdb->last_error ) { return null; } $jobs = []; foreach ( $rows as $row ) { $settings = json_decode( (string) ( $row['settings'] ?? '' ), true ); if ( is_array( $settings ) && ( $settings['provider'] ?? null ) === $provider && ( $settings['model'] ?? null ) === $model ) { $jobs[] = [ 'id' => (int) $row['id'], 'name' => (string) $row['name'], ]; } } return $jobs; } /** * Update job status * * @param int $job_id Job ID * @param string $status New status * @param string|null $error_message Optional error message * @return bool Success status */ public function updateJobStatus($job_id, $status, $error_message = null, ?array $from = null) { if (null !== $from) { return in_array( $this->transitionJobStatus((int) $job_id, (string) $status, $from, $error_message), [self::TRANSITION_APPLIED, self::TRANSITION_ALREADY], true ); } if ('failed' === $status && !$this->canTransitionToFailed((int) $job_id)) { return false; } $data = $this->statusWriteFields((string) $status, $error_message); $formats = array_fill(0, count($data), '%s'); $result = $this->wpdb->update( $this->jobs_table, $data, ['id' => $job_id], $formats, ['%d'] ); if (false !== $result) { $this->keepTickForWork((string) $status); } return $result !== false; } /** * Arm the processor tick when a write moved a job into a status the tick works on. * * @param string $status Status just written. * @return void */ private function keepTickForWork(string $status): void { if (in_array($status, AutomationJob::TICK_STATUSES, true)) { AutomationCronDemand::ensureScheduled(); } } /** * Move a job to $to only while it is still in one of $from, in one * UPDATE. A status write that follows a read taken seconds earlier (a * pool build, a tick start, a resume) must not overwrite what happened * in between: a merchant's pause or cancel, or another tick's write. * Callers pass the status they read and acted on. * * @param int $job_id Job ID. * @param string $to New status. * @param string[] $from Statuses the job must still be in. * @param string|null $error_message Message to store, as updateJobStatus(). * @param array $extra Other columns to write with it (an int is written as %d, null as NULL). * @param string|null $unless_error_message Skip the write while the job stores exactly this error message (a revival passes the user cancellation sentinel, which is stored on a failed job). * @return string One of the TRANSITION_* constants. */ public function transitionJobStatus(int $job_id, string $to, array $from, ?string $error_message = null, array $extra = [], ?string $unless_error_message = null): string { $from = array_values(array_unique(array_map('strval', $from))); if ([] === $from) { return self::TRANSITION_LOST; } $assignments = []; $values = []; foreach (array_merge($this->statusWriteFields($to, $error_message), $extra) as $column => $value) { if (null === $value) { $assignments[] = "{$column} = NULL"; continue; } $assignments[] = $column . ' = ' . (is_int($value) ? '%d' : '%s'); $values[] = $value; } $values[] = $job_id; $values = array_merge($values, $from); $unless_clause = ''; if (null !== $unless_error_message) { $unless_clause = ' AND (error_message IS NULL OR error_message <> %s)'; $values[] = $unless_error_message; } $status_placeholders = implode(', ', array_fill(0, count($from), '%s')); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Table and column names are the class's own; every value is a placeholder. $result = $this->wpdb->query( $this->wpdb->prepare( "UPDATE {$this->jobs_table} SET " . implode(', ', $assignments) . " WHERE id = %d AND status IN ({$status_placeholders}){$unless_clause}", $values ) ); if (false === $result) { return self::TRANSITION_ERROR; } if ((int) $result > 0) { $this->keepTickForWork($to); return self::TRANSITION_APPLIED; } $current = $this->wpdb->get_var( $this->wpdb->prepare("SELECT status FROM {$this->jobs_table} WHERE id = %d", $job_id) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $to === (string) $current && in_array($to, $from, true) ? self::TRANSITION_ALREADY : self::TRANSITION_LOST; } /** * The columns a status write sets: the status, the time, started_at for * running, completed_at for completed or failed, and the error message * (cleared on the way back to work or to completed when none is given). * * @param string $status New status. * @param string|null $error_message Message to store. * @return array */ private function statusWriteFields(string $status, ?string $error_message): array { $data = [ 'status' => $status, 'updated_at' => JobTime::now(), ]; if ('running' === $status) { $data['started_at'] = JobTime::now(); } elseif (in_array($status, ['completed', 'failed'], true)) { $data['completed_at'] = JobTime::now(); } if (null !== $error_message) { $data['error_message'] = $error_message; } elseif (in_array($status, ['running', 'ready', 'scheduled', 'preparing', 'completed'], true)) { $data['error_message'] = null; } return $data; } /** * Whether $job_id may transition to 'failed' right now. * * Refused when the job is already settled: 'completed', the literal * 'cancelled' status, or 'failed' already carrying * self::CANCELLED_BY_USER_ERROR_MESSAGE (how a user cancellation is * actually stored; see that constant's docblock). A job not found at * all is left to the normal update (which will simply affect 0 rows) * rather than refused for an unrelated reason. * * @param int $job_id Job ID. * @return bool */ private function canTransitionToFailed($job_id) { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix $current = $this->wpdb->get_row($this->wpdb->prepare( "SELECT status, error_message FROM {$this->jobs_table} WHERE id = %d", $job_id )); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if (!$current) { return true; } if (in_array($current->status, ['completed', 'cancelled'], true)) { return false; } if ('failed' === $current->status && self::CANCELLED_BY_USER_ERROR_MESSAGE === $current->error_message) { return false; } return true; } /** * Pause a job whose paid behavior cannot be honored, storing why. * * @param int $job_id Job ID. * @param string $message User-visible reason. * @param bool $reset_pool Drop a partially built pool so a resume rebuilds it. * @param string[]|null $from Statuses the job must still be in (see updateJobStatus()). * @return bool Success status */ public function pauseForEntitlement(int $job_id, string $message, bool $reset_pool = false, ?array $from = null): bool { if ($reset_pool) { $this->resetJobPool($job_id); } return $this->updateJobStatus($job_id, 'paused', $message, $from); } /** * Remove a job's product pool and progress counters so the pool is built * again (a new recurring cycle, or a pool build that was blocked). The * pool builder's keyset cursor starts after the highest pooled product, * so a rebuild needs an empty pool. * * @param int $job_id Job ID. * @return bool Success status */ public function resetJobPool(int $job_id): bool { $deleted = $this->wpdb->delete($this->job_products_table, ['job_id' => $job_id], ['%d']); $updated = $this->wpdb->update( $this->jobs_table, [ 'total_products' => 0, 'processed_products' => 0, 'failed_products' => 0, 'progress' => 0, 'updated_at' => JobTime::now(), ], ['id' => $job_id], ['%d', '%d', '%d', '%d', '%s'], ['%d'] ); return false !== $deleted && false !== $updated; } /** * Overwrite a job's settings column directly (and bump updated_at) * without re-running AutomationJob::validate() against the whole job. * * Used by the Premium recurring-cycle re-pin, which computes a new * settings.blueprint from the job's OWN already-valid settings — full * revalidation of the unrelated schedule/status/filter fields the * model's validate() also checks would be pure overhead on every cycle * start, for an array this method's own caller already derived. * * @param int $job_id Job ID. * @param array $settings New settings value. * @return bool Success status. */ public function updateJobSettings(int $job_id, array $settings): bool { $updated = $this->wpdb->update( $this->jobs_table, [ 'settings' => wp_json_encode($settings), 'updated_at' => JobTime::now(), ], ['id' => $job_id], ['%s', '%s'], ['%d'] ); if (false !== $updated) { AutomationCronDemand::ensureScheduled(); } return false !== $updated; } /** * Set a job's next_run directly (and bump updated_at). * * @param int $job_id Job ID. * @param string $next_run UTC 'Y-m-d H:i:s' time, the format next_run is stored in. * @return bool Success status. */ public function setJobNextRun(int $job_id, string $next_run): bool { $updated = $this->wpdb->update( $this->jobs_table, [ 'next_run' => $next_run, 'updated_at' => JobTime::now(), ], ['id' => $job_id], ['%s', '%s'], ['%d'] ); return false !== $updated; } /** * One-time upgrade step for recurring jobs that were mid-cycle before cycles re-armed. * * Before recurring jobs were re-armed, starting a cycle never moved * next_run forward, so a job that was preparing, running or paused at the * upgrade still stores the start of the cycle it is working through: a * next_run not later than started_at. Kept, that past next_run would make * the re-arm start a full new cycle as soon as the run completes, and a * resume drop the rows still to do. Clearing it lets a paused job resume * into its remaining rows and the re-arm calculate the real next cycle. * A due cycle that has not begun (next_run later than started_at) is kept. * * Both columns are UTC. Each row is cleared only if its next_run is unchanged. * * @return int Number of jobs whose stored run was cleared. */ public function clearLegacyInProgressCycleRuns(): int { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $this->wpdb->get_results( "SELECT id, next_run, started_at, schedule_config FROM {$this->jobs_table} WHERE status IN ('preparing', 'running', 'paused') AND next_run IS NOT NULL AND started_at IS NOT NULL", ARRAY_A ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $cleared = 0; foreach ((array) $rows as $row) { $row = (array) $row; $schedule = json_decode((string) ($row['schedule_config'] ?? ''), true); if (!\AIPT\Api\AutomationJobs\Services\JobEntitlementGuard::isRecurring($schedule)) { continue; } $next_ts = strtotime((string) $row['next_run'] . ' UTC'); $started_ts = JobTime::toTimestamp($row['started_at']); if (false === $next_ts || false === $started_ts || $next_ts > $started_ts) { continue; } $updated = $this->wpdb->update( $this->jobs_table, ['next_run' => null], ['id' => (int) $row['id'], 'next_run' => (string) $row['next_run']], ['%s'], ['%d', '%s'] ); if (false !== $updated && (int) $updated > 0) { $cleared++; } } return $cleared; } /** * Number of pool rows that are still pending or processing. * * @param int $job_id Job ID. * @return int */ public function countOpenJobProducts(int $job_id): int { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Table name from $wpdb->prefix return (int) $this->wpdb->get_var( $this->wpdb->prepare( "SELECT COUNT(*) FROM {$this->job_products_table} WHERE job_id = %d AND status IN ('pending', 'processing')", $job_id ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared } /** * Update job progress * * @param int $job_id Job ID * @param int $processed_products Number of processed products * @param int $failed_products Number of failed products * @return bool Success status */ public function updateJobProgress($job_id, $processed_products, $failed_products = 0) { $job = $this->getJob($job_id); if (!$job) { return false; } $progress = $job->total_products > 0 ? round(($processed_products / $job->total_products) * 100) : 0; $result = $this->wpdb->update( $this->jobs_table, [ 'progress' => min(100, max(0, $progress)), 'processed_products' => $processed_products, 'failed_products' => $failed_products, 'updated_at' => JobTime::now(), 'last_progress_logged_at' => JobTime::now() ], ['id' => $job_id], ['%d', '%d', '%d', '%s', '%s'], ['%d'] ); return $result !== false; } /** * Create job products entries * * @param int $job_id Job ID * @param array $product_filter Product filter configuration * @return bool Success status */ private function createJobProducts($job_id, $product_filter, bool $skipProcessed = false, array $targetedTypes = []) { global $wpdb; try { $product_ids = $this->getFilteredProductIds($product_filter, $skipProcessed, $targetedTypes); if (empty($product_ids)) { return true; } $batch_size = 100; $batches = array_chunk($product_ids, $batch_size); foreach ($batches as $batch) { $values = []; $placeholders = []; foreach ($batch as $product_id) { $values[] = $job_id; $values[] = $product_id; $values[] = 'pending'; $values[] = JobTime::now(); $placeholders[] = '(%d, %d, %s, %s)'; } $query = "INSERT INTO {$this->job_products_table} (job_id, product_id, status, created_at) VALUES " . implode(', ', $placeholders); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk insert with table name from $wpdb->prefix $result = $wpdb->query($wpdb->prepare($query, $values)); if ($result === false) { throw new \Exception('Failed to create job products: ' . $wpdb->last_error); } } return true; } catch (\Exception $e) { Logger::error('automation', 'Job products could not be created', ['job_id' => (int) $job_id, 'error' => $e->getMessage()]); return false; } } /** * Get filtered product IDs based on filter configuration * * @param array $product_filter Product filter configuration * @return array Product IDs */ private function getFilteredProductIds($product_filter, bool $skipProcessed = false, array $targetedTypes = []) { global $wpdb; $query = " SELECT DISTINCT p.ID FROM {$wpdb->posts} p WHERE p.post_type = 'product' AND p.post_status = 'publish' "; $query_params = []; if ( PremiumClassGuard::exists( '\\AIPT\\Premium\\AutomationJobs\\Services\\ProductFilterAugmenter' ) ) { \AIPT\Premium\AutomationJobs\Services\ProductFilterAugmenter::addManagerFilters( $query, $query_params, $product_filter ); } if (!empty($product_filter['priceRange']['min']) || !empty($product_filter['priceRange']['max'])) { $price_conditions = []; if (!empty($product_filter['priceRange']['min'])) { $price_conditions[] = "CAST(pm.meta_value AS DECIMAL(10,2)) >= %f"; $query_params[] = (float) $product_filter['priceRange']['min']; } if (!empty($product_filter['priceRange']['max'])) { $price_conditions[] = "CAST(pm.meta_value AS DECIMAL(10,2)) <= %f"; $query_params[] = (float) $product_filter['priceRange']['max']; } if (!empty($price_conditions)) { $query .= " AND p.ID IN ( SELECT post_id FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_price' AND " . implode(' AND ', $price_conditions) . " )"; } } if (!empty($product_filter['includeIds'])) { $include_ids = array_filter(array_map('intval', explode(',', $product_filter['includeIds']))); if (!empty($include_ids)) { $include_placeholders = implode(',', array_fill(0, count($include_ids), '%d')); $query .= " AND p.ID IN ({$include_placeholders})"; $query_params = array_merge($query_params, $include_ids); } else { $query .= ' AND 1=0'; } } if (!empty($product_filter['excludeIds'])) { $exclude_ids = array_map('intval', explode(',', $product_filter['excludeIds'])); if (!empty($exclude_ids)) { $exclude_placeholders = implode(',', array_fill(0, count($exclude_ids), '%d')); $query .= " AND p.ID NOT IN ({$exclude_placeholders})"; $query_params = array_merge($query_params, $exclude_ids); } } if ($skipProcessed) { $skip_condition = $this->buildAiProcessedSkipPredicate('p', $targetedTypes); if ('' !== $skip_condition) { $query .= " AND {$skip_condition}"; } } $query .= " ORDER BY p.ID ASC LIMIT 1000"; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Complex product filter query with table names from $wpdb if (!empty($query_params)) { $results = $wpdb->get_col($wpdb->prepare($query, $query_params)); } else { $results = $wpdb->get_col($query); } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return array_map('intval', $results); } private function buildAiProcessedSkipPredicate($product_alias, array $targetedTypes) { if (empty($targetedTypes)) { return $this->wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- The table name is from $wpdb and the alias is an internal constant. "NOT EXISTS (SELECT 1 FROM {$this->wpdb->postmeta} aipt_ai_processed_pm WHERE aipt_ai_processed_pm.post_id = {$product_alias}.ID AND aipt_ai_processed_pm.meta_key = %s)", \AIPT\Core\ContentMarking\MetaKeys::ROLLUP ); } $conditions = []; foreach ($targetedTypes as $targeted_type) { $meta_key = \AIPT\Core\ContentMarking\MetaKeys::keyForType((string) $targeted_type); if (null === $meta_key) { continue; } $conditions[] = $this->wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- The table name is from $wpdb and the alias is an internal constant. "NOT EXISTS (SELECT 1 FROM {$this->wpdb->postmeta} aipt_ai_processed_pm WHERE aipt_ai_processed_pm.post_id = {$product_alias}.ID AND aipt_ai_processed_pm.meta_key = %s)", $meta_key ); } if (empty($conditions)) { return ''; } return '( ' . implode(' OR ', $conditions) . ' )'; } /** * Get failed product IDs by job ID * * @param int $jobId Job ID * @return array Array of failed product IDs */ public function getFailedProductIdsByJobId(int $jobId): array { $table = $this->wpdb->prefix . 'aipt_job_products'; // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Direct query needed for job-specific data, table name is safe prefixed string $result = $this->wpdb->get_col( $this->wpdb->prepare( "SELECT product_id FROM {$table} WHERE job_id = %d AND status = 'failed' ORDER BY product_id ASC", $jobId ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $result; } }