*/ private $logged_review_policy_override = []; /** * Job id => refusal reason => true, for the setup refusals of the review * queue (no SEO plugin, an image the product does not own) this instance * already logged: such a refusal is the same for every product of a job, * so it is logged once per job and reason in each batch (one * ResultProcessor per cron tick), not once per product. * * @var array> */ private $logged_review_refusals = []; /** @var ReviewQueueStager|null Test seam; null means the stager the Business build offers when a result is staged. */ private $review_stager; /** * @param JobLoggerInterface $logger The job log. * @param ReviewQueueStager|null $review_stager Test seam; every real caller omits it. */ public function __construct(JobLoggerInterface $logger, ?ReviewQueueStager $review_stager = null) { global $wpdb; $this->wpdb = $wpdb; $this->job_products_table = $wpdb->prefix . 'aipt_job_products'; $this->logger = $logger; $this->review_stager = $review_stager; } /** * Transform raw tool results to a unified structure suitable for persistence. * Input format depends on tool; output is normalized per product id. * * @param int $job_id * @param array $raw_results * @return array[] Array of per-product result arrays */ public function transformToUnifiedFormat(int $job_id, array $raw_results): array { $grouped = []; $image_alt_eligibility_seeded = []; foreach ($raw_results as $item) { if (!is_array($item)) { continue; } $product_id = isset($item['product_id']) ? (int) $item['product_id'] : 0; if ($product_id <= 0) { continue; } if (!isset($grouped[$product_id])) { $grouped[$product_id] = [ 'job_id' => $job_id, 'product_id' => $product_id, 'title' => null, 'description' => null, 'short_desc' => null, 'tags' => [], 'faq' => null, 'seo_meta' => null, 'image_alt' => [], 'raw' => [], 'executionPath' => null, 'blueprint' => null, 'findings' => [], 'eligibility' => null, 'contextHash' => null, 'sourcesUsed' => [], 'blueprintByPiece' => [], ]; } $type = isset($item['type']) ? sanitize_text_field((string) $item['type']) : ''; $text = isset($item['text']) ? (string) $item['text'] : null; $is_image_alt_item = isset($item['attachment_id'], $item['alt_text']); if (null === $grouped[$product_id]['executionPath'] && array_key_exists('executionPath', $item)) { $grouped[$product_id]['executionPath'] = is_string($item['executionPath']) ? $item['executionPath'] : null; $grouped[$product_id]['blueprint'] = isset($item['blueprint']) && is_array($item['blueprint']) ? $item['blueprint'] : null; $grouped[$product_id]['findings'] = isset($item['findings']) && is_array($item['findings']) ? array_values($item['findings']) : []; $grouped[$product_id]['eligibility'] = isset($item['eligibility']) && is_array($item['eligibility']) ? $item['eligibility'] : null; $grouped[$product_id]['contextHash'] = isset($item['contextHash']) ? (string) $item['contextHash'] : null; $grouped[$product_id]['sourcesUsed'] = isset($item['sourcesUsed']) && is_array($item['sourcesUsed']) ? array_values($item['sourcesUsed']) : []; if ($is_image_alt_item) { $image_alt_eligibility_seeded[$product_id] = true; } } elseif ( $is_image_alt_item && !empty($image_alt_eligibility_seeded[$product_id]) && isset($item['eligibility']) && is_array($item['eligibility']) ) { $merged_eligibility = is_array($grouped[$product_id]['eligibility']) ? $grouped[$product_id]['eligibility'] : []; $merged_eligibility['requiresReview'] = !empty($merged_eligibility['requiresReview']) || !empty($item['eligibility']['requiresReview']); if (array_key_exists('canApply', $item['eligibility']) && empty($item['eligibility']['canApply'])) { $merged_eligibility['canApply'] = false; } $merged_eligibility['blockers'] = array_merge( is_array($merged_eligibility['blockers'] ?? null) ? $merged_eligibility['blockers'] : [], is_array($item['eligibility']['blockers'] ?? null) ? $item['eligibility']['blockers'] : [] ); $grouped[$product_id]['eligibility'] = $merged_eligibility; if (!empty($item['findings']) && is_array($item['findings'])) { $grouped[$product_id]['findings'] = array_merge($grouped[$product_id]['findings'], array_values($item['findings'])); } } if ($grouped[$product_id]['title'] === null) { $title = isset($item['title']) ? (string) $item['title'] : null; if ($title === null && $type === 'title') { if (!empty($text)) { $title = $text; } elseif (!empty($item['variants']) && is_array($item['variants'])) { $first = reset($item['variants']); if (is_string($first) && $first !== '') { $title = $first; } } } if (!empty($title)) { $grouped[$product_id]['title'] = $title; $this->setPieceBlueprint($grouped[$product_id], 'title', $item); } } if ($grouped[$product_id]['description'] === null) { $description = isset($item['description']) ? (string) $item['description'] : null; if ($description === null && $type === 'full' && !empty($text)) { $description = $text; } if (!empty($description)) { $grouped[$product_id]['description'] = $description; $this->setPieceBlueprint($grouped[$product_id], 'description', $item); } } if ($grouped[$product_id]['short_desc'] === null) { $short_desc = isset($item['short_description']) ? (string) $item['short_description'] : null; if ($short_desc === null && $type === 'short' && !empty($text)) { $short_desc = $text; } if (!empty($short_desc)) { $grouped[$product_id]['short_desc'] = $short_desc; $this->setPieceBlueprint($grouped[$product_id], 'short_description', $item); } } $tags_arr = []; if (isset($item['tags']) && is_array($item['tags'])) { $tags_arr = array_values(array_filter(array_map('strval', $item['tags']))); } elseif ($type === 'tags' && is_string($text)) { $parts = array_map('trim', explode(',', $text)); $tags_arr = array_values(array_filter($parts, function($v){ return $v !== ''; })); } if (!empty($tags_arr)) { $existing = $grouped[$product_id]['tags']; $merged = array_values(array_unique(array_merge($existing, $tags_arr))); $grouped[$product_id]['tags'] = $merged; $this->setPieceBlueprint($grouped[$product_id], 'tags', $item); } if ($grouped[$product_id]['faq'] === null && !empty($item['faqs']) && is_array($item['faqs'])) { $faqs = $this->normalizeFaqs($item['faqs']); if (!empty($faqs)) { $grouped[$product_id]['faq'] = $faqs; $this->setPieceBlueprint($grouped[$product_id], 'faq', $item); } } if ($grouped[$product_id]['seo_meta'] === null) { $seo_meta = []; if (isset($item['meta_title']) && is_string($item['meta_title'])) { $meta_title = trim(sanitize_text_field($item['meta_title'])); if ($meta_title !== '') { $seo_meta['meta_title'] = $meta_title; } } if (isset($item['meta_description']) && is_string($item['meta_description'])) { $meta_description = trim(sanitize_textarea_field($item['meta_description'])); if ($meta_description !== '') { $seo_meta['meta_description'] = $meta_description; } } if (isset($item['focus_keyword']) && is_string($item['focus_keyword'])) { $focus_keyword = trim(sanitize_text_field($item['focus_keyword'])); if ($focus_keyword !== '') { $seo_meta['focus_keyword'] = $focus_keyword; } } if (!empty($seo_meta)) { $grouped[$product_id]['seo_meta'] = $seo_meta; $this->setPieceBlueprint($grouped[$product_id], 'seo_meta', $item); } } if (isset($item['attachment_id'], $item['alt_text'])) { $status = isset($item['status']) ? sanitize_text_field((string) $item['status']) : ''; if ($status !== 'error' && $status !== 'rejected') { $attachment_id = (int) $item['attachment_id']; $alt_text = trim(sanitize_text_field((string) $item['alt_text'])); if ($attachment_id > 0 && $alt_text !== '') { $grouped[$product_id]['image_alt'][] = [ 'attachment_id' => $attachment_id, 'alt_text' => $alt_text, 'status' => $status, ]; $this->setPieceBlueprint($grouped[$product_id], 'image_alt', $item); } } } $grouped[$product_id]['raw'][] = $item; } return array_values($grouped); } /** * Check whether a normalized result contains content that can be applied. * * @param array $result Normalized result payload. * @return bool True when at least one applicable content field is present. */ public function hasApplicableContent(array $result): bool { if ( isset($result['eligibility']) && is_array($result['eligibility']) && array_key_exists('canApply', $result['eligibility']) && empty($result['eligibility']['canApply']) ) { return false; } foreach (['title', 'description', 'short_desc'] as $field) { if (isset($result[$field]) && is_string($result[$field]) && trim($result[$field]) !== '') { return true; } } foreach (['tags', 'faq'] as $field) { if (!empty($result[$field]) && is_array($result[$field]) && $this->arrayHasNonEmptyValue($result[$field])) { return true; } } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { foreach ($result['seo_meta'] as $value) { if (is_string($value) && trim($value) !== '') { return true; } } } if (!empty($result['image_alt']) && is_array($result['image_alt'])) { foreach ($result['image_alt'] as $item) { if (is_array($item) && isset($item['alt_text']) && trim((string) $item['alt_text']) !== '') { return true; } } } return false; } private function arrayHasNonEmptyValue(array $items): bool { foreach ($items as $item) { if (is_array($item)) { if ($this->arrayHasNonEmptyValue($item)) { return true; } continue; } if (trim((string) $item) !== '') { return true; } } return false; } /** * Apply a single result either to the review queue or directly to product. * * On the review path a product counts as done when a field was newly * staged, or when nothing failed and a proposal of it already waits (or is * being approved). A field refused for a setup reason is a warning. A * product with a failed field and nothing newly staged fails, so Retry * failed offers that field again; so does a product with nothing in To * review. * * @param array $result Normalized result * @param array $content_settings Job content settings * @return string 'draft' when at least one field of the result was newly * staged in the review queue (the routing value and outcome * token keep their old name), 'published' when at least one * field was written to the product, 'waiting' when nothing * was newly staged, nothing failed and a proposal of the * product already waits in the queue or is being approved, * and 'unchanged' when nothing was written (product not * found, every field kept, or no applicable field). * JobExecutor turns 'waiting' into 'unchanged' right after * the call, so no other consumer sees it. * @throws \Exception When the review queue is not available, a field * failed with nothing newly staged, nothing is in To * review, or the product write failed. */ public function applyResult(array $result, array $content_settings): string { $job_id = isset($result['job_id']) ? (int) $result['job_id'] : 0; $status = $this->resolveEffectiveStatus($content_settings, $job_id); if ($status === 'draft') { return $this->stageForReview($result, $content_settings); } else { $snapshot_result = $result; if ( ! empty( $snapshot_result['image_alt'] ) && is_array( $snapshot_result['image_alt'] ) ) { $filter_product_id = isset( $result['product_id'] ) ? (int) $result['product_id'] : 0; $snapshot_result['image_alt'] = array_values( array_filter( $snapshot_result['image_alt'], function ( $item ) use ( $filter_product_id ) { if ( ! is_array( $item ) ) { return false; } $attachment_id = isset( $item['attachment_id'] ) ? (int) $item['attachment_id'] : 0; if ( $attachment_id <= 0 || ! $this->attachmentBelongsToProduct( $attachment_id, $filter_product_id ) ) { return false; } $alt_text = sanitize_text_field( (string) ( $item['alt_text'] ?? '' ) ); return (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) !== $alt_text; } ) ); } $product_id = isset( $result['product_id'] ) ? (int) $result['product_id'] : 0; unset( $snapshot_result['product_id'], $snapshot_result['source'] ); $unstaged_results = array(); $field_results = ProductFieldWriter::apply( $product_id, 'automation', $snapshot_result, function () use ( $result, $content_settings, &$unstaged_results ): array { return $this->applyToProduct( $result, $content_settings, $unstaged_results ); }, array( 'finish_per_field' => true ) ); if ( ! $this->assertSomeFieldLanded( $field_results + $unstaged_results ) ) { return 'unchanged'; } $this->logPartialResult( $job_id, $product_id, $field_results + $unstaged_results ); return 'published'; } } /** * Say in the job log what a published result left out. * * A result counts as published when one of its fields landed, also when * another field or image did not, and automation has no retry for one * item: the job log is where the merchant learns which part of the * product was not written. * * @param int $job_id Applying job id. * @param int $product_id Product id. * @param array $field_results Per-field outcomes of the write; image alt is a map of attachment id to outcome. * @return void */ private function logPartialResult(int $job_id, int $product_id, array $field_results): void { $fields = []; $attachments = []; foreach ($field_results as $field => $outcome) { if (is_array($outcome)) { foreach ($outcome as $attachment_id => $landed) { if (empty($landed)) { $attachments[] = (int) $attachment_id; } } } elseif (empty($outcome)) { $fields[] = (string) $field; } } if ([] === $fields && [] === $attachments) { return; } $this->logger->warning($job_id, 'Part of the result could not be written to the product', [ 'product_id' => $product_id, 'fields' => $fields, 'attachment_ids' => $attachments, ]); } /** * Refuse an apply in which every attempted field failed to write. * * A partial failure stays non-fatal (the landed fields keep their history), * but a result that wrote nothing must not be recorded as a completed * product. Nothing attempted (no-op) is left alone. * * @param array $field_results Per-field outcomes from applyToProduct(). * @return bool True when at least one field was written, false when nothing was attempted. * @throws \Exception When fields were attempted and none landed. */ private function assertSomeFieldLanded(array $field_results): bool { $attempted = []; foreach ($field_results as $field => $outcome) { if (is_array($outcome)) { if (in_array(true, $outcome, true)) { return true; } if (!empty($outcome)) { $attempted[] = $field; } } elseif (!empty($outcome)) { return true; } else { $attempted[] = $field; } } if (empty($attempted)) { return false; } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message; REST layer controls output escaping. throw new \Exception('No generated field could be written (' . implode(', ', $attempted) . ')'); } /** * Resolve the effective apply-routing status for a result. * * Pure decision helper — performs NO database writes and never mutates * existing rows. Returns 'draft' when the generated content must be routed * to the review queue, otherwise the normalized job status. * * @param array $content_settings Job content settings (may carry 'status'). * @return string 'draft' to queue for review, otherwise the job status. * @throws \Exception When the job was explicitly configured for review * routing but the entitlement that requires has lapsed * (safety-critical fail-closed — see below). */ /** * Resolve the effective routing status for a result. * * @param array $content_settings Job content settings. * @param int $job_id Applying automation job id (threaded to * the aipt_automation_force_review filter; * 0 when unknown — preserves prior behavior). * @return string */ private function resolveEffectiveStatus(array $content_settings, int $job_id = 0): string { $raw = isset($content_settings['status']) ? $content_settings['status'] : 'published'; $status = strtolower(sanitize_text_field((string) $raw)); if ('draft' === $status && ! apply_filters('aipt_content_review_enabled', false)) { throw new \Exception( 'This job is configured to send results to To review, but the required plan entitlement is no longer active. The result was not applied to avoid publishing without review.' ); } if ('draft' !== $status && $this->reviewPolicyForcesDraft($job_id)) { if (empty($this->logged_review_policy_override[$job_id])) { $this->logged_review_policy_override[$job_id] = true; $this->logger->warning( $job_id, 'The site Review Policy is on, so this run\'s results go to review instead of following the job\'s configured status.', ['configured_status' => $status] ); } return 'draft'; } return $status; } /** * Whether the Business review policy is active and forces review routing. * * Both conditions must hold: * 1. The opt-in switch (aipt_review_policy_enabled) is on — the policy is * inert until the site owner enables it. * 2. The premium-owned 'aipt_automation_force_review' filter returns true. * This always-shipped code carries NO license check (G9 free-scope); * src/Premium's ReviewPolicyService is the sole registrant and owns the * Business entitlement decision. On a free build the premium file is * stripped so the filter is unregistered and the false default makes * this a no-op. * * @param int $job_id Applying automation job id (threaded to the filter; 0 when unknown). * @return bool */ private function reviewPolicyForcesDraft(int $job_id = 0): bool { if (empty(get_option('aipt_review_policy_enabled', false))) { return false; } return (bool) apply_filters('aipt_automation_force_review', false, $job_id); } /** * Persist success for single product with result payload. */ public function recordSuccess(int $job_id, int $product_id, array $result_payload): void { $this->wpdb->update( $this->job_products_table, [ 'status' => 'completed', 'result' => wp_json_encode($result_payload), 'processed_at' => \AIPT\Api\AutomationJobs\JobTime::now(), 'error_message'=> null, ], [ 'job_id' => $job_id, 'product_id' => $product_id ], [ '%s', '%s', '%s' ], [ '%d', '%d' ] ); } /** * Persist failure for a single product. * * @param int $job_id * @param int $product_id * @param string $message * @param array $result_payload Optional provenance to keep even on a * failed item (e.g. a content structure * result held back rather than applied: * its blueprint/revision/findings should * still be visible). Additive: * an empty array behaves exactly as * before. */ public function recordFailure(int $job_id, int $product_id, string $message, array $result_payload = []): void { $data = [ 'status' => 'failed', 'error_message' => $message, 'processed_at' => \AIPT\Api\AutomationJobs\JobTime::now(), ]; $formats = [ '%s', '%s', '%s' ]; if (!empty($result_payload)) { $result_json = wp_json_encode($result_payload); $data['result'] = is_string($result_json) && $result_json !== '' ? $result_json : '{}'; $formats[] = '%s'; } $this->wpdb->update( $this->job_products_table, $data, [ 'job_id' => $job_id, 'product_id' => $product_id ], $formats, [ '%d', '%d' ] ); } /** * Setup refusals of the review queue, in the words of the job log. */ private const REVIEW_REFUSAL_LABELS = [ 'no_seo_plugin' => 'no SEO plugin is active', 'no_focus_keyword_field' => 'the active SEO plugin has no focus keyword field', 'not_product_image' => 'the image does not belong to the product', 'not_usable_image' => 'the image file is missing', 'invalid_value' => 'the value could not be stored', 'product_not_eligible' => 'the product is not eligible', 'invalid_request' => 'the request named no product or no job', ]; /** * Send the fields of one product's result to the review queue. * * The job owner is the row's creator: the job runs from cron, so no user * is logged in. A site without the queue (no Business stager, or a plan * that no longer includes it) refuses, and nothing is written: the result * is never applied live in its place. * * Under "only fill empty" the fields the product already holds are not * sent (the stager only keeps the choice for the approval-time check, and * a proposal the reviewer is certain to refuse is noise). Every field * that is sent must come back staged or skipped: one the stager drops * without a word counts as failed. * * The rule: a product counts as done when a field was newly staged, or * when nothing failed and a proposal of it already waits (or is being * approved). JobExecutor skips a product whose every field already waits * before the provider call (ReviewQueueStager::settledAutomationTargets()); * 'waiting' here is what remains of that check after a call was paid: a * proposal staged meanwhile, a settings change in the middle of a tick, or * a held-back content template result. A field refused for a setup reason is a warning, logged once * per job and reason in each batch (one ResultProcessor per tick). A * product with a failed field and nothing newly staged fails, so Retry * failed offers that field again; so does a product with nothing in To * review. * * @param array $result Unified per-product result. * @param array $content_settings Job content settings. * @return string 'draft' when a field was newly staged, 'waiting' when * nothing was newly staged, nothing failed and a proposal * already waits or is being approved (setup refusals among * the skips are logged), 'unchanged' when nothing was left * to offer: under "only fill empty" the fields the product * already holds, and in both modes a title or image alt * equal to the stored one. * @throws \Exception When the queue is not available, the stager failed, * nothing was newly staged and a field failed, or * nothing is in To review because every field was * refused for a setup reason. */ private function stageForReview(array $result, array $content_settings): string { $job_id = isset($result['job_id']) ? (int) $result['job_id'] : 0; $product_id = isset($result['product_id']) ? (int) $result['product_id'] : 0; $stager = $this->review_stager ?? ReviewQueueStaging::stager(); if (null === $stager) { throw new \Exception( 'This job is configured to send results to To review, but this site has no review queue. The result was not applied to avoid publishing without review.' ); } if (!apply_filters('aipt_content_review_enabled', false)) { throw new \Exception( 'This job is configured to send results to To review, but the required plan entitlement is no longer active. The result was not applied to avoid publishing without review.' ); } $created_by = (int) ($content_settings['created_by'] ?? 0); if ($created_by <= 0) { $created_by = (int) ($result['created_by'] ?? 0); } if ($created_by <= 0) { throw new \Exception( 'The result could not be sent to To review: the job has no owner to attribute the proposals to.' ); } $overwrite = 'empty_only' === ($content_settings['overwrite'] ?? 'replace') ? 'empty_only' : 'replace'; $filtered = $this->dropFieldsTheJobKeeps($result, $product_id, $overwrite); $offered = $this->offeredReviewFields($filtered); if ([] === $offered) { return 'unchanged'; } $context = [ 'job_id' => $job_id, 'created_by' => $created_by, 'overwrite' => $overwrite, ]; if (isset($content_settings['writeMode'])) { $context['writeMode'] = (string) $content_settings['writeMode']; } try { $outcome = $stager->stageAutomationResult($filtered, $context); } catch (\Throwable $e) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message; REST layer controls output escaping. throw new \Exception('The result could not be sent to To review: ' . $e->getMessage(), (int) ($e->getCode() ?: 0), $e); } $staged = is_array($outcome['staged'] ?? null) ? array_values(array_map('strval', $outcome['staged'])) : []; $skipped = $this->normalizeSkippedFields($outcome['skipped'] ?? []); $accounted = array_merge($staged, array_column($skipped, 'field')); foreach ($offered as $field) { if (!in_array($field, $accounted, true)) { $skipped[] = ['field' => $field, 'reason' => 'not_staged']; } } $failed = []; $waiting = false; $refusals = []; foreach ($skipped as $skip) { if ('stage_failed' === $skip['reason'] || 'not_staged' === $skip['reason']) { $failed[] = $skip; } elseif ('already_waiting' === $skip['reason'] || 'in_progress' === $skip['reason']) { $waiting = true; } else { $refusals[] = $skip; } } if ([] !== $staged) { $this->logReviewRefusals($job_id, $product_id, $refusals); if ([] !== $failed) { $this->logger->warning($job_id, 'Part of the result could not be sent to To review', [ 'product_id' => $product_id, 'fields' => $this->describeSkippedFields($failed), ]); } return 'draft'; } if ([] !== $failed) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message; REST layer controls output escaping. throw new \Exception('The result could not be sent to To review (' . implode('; ', $this->describeSkippedFields(array_merge($failed, $refusals))) . ')'); } if ($waiting) { $this->logReviewRefusals($job_id, $product_id, $refusals); return 'waiting'; } // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message; REST layer controls output escaping. throw new \Exception($this->noReviewTargetMessage($refusals)); } /** * Why a product ends as failed when the review queue refuses every field * its job would send: the message of the product row, in the words of the * job log. The post-call path throws it when nothing could be staged, and * the pre-call check fails the product with it before any provider call, * so a merchant sees the same reason either way. * * @param array $refusals The refused fields with their setup reasons. * @return string */ public function noReviewTargetMessage(array $refusals): string { return 'No generated field could be sent to To review (' . implode('; ', $this->describeSkippedFields($refusals)) . ')'; } /** * The stager's skipped list as field and reason pairs, whatever it holds. * * @param mixed $skipped The stager's answer. * @return array */ private function normalizeSkippedFields($skipped): array { $normalized = []; if (!is_array($skipped)) { return $normalized; } foreach ($skipped as $skip) { if (is_array($skip) && isset($skip['field'])) { $normalized[] = [ 'field' => (string) $skip['field'], 'reason' => (string) ($skip['reason'] ?? 'stage_failed'), ]; } } return $normalized; } /** * Skipped fields as "field: reason" lines. * * @param array $skips Skipped fields. * @return string[] */ private function describeSkippedFields(array $skips): array { $lines = []; foreach ($skips as $skip) { $reason = self::REVIEW_REFUSAL_LABELS[$skip['reason']] ?? ('stage_failed' === $skip['reason'] ? 'the review queue could not store it' : 'the review queue did not take it'); $lines[] = $skip['field'] . ': ' . $reason; } return $lines; } /** * Log the setup refusals of the review queue once per job and reason in * each batch (one ResultProcessor per tick, so the dedupe is per tick, not * per run): a missing SEO plugin or a variation-only image is the same for * every product of the job, and a catalog of thousands would drown the log. * * @param int $job_id Applying job id. * @param int $product_id The first product the reason was seen on. * @param array $refusals Skipped fields with a setup reason. * @return void */ public function logReviewRefusals(int $job_id, int $product_id, array $refusals): void { $by_reason = []; foreach ($refusals as $skip) { if (empty($this->logged_review_refusals[$job_id][$skip['reason']])) { $by_reason[$skip['reason']][] = $skip['field']; } } foreach ($by_reason as $reason => $fields) { $this->logged_review_refusals[$job_id][$reason] = true; $this->logger->warning( $job_id, 'Some fields could not be sent to To review: ' . (self::REVIEW_REFUSAL_LABELS[$reason] ?? $reason) . '. Only the first product with this problem in each batch is logged.', [ 'product_id' => $product_id, 'reason' => $reason, 'fields' => $fields, ] ); } } /** * The field names the stager is offered by a result, in its own naming: * title, description, short_description, tags, faq, seo_meta_title, * seo_meta_description, seo_focus_keyword and image_alt:{attachment id}. * A tags or FAQ value that is no array counts as offered too: the stager * drops it without a word, and stageForReview() must see that. * * @param array $result Unified per-product result. * @return string[] */ private function offeredReviewFields(array $result): array { $fields = []; foreach (['title' => 'title', 'description' => 'description', 'short_desc' => 'short_description'] as $key => $field) { if (isset($result[$key]) && is_scalar($result[$key]) && '' !== trim((string) $result[$key])) { $fields[] = $field; } } foreach (['tags' => 'tags', 'faq' => 'faq'] as $key => $field) { if (!empty($result[$key]) && (!is_array($result[$key]) || $this->arrayHasNonEmptyValue($result[$key]))) { $fields[] = $field; } } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { foreach (['meta_title' => 'seo_meta_title', 'meta_description' => 'seo_meta_description', 'focus_keyword' => 'seo_focus_keyword'] as $key => $field) { if (isset($result['seo_meta'][$key]) && is_string($result['seo_meta'][$key]) && '' !== trim($result['seo_meta'][$key])) { $fields[] = $field; } } } if (!empty($result['image_alt']) && is_array($result['image_alt'])) { foreach ($result['image_alt'] as $item) { if (!is_array($item)) { continue; } $attachment_id = (int) ($item['attachment_id'] ?? 0); if ($attachment_id > 0 && '' !== sanitize_text_field((string) ($item['alt_text'] ?? ''))) { $fields[] = 'image_alt:' . $attachment_id; } } } return $fields; } /** * Remove from a result what the live write would leave alone, so the review * queue is not offered a proposal the reviewer could only refuse. * * In both modes a title equal to the stored one and an image alt equal to * its stored one are no-ops and go. Under "only fill empty" a field the * product already holds goes too, by the same decisions the live write * makes (EmptyOnlyRule::keptFields(), filterSeoMeta(), keepsImageAlt()). A * product that cannot be read keeps its result as it is: the stager * refuses it with its own reason. * * @param array $result Unified per-product result. * @param int $product_id Product id. * @param string $overwrite 'replace' | 'empty_only'. * @return array The result without the dropped fields. */ private function dropFieldsTheJobKeeps(array $result, int $product_id, string $overwrite): array { $product = $product_id > 0 && function_exists('wc_get_product') ? wc_get_product($product_id) : null; if (!$product) { return $result; } $kept = EmptyOnlyRule::keptFields($product, $product_id, $overwrite); if (isset($result['title']) && (!empty($kept['title']) || sanitize_text_field((string) $result['title']) === (string) $product->get_name())) { unset($result['title']); } if (!empty($kept['description'])) { unset($result['description']); } if (!empty($kept['short_desc'])) { unset($result['short_desc']); } if (!empty($kept['tags'])) { unset($result['tags']); } if (!empty($kept['faq'])) { unset($result['faq']); } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { $result['seo_meta'] = EmptyOnlyRule::filterSeoMeta($result['seo_meta'], EmptyOnlyRule::currentSeoInfo($product_id, $overwrite), $overwrite); } if (!empty($result['image_alt']) && is_array($result['image_alt'])) { $result['image_alt'] = array_values(array_filter( $result['image_alt'], function ($item) use ($overwrite): bool { if (!is_array($item)) { return false; } $attachment_id = isset($item['attachment_id']) ? (int) $item['attachment_id'] : 0; if ($attachment_id <= 0) { return true; } $alt_text = sanitize_text_field((string) ($item['alt_text'] ?? '')); $current_alt = (string) get_post_meta($attachment_id, '_wp_attachment_image_alt', true); return !EmptyOnlyRule::keepsImageAlt($current_alt, $alt_text, $overwrite); } )); } return $result; } /** * Apply a normalized result to a product, returning the per-field write * outcome for snapshot finalization. * * The core WooCommerce fields (title/description/short_description) are * persisted by one atomic save(); the auxiliary fields (tags/faq/seo_meta/ * image_alt) are written independently afterwards. Each field's outcome is * reported separately so the caller finalizes that field's staged snapshot * on its OWN result — a field that landed keeps its history even when a * sibling field fails, and a failed field never records a fake change. * * @param array $result Normalized result. * @param array $content_settings Job content settings. * @return array Write outcomes keyed by snapshot field_type. * @throws \Exception When the core product save fails (nothing this apply * touched landed — the caller rolls back every staged * snapshot and records the product as failed). */ /** * Serialize the ENTIRE product apply behind the shared per-product advisory * mutex, not just its FAQ write. * * ProductWriteLock is the same mutex BatchSaveService (the Product Editor) * uses, so this is what stops two concurrent AI writers — two automation jobs * with overlapping filters, or an automation job racing a bulk generator or a * Content Review apply — from each reading and then each writing the same * product and silently losing one completed write. Previously only * applyFaq() took the lock, leaving the core WC_Product::save() and the tags * / SEO-meta / image-alt writes unprotected. * * The lock is an ADDITIVE safety measure, never a new precondition: when the * database has no advisory lock support the apply proceeds exactly as it did * before rather than silently discarding the job's work. $lock_settled is * threaded down so applyFaq() does not ask for the same named lock again: * on MySQL versions without recursive GET_LOCK its inner release would * otherwise drop this outer lock mid-apply, before the SEO and image-alt * writes, and without a lock backend its own refusal would keep the FAQ * from ever being written. * * @param array $result Normalized result payload. * @param array $content_settings Job content settings. * @param array $unstaged_results Filled with the outcomes of writes that have no snapshot. * @return array Per-field write outcomes. */ private function applyToProduct(array $result, array $content_settings, array &$unstaged_results = []): array { $product_id = isset($result['product_id']) ? (int) $result['product_id'] : 0; if ($product_id <= 0) { return []; } $release = \AIPT\Api\Helpers\ProductWriteLock::acquire($product_id); if (false === $release) { $message = 'Product ' . $product_id . ' is being written by another writer; this apply was skipped and can be retried.'; // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer-facing exception message, not user output. throw new \Exception($message); } if (!is_callable($release)) { return $this->applyToProductWrites($result, $content_settings, true, $unstaged_results); } try { return $this->applyToProductWrites($result, $content_settings, true, $unstaged_results); } finally { $release(); } } /** * The actual write sequence. Callers must reach this through * applyToProduct() so the product write lock is honored. * * @param array $result Normalized result payload. * @param array $content_settings Job content settings. * @param bool $lock_settled Whether applyToProduct() already asked for * the product write lock: it holds it, or the * database has no advisory lock at all. * @param array $unstaged_results Filled with the outcomes of writes that have no snapshot. * @return array */ private function applyToProductWrites(array $result, array $content_settings, bool $lock_settled = false, array &$unstaged_results = []): array { $product_id = (int) $result['product_id']; if ($product_id <= 0) { return []; } $job_id = isset($result['job_id']) ? (int) $result['job_id'] : 0; $product = function_exists('wc_get_product') ? wc_get_product($product_id) : null; if (!$product) { $this->logger->warning($job_id, 'Product not found for apply', [ 'product_id' => $product_id, 'type' => 'WC_UPDATE' ]); return []; } $overwrite = 'empty_only' === ($content_settings['overwrite'] ?? 'replace') ? 'empty_only' : 'replace'; $kept = EmptyOnlyRule::keptFields($product, $product_id, $overwrite); $keep_existing_title = $kept['title']; $keep_existing_description = $kept['description']; $keep_existing_short_desc = $kept['short_desc']; $keep_existing_tags = $kept['tags']; $keep_existing_faq = $kept['faq']; $field_results = []; $should_save_product = false; $title = isset($result['title']) ? sanitize_text_field((string) $result['title']) : ''; if (!empty($title) && !$keep_existing_title) { $product->set_name($title); $should_save_product = true; } if (!empty($result['description']) && !$keep_existing_description) { $product->set_description(\AIPT\Utils\DescriptionSanitizer::clean($result['description'])); $should_save_product = true; } if (!empty($result['short_desc']) && !$keep_existing_short_desc) { $product->set_short_description(\AIPT\Utils\DescriptionSanitizer::clean($result['short_desc'])); $should_save_product = true; } $product_saved = true; $description_set = (!empty($result['description']) && !$keep_existing_description) || (!empty($result['short_desc']) && !$keep_existing_short_desc); $changes = $description_set && is_callable([$product, 'get_changes']) ? (array) $product->get_changes() : []; $description_text_changed = [] !== array_intersect(array_keys($changes), ['description', 'short_description']); if ($should_save_product) { try { $save_result = \AIPT\Api\Helpers\ProductSaveVerifier::save($product); $product_saved = $save_result['landed']; } catch (\Throwable $e) { $this->logger->error((int) $result['job_id'], 'Product save failed', [ 'product_id' => $product_id, 'error' => $e->getMessage(), 'type' => 'WC_UPDATE' ]); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception message surfaces to the REST layer which controls output escaping. throw new \Exception('Product save failed for product ' . $product_id . ': ' . $e->getMessage(), (int)($e->getCode() ?: 0), $e); } if (!$product_saved) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception message; REST layer controls output escaping. throw new \Exception('Product save returned no result for product ' . $product_id . ' (core fields not persisted)'); } } if (!empty($title) && !$keep_existing_title) { $field_results['title'] = $product_saved; ProductFieldWriter::mark($product_id, 'title', MetaKeys::GEN_AUTOMATION, $this->automationMarkMeta($job_id)); } if (!empty($result['description']) && !$keep_existing_description) { $field_results['description'] = $product_saved; } if (!empty($result['short_desc']) && !$keep_existing_short_desc) { $field_results['short_description'] = $product_saved; } if ($description_set) { ProductFieldWriter::mark($product_id, 'description', MetaKeys::GEN_AUTOMATION, $this->automationMarkMeta($job_id)); if ($description_text_changed) { ProductFieldWriter::bump($product_id, $product_id); } } if (!empty($result['tags']) && is_array($result['tags']) && !$keep_existing_tags) { $field_results['tags'] = $this->applyTags($product_id, $result['tags'], $job_id); } if (!empty($result['faq']) && is_array($result['faq']) && !$keep_existing_faq) { $write_mode = isset($content_settings['writeMode']) ? sanitize_text_field((string) $content_settings['writeMode']) : 'append'; $field_results['faq'] = $this->applyFaq($product_id, $result['faq'], $write_mode, $job_id, $lock_settled); } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { $seo_meta_to_apply = EmptyOnlyRule::filterSeoMeta($result['seo_meta'], EmptyOnlyRule::currentSeoInfo($product_id, $overwrite), $overwrite); if (!empty($seo_meta_to_apply)) { $seo_results = $this->applySeoMeta($product_id, $seo_meta_to_apply, $job_id); if (array_key_exists('title', $seo_results)) { $field_results['seo_meta_title'] = $seo_results['title']; } if (array_key_exists('description', $seo_results)) { $field_results['seo_meta_description'] = $seo_results['description']; } if (array_key_exists('focus_keyword', $seo_results)) { $unstaged_results['seo_focus_keyword'] = $seo_results['focus_keyword']; } } } if (!empty($result['image_alt']) && is_array($result['image_alt'])) { $field_results['image_alt'] = $this->applyImageAlt($product_id, $result['image_alt'], $job_id, $overwrite); } return $field_results; } /** * Build the content-mark metadata for an automation apply, carrying the * applying job's id so the premium auto-on-publish breaker resets EXACTLY * that job's provider-quota failure streak on success * (AutoOnPublishService::onContentMarked). The job_id key is omitted when it * is unknown (0) so non-automation callers keep a byte-identical meta payload. * * @param int $job_id Applying automation job id (0 when unknown). * @return array{gen:string,job_id?:int} */ private function automationMarkMeta(int $job_id): array { $meta = ['gen' => MetaKeys::GEN_AUTOMATION]; if ($job_id > 0) { $meta['job_id'] = $job_id; } return $meta; } /** * Apply tags to a product. * * @param int $product_id Product id. * @param array $tag_names Tag names to apply. * @param int $job_id Applying automation job id. * @return bool True when at least one tag was written to the product. */ private function applyTags(int $product_id, array $tag_names, int $job_id = 0): bool { $tag_ids = []; foreach ($tag_names as $name) { $name = trim((string) $name); if ($name === '') { continue; } $term = get_term_by('name', $name, 'product_tag'); if ($term && !is_wp_error($term)) { $tag_ids[] = (int) $term->term_id; continue; } $created = wp_insert_term($name, 'product_tag'); if (!is_wp_error($created) && isset($created['term_id'])) { $tag_ids[] = (int) $created['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) || empty($term_result)) { return false; } ProductFieldWriter::mark($product_id, 'tags', MetaKeys::GEN_AUTOMATION, $this->automationMarkMeta($job_id)); return true; } /** * Record a piece's blueprint attribution the first time that piece is * set, never overwriting an already-recorded one (first-item-wins, * mirroring the content fields' own "=== null" guard above). The review * queue stores each raw item's OWN blueprint, not one value flattened * per product — a job can combine several generator forks per product * (e.g. description + short description), each potentially its own * Blueprint run. * * @param array $group `$grouped[$product_id]`, updated in place. * @param string $piece Piece name AutomationReviewStager::blueprintOpts() reads (title|description|short_description|tags|faq|seo_meta|image_alt). * @param array $item Raw per-item result payload. * @return void */ private function setPieceBlueprint(array &$group, string $piece, array $item): void { if (isset($group['blueprintByPiece'][$piece])) { return; } if (isset($item['blueprint']) && is_array($item['blueprint'])) { $group['blueprintByPiece'][$piece] = $item['blueprint']; } } private function normalizeFaqs(array $items): array { $faqs = []; foreach ($items 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, ]; } } return $faqs; } /** * Apply FAQ content to a product. * * @param int $product_id Product id. * @param array $faqs FAQ items. * @param string $write_mode 'append' or 'replace'. * @param int $job_id Applying automation job id. * @param bool $lock_settled Whether the caller already asked for the product * write lock (it holds it, or there is no lock backend). * @return bool True when the FAQ payload landed in post meta. */ private function applyFaq(int $product_id, array $faqs, string $write_mode, int $job_id = 0, bool $lock_settled = false): bool { $release = null; if (!$lock_settled) { $release = \AIPT\Api\Helpers\ProductWriteLock::acquire($product_id); if (false === $release) { return false; } } try { wp_cache_delete($product_id, 'post_meta'); $structured_faqs = $this->normalizeFaqs($faqs); $existing_json = get_post_meta($product_id, '_aipt_faq_data', true); $existing_faqs = (is_string($existing_json) && '' !== $existing_json) ? json_decode($existing_json, true) : []; $structured_faqs = FaqList::forWrite(is_array($existing_faqs) ? $existing_faqs : null, $structured_faqs, $write_mode); $json = wp_json_encode($structured_faqs); if ($json === false) { return false; } $updated = update_post_meta($product_id, '_aipt_faq_data', wp_slash($json)); if ((!is_wp_error($updated) && !empty($updated)) || ContentMarkService::wroteLiveValue($product_id, '_aipt_faq_data', $json)) { ProductFieldWriter::bump($product_id, $product_id); ProductFieldWriter::mark($product_id, 'faq', MetaKeys::GEN_AUTOMATION, $this->automationMarkMeta($job_id)); return true; } return false; } finally { if (is_callable($release)) { $release(); } } } /** * Apply SEO meta to a product. * * @param int $product_id Product id. * @param array $seo_meta SEO fields (meta_title / meta_description / focus_keyword). * @param int $job_id Applying automation job id. * @return array Per-field write outcomes keyed by SeoMetaWriter * WRITER keys ('title' / 'description' / * 'focus_keyword'). A missing key means the field * was not attempted. Callers map writer keys to * canonical snapshot field_types. */ private function applySeoMeta(int $product_id, array $seo_meta, int $job_id = 0): array { $detected_plugin = SeoPluginDetector::detect(); if (null === $detected_plugin || empty($detected_plugin['plugin_slug'])) { $failed = []; if (!empty($seo_meta['meta_title']) && is_string($seo_meta['meta_title'])) { $failed['title'] = false; } if (!empty($seo_meta['meta_description']) && is_string($seo_meta['meta_description'])) { $failed['description'] = false; } return $failed; } $write_data = SeoMetaWriter::buildWriteData($seo_meta, (string) $detected_plugin['plugin_slug']); if (empty($write_data)) { return []; } $writer = new SeoMetaWriter(); $results = $writer->bulkWrite($product_id, $write_data, (string) $detected_plugin['plugin_slug'], MetaKeys::GEN_AUTOMATION, $job_id); $field_results = []; foreach (array_keys($write_data) as $key) { $field_results[$key] = !empty($results[$key]); } return $field_results; } /** * Apply image alt text to a product's attachments. * * @param int $product_id Product id. * @param array $items Per-attachment alt items. * @param int $job_id Applying automation job id. * @return array Per-attachment write outcomes keyed by * attachment_id: true only when that attachment's * alt write landed. Passed straight to * finalizeStagedByField() as the image_alt map so * each staged row finalizes on its OWN write — * never one bool across N attachment rows. */ private function applyImageAlt(int $product_id, array $items, int $job_id = 0, string $overwrite = 'replace'): array { $alt_changed = false; $outcomes = array(); foreach ($items as $item) { if (!is_array($item)) { continue; } $attachment_id = isset($item['attachment_id']) ? (int) $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 (EmptyOnlyRule::keepsImageAlt($current_alt, $alt_text, $overwrite)) { continue; } $outcomes[$attachment_id] = false; $updated = update_post_meta($attachment_id, '_wp_attachment_image_alt', wp_slash($alt_text)); if ((!is_wp_error($updated) && !empty($updated)) || ContentMarkService::wroteLiveValue($attachment_id, '_wp_attachment_image_alt', $alt_text)) { $outcomes[$attachment_id] = true; $alt_changed = true; ProductFieldWriter::bump($product_id, $attachment_id); } } if ($alt_changed) { ProductFieldWriter::mark($product_id, 'image_alt', MetaKeys::GEN_AUTOMATION, $this->automationMarkMeta($job_id)); ProductFieldWriter::bump($product_id, $product_id); } return $outcomes; } private function attachmentBelongsToProduct(int $attachment_id, int $product_id): bool { $product = function_exists('wc_get_product') ? wc_get_product($product_id) : null; if (!$product || !wp_get_attachment_image_url($attachment_id, 'full')) { return false; } if ((int) $product->get_image_id() === $attachment_id) { return true; } $gallery_ids = array_map('absint', (array) $product->get_gallery_image_ids()); return in_array($attachment_id, $gallery_ids, true); } }