*/ private $last_bulk_failures = []; /** * Job logger, for entries the Automation Jobs log viewer surfaces * (distinct from the PHP error_log() calls below, which are * developer-facing only). * @var JobLoggerInterface */ private $logger; /** * Constructor * * @param JobLoggerInterface|null $logger Optional logger override for tests; * defaults to the real JobLogger. */ public function __construct(?JobLoggerInterface $logger = null) { global $wpdb; $this->wpdb = $wpdb; $this->draft_table = $wpdb->prefix . 'aipt_draft_content'; $this->logger = $logger ?: new JobLogger(); } /** * Save draft content * * @param int $job_id Job ID * @param int $product_id Product ID * @param string $content_type Content type (title, description, short_description, tags) * @param string $generated_content Generated content * @param string|null $original_content Original content * @param int|null $created_by User ID that owns the parent job/draft * @param string $record_kind Record kind discriminator ('review' or 'backup'). * @param array $opts Additive: blueprint_id/blueprint_name/blueprint_revision/blueprint_builtin, * the blueprint that produced this raw item's content. Absent for a * custom-prompts write, which leaves every column at its default. * @return int|false Draft content ID or false on failure */ public function saveDraftContent($job_id, $product_id, $content_type, $generated_content, $original_content = null, $created_by = null, $record_kind = 'review', array $opts = array()) { try { if ($original_content === null) { $original_content = $this->getOriginalContent($product_id, $content_type); } $draft_created_by = $this->resolveDraftCreatedBy((int) $job_id, $created_by); $blueprint_columns = $this->buildBlueprintColumns($opts); $data = array_merge( [ 'job_id' => $job_id, 'product_id' => $product_id, 'content_type' => $content_type, 'record_kind' => $record_kind, 'original_content' => $original_content, 'generated_content' => $generated_content, 'status' => 'pending', 'created_by' => $draft_created_by, ], $blueprint_columns, [ 'created_at' => current_time('mysql') ] ); $existing = $this->wpdb->get_row($this->wpdb->prepare( "SELECT id, status, approved_at, updated_at FROM {$this->draft_table} WHERE job_id = %d AND product_id = %d AND content_type = %s AND record_kind = %s", $job_id, $product_id, $content_type, $record_kind )); if ($existing) { if ('pending' !== $existing->status) { if (!$this->wasReviewedBeforeCurrentPass($existing, (int) $job_id, (int) $product_id)) { return false; } $now = current_time('mysql'); $result = $this->wpdb->update( $this->draft_table, array_merge( [ 'generated_content' => $generated_content, 'original_content' => $original_content, 'status' => 'pending', 'created_by' => $draft_created_by, 'approved_by' => null, 'approved_at' => null, ], $blueprint_columns, [ 'created_at' => $now, 'updated_at' => $now, ] ), ['id' => $existing->id, 'status' => $existing->status], ['%s', '%s', '%s', '%d', '%d', '%s', '%d', '%s', '%d', '%d', '%s', '%s'], ['%d', '%s'] ); return (false !== $result && (int) $result > 0) ? (int) $existing->id : false; } $result = $this->wpdb->update( $this->draft_table, array_merge( [ 'generated_content' => $generated_content, 'original_content' => $original_content, 'status' => 'pending', 'created_by' => $draft_created_by, ], $blueprint_columns, [ 'updated_at' => current_time('mysql') ] ), ['id' => $existing->id, 'status' => 'pending'], ['%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s'], ['%d', '%s'] ); return false !== $result ? (int) $existing->id : false; } else { $result = $this->wpdb->insert( $this->draft_table, $data, ['%d', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%s'] ); return $result !== false ? $this->wpdb->insert_id : false; } } catch (\Exception $e) { return false; } } /** * Build the four blueprint-attribution columns from a saveDraftContent() * `$opts` array. Denormalized onto every row that knows its blueprint, * so a later rename or delete of that blueprint never blanks this row's * history. Absent for a custom-prompts write, which leaves every column * at its DB default. * * @since 2.8.0 * @param array $opts saveDraftContent() opts. * @return array{blueprint_id:int,blueprint_name:string,blueprint_revision:int,blueprint_builtin:int} */ private function buildBlueprintColumns(array $opts): array { return [ 'blueprint_id' => isset($opts['blueprint_id']) ? (int) $opts['blueprint_id'] : 0, 'blueprint_name' => isset($opts['blueprint_name']) ? (string) $opts['blueprint_name'] : '', 'blueprint_revision' => isset($opts['blueprint_revision']) ? (int) $opts['blueprint_revision'] : 0, 'blueprint_builtin' => !empty($opts['blueprint_builtin']) ? 1 : 0, ]; } /** * Apply the shared blueprint-attribution read shape to every drafts row: * blueprint_id and blueprint_revision read 0 as null (0 is never a real * id or revision), blueprint_name is always a string, and * blueprint_builtin is always a bool. * * @since 2.8.0 * @param object[] $rows Draft rows as returned by $wpdb->get_results() (stdClass, no ARRAY_A). * @return object[] */ private function normalizeBlueprintShape(array $rows): array { foreach ($rows as $row) { if (!is_object($row)) { continue; } $blueprint_id = isset($row->blueprint_id) ? (int) $row->blueprint_id : 0; $blueprint_revision = isset($row->blueprint_revision) ? (int) $row->blueprint_revision : 0; $row->blueprint_id = $blueprint_id > 0 ? $blueprint_id : null; $row->blueprint_name = isset($row->blueprint_name) ? (string) $row->blueprint_name : ''; $row->blueprint_revision = $blueprint_revision > 0 ? $blueprint_revision : null; $row->blueprint_builtin = !empty($row->blueprint_builtin); } return $rows; } /** * Whether a reviewed draft predates the product's current pass through the job. * * A job queues a product once per pool, so a product can only be generated * again for the same job after a recurring cycle rebuilt the pool. A draft * approved or rejected before the product's pool row was created belongs * to that earlier cycle. A draft reviewed after it, or one being approved * right now ('in_progress'), is never replaced. * * @param object $existing Draft row (status, approved_at, updated_at). * @param int $job_id Job ID. * @param int $product_id Product ID. * @return bool */ private function wasReviewedBeforeCurrentPass($existing, int $job_id, int $product_id): bool { if (!in_array((string) $existing->status, ['approved', 'rejected'], true)) { return false; } $reviewed_at = !empty($existing->updated_at) ? (string) $existing->updated_at : (string) ($existing->approved_at ?? ''); $reviewed_ts = '' !== $reviewed_at ? strtotime($reviewed_at) : false; if (false === $reviewed_ts) { return false; } $pooled_at = $this->wpdb->get_var($this->wpdb->prepare( "SELECT created_at FROM {$this->wpdb->prefix}aipt_job_products WHERE job_id = %d AND product_id = %d", $job_id, $product_id )); $pooled_ts = !empty($pooled_at) ? strtotime((string) $pooled_at) : false; return false !== $pooled_ts && $reviewed_ts < $pooled_ts; } /** * Get original content from product * * @param int $product_id Product ID * @param string $content_type Content type * @return string Original content */ private function getOriginalContent($product_id, $content_type) { $product = wc_get_product($product_id); if (!$product) { return ''; } switch ($content_type) { case 'title': return $product->get_name(); case 'description': return $product->get_description(); case 'short_description': return $product->get_short_description(); case 'tags': $tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']); return is_array($tags) ? implode(', ', $tags) : ''; case 'faq': $faq_data = get_post_meta($product_id, '_aipt_faq_data', true); return is_string($faq_data) ? $faq_data : ''; case 'seo_meta': $detected_plugin = SeoPluginDetector::detect(); if (null === $detected_plugin) { return ''; } $seo_info = SeoPluginDetector::get_seo_info($product_id, $detected_plugin); $original = [ 'meta_title' => $seo_info['meta_title'] ?? '', 'meta_description' => $seo_info['meta_description'] ?? '', 'focus_keyword' => $seo_info['focus_keyword'] ?? '', ]; $json = wp_json_encode($original); return $json !== false ? $json : ''; case 'image_alt': $image_alt = $this->getProductImageAltData($product_id); $json = wp_json_encode($image_alt); return $json !== false ? $json : ''; default: return ''; } } /** * Get draft content by filters * * @param array $filters Filters (job_id, product_id, status, content_type) * @param int $limit Limit * @param int $offset Offset * @return array Draft content items */ public function getDraftContent($filters = [], $limit = 50, $offset = 0) { $where_conditions = ['1=1']; $query_params = []; $where_conditions[] = 'dc.record_kind = %s'; $query_params[] = 'review'; $visibility = \AIPT\Core\ContentBank\ProductVisibilityScope::whereFragment('dc.product_id'); if (null !== $visibility) { $where_conditions[] = $visibility; } if (!empty($filters['job_id'])) { $where_conditions[] = 'dc.job_id = %d'; $query_params[] = $filters['job_id']; } if (!empty($filters['product_id'])) { $where_conditions[] = 'dc.product_id = %d'; $query_params[] = $filters['product_id']; } if (!empty($filters['status'])) { $where_conditions[] = 'dc.status = %s'; $query_params[] = $filters['status']; } if (!empty($filters['content_type'])) { $where_conditions[] = 'dc.content_type = %s'; $query_params[] = $filters['content_type']; } $query = " SELECT dc.*, p.post_title as product_name, j.name as job_name FROM {$this->draft_table} dc LEFT JOIN {$this->wpdb->posts} p ON dc.product_id = p.ID LEFT JOIN {$this->wpdb->prefix}aipt_automation_jobs j ON dc.job_id = j.id WHERE " . implode(' AND ', $where_conditions) . " ORDER BY dc.created_at DESC LIMIT %d OFFSET %d "; $query_params[] = $limit; $query_params[] = $offset; $rows = !empty($query_params) ? $this->wpdb->get_results($this->wpdb->prepare($query, $query_params)) : $this->wpdb->get_results($query); return is_array($rows) ? $this->normalizeBlueprintShape($rows) : $rows; } /** * Get draft content count * * @param array $filters Filters * @return int Count */ public function getDraftContentCount($filters = []) { $where_conditions = ['1=1']; $query_params = []; $where_conditions[] = 'record_kind = %s'; $query_params[] = 'review'; $visibility = \AIPT\Core\ContentBank\ProductVisibilityScope::whereFragment('product_id'); if (null !== $visibility) { $where_conditions[] = $visibility; } if (!empty($filters['job_id'])) { $where_conditions[] = 'job_id = %d'; $query_params[] = $filters['job_id']; } if (!empty($filters['product_id'])) { $where_conditions[] = 'product_id = %d'; $query_params[] = $filters['product_id']; } if (!empty($filters['status'])) { $where_conditions[] = 'status = %s'; $query_params[] = $filters['status']; } if (!empty($filters['content_type'])) { $where_conditions[] = 'content_type = %s'; $query_params[] = $filters['content_type']; } $query = " SELECT COUNT(*) FROM {$this->draft_table} WHERE " . implode(' AND ', $where_conditions); if (!empty($query_params)) { return (int) $this->wpdb->get_var($this->wpdb->prepare($query, $query_params)); } else { return (int) $this->wpdb->get_var($query); } } /** * Approve draft content and apply to product * * @param int $draft_id Draft content ID * @return bool Success status */ public function approveDraftContent($draft_id) { $draft_id = absint($draft_id); $claimed = false; $this->last_approval_error = null; try { if ($draft_id <= 0) { throw new \Exception('Invalid draft content ID'); } $claimed_by = (int) get_current_user_id(); $now = current_time('mysql'); $claim_result = $this->wpdb->update( $this->draft_table, [ 'status' => 'in_progress', 'approved_by' => $claimed_by, 'updated_at' => $now, ], [ 'id' => $draft_id, 'status' => 'pending', 'record_kind' => 'review', ], ['%s', '%d', '%s'], ['%d', '%s', '%s'] ); if ($claim_result === false) { throw new \Exception('Failed to claim draft content'); } if ((int) $claim_result < 1) { $this->last_approval_error = new \WP_Error( 'draft_conflict', __('Draft content is not pending or is already being processed.', 'ai-product-tools'), ['status' => 409] ); throw new \Exception('Draft content is not pending or is already being processed'); } $claimed = true; $draft = $this->wpdb->get_row($this->wpdb->prepare( "SELECT * FROM {$this->draft_table} WHERE id = %d AND status = %s", $draft_id, 'in_progress' )); if (!$draft) { throw new \Exception('Draft content not found'); } $write_mode = 'append'; if ($draft->content_type === 'faq') { $write_mode = $this->resolveFaqWriteMode((int) $draft->job_id); } $success = $this->applyContentToProduct( $draft->product_id, $draft->content_type, $draft->generated_content, $write_mode, array( 'id' => isset($draft->blueprint_id) ? (int) $draft->blueprint_id : 0, 'name' => isset($draft->blueprint_name) ? (string) $draft->blueprint_name : '', 'revision' => isset($draft->blueprint_revision) ? (int) $draft->blueprint_revision : 0, 'builtin' => !empty($draft->blueprint_builtin), ), (int) $draft->job_id ); if ($success) { $final_result = $this->wpdb->update( $this->draft_table, [ 'status' => 'approved', 'approved_by' => $claimed_by, 'approved_at' => current_time('mysql'), 'updated_at' => current_time('mysql') ], ['id' => $draft_id, 'status' => 'in_progress'], ['%s', '%d', '%s', '%s'], ['%d', '%s'] ); if (false === $final_result || (int) $final_result < 1) { $forced = $this->wpdb->update( $this->draft_table, [ 'status' => 'approved', 'approved_by' => $claimed_by, 'approved_at' => current_time('mysql'), 'updated_at' => current_time('mysql') ], ['id' => $draft_id], ['%s', '%d', '%s', '%s'], ['%d'] ); return false !== $forced && (int) $forced >= 1; } return true; } $this->releaseDraftClaim($draft_id); return false; } catch (\Exception $e) { if ($claimed) { $this->releaseDraftClaim($draft_id); } return false; } } /** * Reason-aware refusal recorded by the last approveDraftContent() call. * * @return \WP_Error|null Null when the last approval was not refused for a plan reason. */ public function getLastApprovalError() { return $this->last_approval_error; } /** * Reason-aware refusal recorded by the last rejectDraftContent() call. * * @return \WP_Error|null Null when the last rejection was not refused for a specific reason. */ public function getLastRejectionError() { return $this->last_rejection_error; } /** * Refusal messages recorded by the last bulkApproveDraftContent() or * bulkRejectDraftContent() call, keyed by draft id. A failed draft with no * specific refusal has no entry. * * @return array */ public function getLastBulkFailures() { return $this->last_bulk_failures; } private function resolveDraftCreatedBy($job_id, $created_by = null) { if (null !== $created_by && (int) $created_by > 0) { return (int) $created_by; } $jobs_table = $this->wpdb->prefix . 'aipt_automation_jobs'; $job_created_by = $this->wpdb->get_var($this->wpdb->prepare( "SELECT created_by FROM {$jobs_table} WHERE id = %d", $job_id )); if ((int) $job_created_by > 0) { return (int) $job_created_by; } return (int) get_current_user_id(); } private function releaseDraftClaim($draft_id) { $this->wpdb->update( $this->draft_table, [ 'status' => 'pending', 'approved_by' => null, 'updated_at' => current_time('mysql'), ], [ 'id' => $draft_id, 'status' => 'in_progress', ], ['%s', '%d', '%s'], ['%d', '%s'] ); } /** * Apply content to product * * @param int $product_id Product ID * @param string $content_type Content type * @param string $content Content to apply * @param string $write_mode Write mode for FAQ content ('append' or 'replace') * @param array $blueprint Denormalized blueprint attribution `{id,name,revision,builtin}` * for this draft, read off its own row, or empty for a * custom-prompts draft. * @param int $job_id Parent automation job id, for a content-type apply * that needs to write its own job log entry on refusal. * @return bool Success status */ private function applyContentToProduct($product_id, $content_type, $content, $write_mode = 'append', array $blueprint = array(), $job_id = 0) { $product_id = (int) $product_id; try { $product = wc_get_product($product_id); if (!$product) { return false; } try { $snapshot_fields = $this->buildSnapshotFields($product_id, $product, $content_type, $content); if (!empty($snapshot_fields)) { $snapshot_fields['blueprint_id'] = isset($blueprint['id']) ? (int) $blueprint['id'] : 0; $snapshot_fields['blueprint_name'] = isset($blueprint['name']) ? (string) $blueprint['name'] : ''; $snapshot_fields['blueprint_revision'] = isset($blueprint['revision']) ? (int) $blueprint['revision'] : 0; $snapshot_fields['blueprint_builtin'] = !empty($blueprint['builtin']); ContentApplyDispatcher::before($product_id, $snapshot_fields, 'automation'); } else { do_action( ContentApplyDispatcher::HOOK, array( 'product_id' => $product_id, 'source' => 'automation', ) ); } } catch (\Throwable $snapshot_error) { } $mark_type = null; $success = false; $skip_product_save = false; switch ($content_type) { case 'title': $product->set_name(sanitize_text_field($content)); $mark_type = 'title'; break; case 'description': $product->set_description(\AIPT\Utils\DescriptionSanitizer::clean($content)); $mark_type = 'description'; break; case 'short_description': $product->set_short_description(\AIPT\Utils\DescriptionSanitizer::clean($content)); $mark_type = 'description'; break; case 'tags': $skip_product_save = true; $success = $this->applyTagsContent($product_id, $content); break; case 'faq': $skip_product_save = true; $success = $this->applyFaqContent($product_id, $content, $write_mode, $job_id); break; case 'seo_meta': $skip_product_save = true; [$success, $seo_outcomes] = $this->applySeoMetaContent($product_id, $content); break; case 'image_alt': $skip_product_save = true; [$success, $alt_outcomes] = $this->applyImageAltContent($product_id, $content); break; default: SnapshotStore::handle_after_apply($product_id, false); return false; } if (!$skip_product_save) { $save_result = \AIPT\Api\Helpers\ProductSaveVerifier::save($product); if (!$save_result['landed']) { SnapshotStore::handle_after_apply($product_id, false); return false; } $success = true; if (null !== $mark_type) { ContentMarkService::mark($product_id, $mark_type, ['gen' => MetaKeys::GEN_AUTOMATION]); } } if (isset($seo_outcomes)) { SnapshotStore::finalizeStagedByField($product_id, $seo_outcomes); } elseif (isset($alt_outcomes)) { SnapshotStore::finalizeStagedByField($product_id, ['image_alt' => $alt_outcomes]); } else { SnapshotStore::handle_after_apply($product_id, $success); } return $success; } catch (\Throwable $e) { SnapshotStore::handle_after_apply($product_id, false); return false; } } /** * Apply tags to a product from a comma-separated draft value. * * Extracted from the former inline switch case so the dispatcher-based * apply flow can treat tags like every other non-product-save field. * * @param int $product_id Product id. * @param string $content Comma-separated tag names. * @return bool True when the tag write landed. */ private function applyTagsContent($product_id, $content) { $tag_names = array_map('trim', explode(',', (string) $content)); $tag_ids = []; foreach ($tag_names as $tag_name) { if (!empty($tag_name)) { $term = get_term_by('name', $tag_name, 'product_tag'); if (!$term) { $term = wp_insert_term($tag_name, 'product_tag'); if (!is_wp_error($term)) { $tag_ids[] = $term['term_id']; } } else { $tag_ids[] = $term->term_id; } } } if (empty($tag_ids)) { return false; } $term_result = wp_set_post_terms($product_id, $tag_ids, 'product_tag'); if (is_wp_error($term_result)) { return false; } ContentMarkService::mark((int) $product_id, 'tags', ['gen' => MetaKeys::GEN_AUTOMATION]); return true; } /** * Build the snapshot-dispatch payload for a draft content type. * * The payload shape mirrors the automation `$result` contract consumed by * SnapshotStore::handle_before_apply(): keys among * title|description|short_desc|tags|faq|seo_meta|image_alt. Only the * CURRENT (pre-apply) value is read by the listener; the payload values act * as presence flags (and, for text fields, the generated_value record). * * image_alt is pre-filtered to attachments that belong to this product, * matching applyImageAltContent()'s write filter, so the dispatcher never * stages a snapshot for an attachment the write will skip. * * @param int $product_id Product id. * @param string $content_type Content type from the draft row. * @param string $content Generated content about to be applied. * @return array Normalized result payload, or empty array to skip capture. */ /** * Build the snapshot-dispatch payload for a draft content type. * * Fields whose live value already equals the drafted content are omitted — * a no-op apply must not record a history entry whose "before" and "after" * are identical (the old direct-capture helpers skipped these too). * * @param int $product_id Product id being applied to. * @param \WC_Product $product The product being applied to. * @param string $content_type Content type from the draft row. * @param string $content Drafted content about to be applied. * @return array Normalized result payload, or empty array when there is * nothing that will actually change. */ private function buildSnapshotFields($product_id, $product, $content_type, $content) { switch ($content_type) { case 'title': if ((string) $product->get_name() === (string) $content) { return []; } return ['title' => (string) $content]; case 'description': if ((string) $product->get_description() === (string) $content) { return []; } return ['description' => (string) $content]; case 'short_description': if ((string) $product->get_short_description() === (string) $content) { return []; } return ['short_desc' => (string) $content]; case 'tags': $tag_names = array_values(array_filter(array_map('trim', explode(',', (string) $content)))); return empty($tag_names) ? [] : ['tags' => $tag_names]; case 'faq': $decoded = json_decode((string) $content, true); return (is_array($decoded) && !empty($decoded)) ? ['faq' => $decoded] : []; case 'seo_meta': $decoded = json_decode((string) $content, true); return (is_array($decoded) && !empty($decoded)) ? ['seo_meta' => $decoded] : []; case 'image_alt': $decoded = json_decode((string) $content, true); if (!is_array($decoded)) { return []; } $items = []; foreach ($decoded as $item) { if (!is_array($item)) { continue; } $attachment_id = absint($item['attachment_id'] ?? 0); if ($attachment_id <= 0 || !$this->attachmentBelongsToProduct($attachment_id, $product_id)) { continue; } $draft_alt = sanitize_text_field((string) ($item['alt_text'] ?? '')); if ((string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true) === $draft_alt) { continue; } $items[] = $item; } return empty($items) ? [] : ['image_alt' => $items]; default: return []; } } private function getProductImageAltData($product_id) { $product = wc_get_product($product_id); if (!$product) { return []; } $attachment_ids = []; $featured_id = (int) $product->get_image_id(); if ($featured_id > 0) { $attachment_ids[] = $featured_id; } foreach ((array) $product->get_gallery_image_ids() as $gallery_id) { $gallery_id = absint($gallery_id); if ($gallery_id > 0) { $attachment_ids[] = $gallery_id; } } $items = []; foreach (array_values(array_unique($attachment_ids)) as $attachment_id) { $items[] = [ 'attachment_id' => $attachment_id, 'alt_text' => sanitize_text_field((string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true)), ]; } return $items; } private function applyFaqContent($product_id, $content, $write_mode = 'append', $job_id = 0) { $decoded = json_decode((string) $content, true); if (!is_array($decoded)) { return false; } $faqs = []; foreach ($decoded as $faq) { if (!is_array($faq)) { continue; } $question = sanitize_text_field((string) ($faq['question'] ?? '')); $answer = wp_kses_post((string) ($faq['answer'] ?? '')); if ($question !== '' || $answer !== '') { $faqs[] = [ 'question' => $question, 'answer' => $answer, ]; } } if (empty($faqs)) { $this->last_approval_error = new \WP_Error( 'draft_empty_content', __('This FAQ draft has no complete question and answer pairs, so it was not applied.', 'ai-product-tools'), ['status' => 422] ); $this->logger->error( (int) $job_id, 'FAQ draft approval refused: the generated batch had no complete question and answer pairs.', ['product_id' => (int) $product_id, 'write_mode' => $write_mode] ); return false; } $release = \AIPT\Api\Helpers\ProductWriteLock::acquire((int) $product_id); if (!is_callable($release)) { return false; } try { wp_cache_delete($product_id, 'post_meta'); if ($write_mode === 'append') { $existing_json = get_post_meta($product_id, '_aipt_faq_data', true); $existing_faqs = (is_string($existing_json) && '' !== $existing_json) ? json_decode($existing_json, true) : []; if (is_array($existing_faqs)) { $faqs = FaqList::append($existing_faqs, $faqs); } } $json = wp_json_encode($faqs); if ($json === false) { return false; } $current = (string) get_post_meta($product_id, '_aipt_faq_data', true); $updated = false; if ($current !== $json) { $updated = update_post_meta($product_id, '_aipt_faq_data', wp_slash($json)); } if (false !== $updated || ContentMarkService::wroteLiveValue((int) $product_id, '_aipt_faq_data', $json)) { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision((int) $product_id); ContentMarkService::mark((int) $product_id, 'faq', ['gen' => MetaKeys::GEN_AUTOMATION]); return true; } return false; } finally { $release(); } } /** * Resolve FAQ writeMode from parent automation job settings. * * Returns 'append' or 'replace'. Defaults to 'append' when the job row * is missing, settings JSON is invalid, or writeMode is absent/invalid. * 'replace' is paid ('faqReplaceMode') and is re-gated at approval time * through aipt_faq_replace_enabled, like ContentReviewApplier: a definitive * denial appends; an unverifiable license refuses the approval so a * temporary outage never duplicates FAQs. * * @param int $job_id Automation job ID from the draft content row. * @return string 'append' or 'replace' * @throws \RuntimeException When replace cannot be verified right now. */ private function resolveFaqWriteMode(int $job_id): string { $jobs_table = $this->wpdb->prefix . 'aipt_automation_jobs'; $settings_json = $this->wpdb->get_var($this->wpdb->prepare( "SELECT settings FROM {$jobs_table} WHERE id = %d", $job_id )); if (empty($settings_json) || !is_string($settings_json)) { return 'append'; } $settings = json_decode($settings_json, true); if (!is_array($settings) || !isset($settings['writeMode'])) { return 'append'; } $mode = sanitize_text_field((string) $settings['writeMode']); if ($mode !== 'replace') { return 'append'; } if (apply_filters('aipt_faq_replace_enabled', false)) { return 'replace'; } if (PlanDenial::isVerificationUnavailable(PlanDenial::reason('faqReplaceMode', PlanDenial::PLAN_PAID))) { $this->last_approval_error = PlanDenial::error( 'faqReplaceMode', PlanDenial::PLAN_PAID, __('Replacing existing FAQs requires a paid plan.', 'ai-product-tools') ); throw new \RuntimeException('FAQ replace mode could not be verified; approval refused.'); } return 'append'; } /** * Apply a seo_meta draft and report PER-FIELD outcomes. * * @return array{0:bool,1:array} [overall success, outcomes * keyed by canonical snapshot field_type (seo_meta_title / * seo_meta_description) for per-field snapshot finalization]. */ private function applySeoMetaContent($product_id, $content) { $decoded = json_decode((string) $content, true); if (!is_array($decoded)) { return [false, []]; } $detected_plugin = SeoPluginDetector::detect(); if (null === $detected_plugin || empty($detected_plugin['plugin_slug'])) { return [false, []]; } $write_data = SeoMetaWriter::buildWriteData($decoded, (string) $detected_plugin['plugin_slug']); if (empty($write_data)) { return [false, []]; } $writer = new SeoMetaWriter(); $results = $writer->bulkWrite($product_id, $write_data, (string) $detected_plugin['plugin_slug'], MetaKeys::GEN_AUTOMATION); $success = true; $outcomes = []; foreach (array_keys($write_data) as $key) { $ok = !empty($results[$key]); if (!$ok) { $success = false; } if ('title' === $key) { $outcomes['seo_meta_title'] = $ok; } elseif ('description' === $key) { $outcomes['seo_meta_description'] = $ok; } } return [$success, $outcomes]; } /** * Apply an image_alt draft and report PER-ATTACHMENT outcomes. * * @return array{0:bool,1:array} [overall success (at least one * attachment written or already correct), outcomes keyed by * attachment_id — true only when that write landed — for * per-subject snapshot finalization]. */ private function applyImageAltContent($product_id, $content) { $decoded = json_decode((string) $content, true); if (!is_array($decoded)) { return [false, []]; } $updated = false; $alt_changed = false; $outcomes = []; foreach ($decoded as $item) { if (!is_array($item)) { continue; } $attachment_id = absint($item['attachment_id'] ?? 0); if ($attachment_id <= 0 || !$this->attachmentBelongsToProduct($attachment_id, $product_id)) { continue; } $alt_text = sanitize_text_field((string) ($item['alt_text'] ?? '')); $current_alt = (string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true); if ($current_alt === $alt_text) { $updated = true; continue; } $outcomes[$attachment_id] = false; if (!empty(update_post_meta($attachment_id, '_wp_attachment_image_alt', wp_slash($alt_text)))) { $updated = true; $alt_changed = true; $outcomes[$attachment_id] = true; \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision($attachment_id); } } if ($alt_changed) { ContentMarkService::mark((int) $product_id, 'image_alt', ['gen' => MetaKeys::GEN_AUTOMATION]); \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision((int) $product_id); } return [$updated, $outcomes]; } private function attachmentBelongsToProduct($attachment_id, $product_id) { if (!wp_get_attachment_image_url($attachment_id, 'full')) { return false; } $product = wc_get_product($product_id); if (!$product) { return false; } if ((int) $product->get_image_id() === (int) $attachment_id) { return true; } $gallery_ids = array_map('absint', (array) $product->get_gallery_image_ids()); return in_array((int) $attachment_id, $gallery_ids, true); } /** * Reject draft content * * @param int $draft_id Draft content ID * @return bool Success status */ public function rejectDraftContent($draft_id) { $this->last_rejection_error = null; try { $result = $this->wpdb->update( $this->draft_table, [ 'status' => 'rejected', 'approved_by' => get_current_user_id(), 'approved_at' => current_time('mysql'), 'updated_at' => current_time('mysql') ], ['id' => $draft_id, 'status' => 'pending', 'record_kind' => 'review'], ['%s', '%d', '%s', '%s'], ['%d', '%s', '%s'] ); if ((int) $result < 1) { $this->last_rejection_error = $this->buildRejectConflictError((int) $draft_id); return false; } return true; } catch (\Exception $e) { return false; } } /** * Build the specific refusal for rejectDraftContent()'s 0-affected-rows * case by reading the row back: "no such (reviewable) draft" versus * "already claimed by a concurrent approve/reject". rejectDraftContent() * has no separate claim step, so this check happens after the fact * instead of before, unlike approveDraftContent()'s atomic claim. * * @param int $draft_id Draft content ID. * @return \WP_Error */ private function buildRejectConflictError($draft_id) { $status = $this->wpdb->get_var($this->wpdb->prepare( "SELECT status FROM {$this->draft_table} WHERE id = %d AND record_kind = %s", $draft_id, 'review' )); if (null === $status) { return new \WP_Error( 'draft_not_found', __('Draft content not found.', 'ai-product-tools'), ['status' => 404] ); } return new \WP_Error( 'draft_conflict', __('Draft content is not pending or is already being processed.', 'ai-product-tools'), ['status' => 409] ); } /** * Bulk approve draft content * * @param array $draft_ids Array of draft content IDs * @return array Results array with success/failure for each ID */ public function bulkApproveDraftContent($draft_ids) { $results = []; $this->last_bulk_failures = []; foreach ($draft_ids as $draft_id) { $results[$draft_id] = $this->approveDraftContent($draft_id); if (!$results[$draft_id] && $this->last_approval_error instanceof \WP_Error) { $this->last_bulk_failures[$draft_id] = $this->last_approval_error->get_error_message(); } } return $results; } /** * Bulk reject draft content * * Convenience wrapper over the single-draft rejectDraftContent(). This is * the bulk form of the core-free "undo" — it is NOT premium-gated (it * mirrors bulkApproveDraftContent()); the reject flow stays Free. * * @param array $draft_ids Array of draft content IDs * @return array Results array with success/failure for each ID */ public function bulkRejectDraftContent($draft_ids) { $results = []; $this->last_bulk_failures = []; foreach ($draft_ids as $draft_id) { $results[$draft_id] = $this->rejectDraftContent($draft_id); if (!$results[$draft_id] && $this->last_rejection_error instanceof \WP_Error) { $this->last_bulk_failures[$draft_id] = $this->last_rejection_error->get_error_message(); } } return $results; } /** * Bulk delete draft content * * @param array $draft_ids Array of draft content IDs * @return array Results array with success/failure for each ID */ public function bulkDeleteDraftContent($draft_ids) { $results = []; foreach ($draft_ids as $draft_id) { $results[$draft_id] = $this->deleteDraftContent($draft_id); } return $results; } /** * Delete draft content * * @param int $draft_id Draft content ID * @return bool Success status */ public function deleteDraftContent($draft_id) { try { $result = $this->wpdb->delete( $this->draft_table, ['id' => $draft_id, 'record_kind' => 'review'], ['%d', '%s'] ); return 1 === $result; } catch (\Exception $e) { return false; } } }