check_automation_rate_limit('create_job', AutomationConstants::RATE_LIMIT_CREATE_JOB); if (is_wp_error($rl)) { return $rl; } if (! $this->acquireJobCountLock()) { return $this->jobCountLockBusyError(); } try { $cap_error = $this->enforceJobCountCap(); if (is_wp_error($cap_error)) { return $cap_error; } $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', __('Some settings of this job are not valid. Check them and try again.', 'ai-product-tools'), [ 'status' => 400, 'errors' => $validation_errors ] ); } if (! $this->jobCountLockStillHeld()) { return $this->jobCountLockBusyError(); } $job_id = $this->job_manager->createJob($job); if (!$job_id) { return new WP_Error( 'job_creation_failed', __('Failed to create job', 'ai-product-tools'), ['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', 'ai-product-tools'), ['status' => 500] ); } $this->job_scheduler->scheduleJob($persisted_job); $created_job = $this->job_manager->getJob($job_id); if (!$created_job) { return $this->jobGoneError(true); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($created_job), 'message' => __('Job created successfully', 'ai-product-tools') ], 201); } catch (JobValidationException $e) { return $this->validationFailure($e, __('Some settings of this job are not valid. Check them and try again.', 'ai-product-tools')); } catch (\Exception $e) { return $this->failure($e, 'Job could not be created', 'job_creation_error', __('The job could not be created.', 'ai-product-tools'), 500); } finally { $this->releaseJobCountLock(); } } /** * 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', 'ai-product-tools'), ['status' => 404] ); } if ($job->isActive()) { return new WP_Error( 'job_cannot_be_updated', __('Cannot update active job', 'ai-product-tools'), ['status' => 400] ); } if ($job->status === 'completed') { return new WP_Error( 'job_completed_not_editable', __('Cannot update a completed job', 'ai-product-tools'), ['status' => 400] ); } $read_status = (string) $job->status; $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'); $keep_stored_blueprint = false; 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); } } if (!current_user_can('manage_aipt_settings') && !array_key_exists('blueprint', $updated_settings) && array_key_exists('blueprint', $previous_settings) ) { $keep_stored_blueprint = true; } $updated_settings = $this->withSkipProcessedSetting($updated_settings); $content_settings = $updated_settings['contentSettings'] ?? []; $resolved_content_settings = $this->withDraftReviewStatus( is_array($content_settings) ? $content_settings : [], JobEntitlementGuard::contentStatus($job->settings) ); 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 ($keep_stored_blueprint && is_array($job->settings)) { $job->settings['blueprint'] = $previous_settings['blueprint']; } } 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; } } } $reschedule = false; 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; $reschedule = true; } $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); } $written = $this->job_manager->updateJob($job, $read_status); if (AutomationJobManager::TRANSITION_LOST === $written) { return new WP_Error( 'aipt_job_changed', __('The job changed while you were editing it. Reload it and try again.', 'ai-product-tools'), ['status' => 409] ); } if (AutomationJobManager::TRANSITION_ERROR === $written) { return new WP_Error( 'job_update_error', __('The job could not be saved.', 'ai-product-tools'), ['status' => 500] ); } $schedule_error = null; if ($reschedule) { try { $this->job_scheduler->rescheduleJob($job); } catch (\Exception $e) { $schedule_error = $e; } } if ($rebuild_pool) { $this->job_manager->rebuildPool($job); $job = $this->job_manager->getJob($job->id) ?? $job; } if (null !== $schedule_error) { Logger::error('automation', 'Job edit saved but its next run could not be scheduled', ['job_id' => (int) $job->id, 'error' => $schedule_error->getMessage()]); return new WP_Error( 'aipt_job_schedule_failed', __('The job was saved, but its next run could not be scheduled. Save the job again to retry.', 'ai-product-tools'), ['status' => 500] ); } return new WP_REST_Response([ 'success' => true, 'data' => $this->prepare_job_for_response($job), 'message' => __('Job updated successfully', 'ai-product-tools') ]); } catch (JobValidationException $e) { return $this->validationFailure($e, __('Some settings of this job are not valid. Check them and try again.', 'ai-product-tools')); } catch (\Exception $e) { return $this->failure($e, 'Job update failed', 'job_update_error', __('The job could not be saved.', 'ai-product-tools'), 500, ['job_id' => (int) $request->get_param('id')]); } } /** * 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', 'ai-product-tools'), ['status' => 404] ); } if ($job->isActive() || in_array($job->status, ['preparing', 'ready'], true)) { try { $this->job_executor->cancelJob($job_id); } catch (JobFinishedBeforeCancelException $finished) { Logger::debug('automation', 'Job finished before its delete could cancel it', ['job_id' => (int) $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', 'ai-product-tools') ]); } catch (\Exception $e) { return $this->actionFailure($e, 'Job delete failed', 'job_delete_error', __('The job could not be deleted.', 'ai-product-tools'), 500, $request); } } /** * 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 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' ] ]; } }