*/ private $logged_review_policy_override = []; public function __construct(JobLoggerInterface $logger) { global $wpdb; $this->wpdb = $wpdb; $this->job_products_table = $wpdb->prefix . 'aipt_job_products'; $this->logger = $logger; } /** * 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 drafts or directly to product. * * @param array $result Normalized result * @param array $content_settings Job content settings * @param DraftContentManager $draft_manager * @return string 'draft' when the result was queued for review, 'published' when at * least one field was written to the product, and 'unchanged' when * nothing was written (product not found, every field kept, or no * applicable field). */ public function applyResult(array $result, array $content_settings, DraftContentManager $draft_manager): string { $job_id = isset($result['job_id']) ? (int) $result['job_id'] : 0; $status = $this->resolveEffectiveStatus($content_settings, $job_id); if ($status === 'draft') { $this->saveDraft($result, $draft_manager); } else { /** * Action hook before applying automation result to product. * * SnapshotStore hooks here (priority 5) to stage the pre-AI values * before the new content is applied. * * @since 2.5.0 * @param array $result The result data to be applied. * @param DraftContentManager $draft_manager Draft content manager instance. * @param object $logger Logger instance. */ $snapshot_result = $result; $snapshot_result['source'] = 'automation'; 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; try { do_action( 'aipt_before_apply_result', $snapshot_result, $draft_manager, $this->logger ); $field_results = $this->applyToProduct( $result, $content_settings ); } catch ( \Throwable $e ) { SnapshotStore::finalizeStaged( $product_id, false ); throw $e; } SnapshotStore::finalizeStagedByField( $product_id, $field_results ); return $this->assertSomeFieldLanded( $field_results ) ? 'published' : 'unchanged'; } return 'draft'; } /** * 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; } 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 draft * 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_draft_review_enabled', false)) { throw new \Exception( 'This job is configured to save results as drafts for 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, 'This run\'s results were routed to Draft Review because the site Review Policy is enabled, instead of 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' => current_time('mysql'), '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' => current_time('mysql'), ]; $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' ] ); } /** * saveDraftContent() `$opts` for one piece, from transformToUnifiedFormat()'s * per-piece `blueprintByPiece` map. Empty for a piece with no recorded * blueprint (a custom-prompts write), which leaves every column at its * DB default. * * @param array $result Unified per-product result (carries blueprintByPiece). * @param string $piece saveDraft() piece type. * @return array */ private function blueprintOptsForPiece(array $result, string $piece): array { $blueprint = $result['blueprintByPiece'][$piece] ?? null; if (!is_array($blueprint)) { return []; } return [ 'blueprint_id' => isset($blueprint['id']) ? (int) $blueprint['id'] : 0, 'blueprint_name' => isset($blueprint['name']) ? (string) $blueprint['name'] : '', 'blueprint_revision' => isset($blueprint['revision']) ? (int) $blueprint['revision'] : 0, 'blueprint_builtin' => !empty($blueprint['builtin']), ]; } private function saveDraft(array $result, DraftContentManager $draft_manager): void { $job_id = isset($result['job_id']) ? (int)$result['job_id'] : 0; $product_id = isset($result['product_id']) ? (int)$result['product_id'] : 0; $created_by = isset($result['created_by']) ? (int) $result['created_by'] : null; if ($job_id <= 0 || $product_id <= 0) { return; } $pieces = []; if (!empty($result['title'])) { $pieces[] = ['type'=>'title','content'=>$result['title'],'opts'=>$this->blueprintOptsForPiece($result, 'title')]; } if (!empty($result['description'])) { $pieces[] = ['type'=>'description','content'=>$result['description'],'opts'=>$this->blueprintOptsForPiece($result, 'description')]; } if (!empty($result['short_desc'])) { $pieces[] = ['type'=>'short_description','content'=>$result['short_desc'],'opts'=>$this->blueprintOptsForPiece($result, 'short_description')]; } if (!empty($result['tags']) && is_array($result['tags'])) { $tag_str = implode(', ', array_filter(array_map('strval', $result['tags']))); if ($tag_str !== '') { $pieces[] = ['type'=>'tags','content'=>$tag_str,'opts'=>$this->blueprintOptsForPiece($result, 'tags')]; } } if (!empty($result['faq']) && is_array($result['faq'])) { $content = wp_json_encode($result['faq']); if ($content !== false) { $pieces[] = ['type'=>'faq','content'=>$content,'opts'=>$this->blueprintOptsForPiece($result, 'faq')]; } } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { $content = wp_json_encode($result['seo_meta']); if ($content !== false) { $pieces[] = ['type'=>'seo_meta','content'=>$content,'opts'=>$this->blueprintOptsForPiece($result, 'seo_meta')]; } } if (!empty($result['image_alt']) && is_array($result['image_alt'])) { $content = wp_json_encode($result['image_alt']); if ($content !== false) { $pieces[] = ['type'=>'image_alt','content'=>$content,'opts'=>$this->blueprintOptsForPiece($result, 'image_alt')]; } } foreach ($pieces as $p) { try { $draft_id = $draft_manager->saveDraftContent($job_id, $product_id, $p['type'], $p['content'], null, $created_by, 'review', $p['opts']); } catch (\Throwable $e) { $this->logger->warning($job_id, 'Draft save failed', ['product_id'=>$product_id,'content_type'=>$p['type'],'error'=>$e->getMessage(), 'type' => 'DB']); throw new \Exception('Draft save failed for content type: ' . esc_html((string) $p['type']) . ': ' . esc_html($e->getMessage()), (int)($e->getCode() ?: 0), $e); } if (!$draft_id) { $this->logger->warning($job_id, 'Draft save returned false', ['product_id'=>$product_id,'content_type'=>$p['type'], 'type' => 'DB']); throw new \Exception('Draft save failed for content type: ' . esc_html((string) $p['type'])); } } } /** * 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 it * cannot be taken (another writer holds it, or the database has no advisory * lock support) the apply proceeds exactly as it did before rather than * silently discarding the job's work. $lock_held is threaded down so * applyFaq() does not re-acquire the same named lock — 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. * * @param array $result Normalized result payload. * @param array $content_settings Job content settings. * @return array Per-field write outcomes. */ private function applyToProduct(array $result, array $content_settings): 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.'; throw new \Exception($message); } if (!is_callable($release)) { return $this->applyToProductWrites($result, $content_settings, false); } try { return $this->applyToProductWrites($result, $content_settings, true); } 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_held Whether applyToProduct() already holds the * product write lock for this product. * @return array */ private function applyToProductWrites(array $result, array $content_settings, bool $lock_held = false): 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'; $keep_existing_title = 'empty_only' === $overwrite && $this->isFieldOccupied((string) $product->get_name()); $keep_existing_description = 'empty_only' === $overwrite && $this->isHtmlFieldOccupied((string) $product->get_description()); $keep_existing_short_desc = 'empty_only' === $overwrite && $this->isHtmlFieldOccupied((string) $product->get_short_description()); $keep_existing_tags = 'empty_only' === $overwrite && $this->hasExistingTags($product_id); $keep_existing_faq = 'empty_only' === $overwrite && $this->hasExistingFaq($product_id); $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; 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' ]); throw new \Exception('Product save failed for product ' . $product_id . ': ' . $e->getMessage(), (int)($e->getCode() ?: 0), $e); } if (!$product_saved) { 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; ContentMarkService::mark($product_id, 'title', $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 ((!empty($result['description']) && !$keep_existing_description) || (!empty($result['short_desc']) && !$keep_existing_short_desc)) { ContentMarkService::mark($product_id, 'description', $this->automationMarkMeta($job_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_held); } if (!empty($result['seo_meta']) && is_array($result['seo_meta'])) { $seo_meta_to_apply = $this->filterSeoMetaForOverwrite($result['seo_meta'], $this->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 (!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; } /** * "empty_only" occupancy test for a plain-text field (title): any * non-whitespace content counts as already filled. * * @param string $current Live current value. * @return bool */ private function isFieldOccupied(string $current): bool { return '' !== trim($current); } /** * "empty_only" occupancy test for an HTML-bearing field (description, * short description): the STRIPPED text must have non-whitespace * content, so empty markup (e.g. "

") still counts as empty — * mirrors DescriptionApplyAdapter's identical empty_only check on the * Content Structure engine's own apply path. * * @param string $current Live current value. * @return bool */ private function isHtmlFieldOccupied(string $current): bool { return '' !== trim(wp_strip_all_tags($current)); } /** * 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; } /** * "empty_only" occupancy test for tags: the whole field is kept once the * product has at least one product_tag term — never a partial merge of * new tags alongside existing ones, mirroring * DescriptionApplyAdapter::planTags()'s identical whole-field check. * * @param int $product_id Product id. * @return bool */ private function hasExistingTags(int $product_id): bool { $existing = function_exists('wp_get_post_terms') ? wp_get_post_terms($product_id, 'product_tag', ['fields' => 'ids']) : []; return is_array($existing) && !empty($existing); } /** * 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; } ContentMarkService::mark($product_id, 'tags', $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). Automation * drafts store 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 saveDraft() piece type (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; } /** * "empty_only" occupancy test for FAQ: whether the product already has * at least one stored FAQ entry, mirroring FaqApplyAdapter's identical * check on the Content Structure engine's own apply path. * * @param int $product_id Product id. * @return bool */ private function hasExistingFaq(int $product_id): bool { $raw = function_exists('get_post_meta') ? get_post_meta($product_id, '_aipt_faq_data', true) : ''; if (!is_string($raw) || '' === $raw) { return false; } $decoded = json_decode($raw, true); return is_array($decoded) && !empty($decoded); } /** * 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. * @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_held = false): bool { $release = null; if (!$lock_held) { $release = \AIPT\Api\Helpers\ProductWriteLock::acquire($product_id); if (!is_callable($release)) { return false; } } try { wp_cache_delete($product_id, 'post_meta'); $structured_faqs = $this->normalizeFaqs($faqs); 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)) { $structured_faqs = FaqList::append($existing_faqs, $structured_faqs); } } $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)) { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision($product_id); ContentMarkService::mark($product_id, 'faq', $this->automationMarkMeta($job_id)); return true; } return false; } finally { if (is_callable($release)) { $release(); } } } /** * Current SEO meta for the empty_only per-field check below, or an empty * array when the mode is 'replace' (never needs it) or no SEO plugin is * active (nothing to compare against; applySeoMeta() itself already * no-ops with no plugin detected). * * @param int $product_id Product id. * @param string $overwrite 'replace' | 'empty_only'. * @return array */ private function currentSeoInfo(int $product_id, string $overwrite): array { if ('empty_only' !== $overwrite) { return []; } $detected_plugin = SeoPluginDetector::detect(); if (null === $detected_plugin || empty($detected_plugin['plugin_slug'])) { return []; } return SeoPluginDetector::get_seo_info($product_id, $detected_plugin, false); } /** * Drop any SEO field the store already has, for an empty_only job — per * field, not the whole result, mirroring SeoMetaApplyAdapter's identical * per-field check on the Content Structure engine's own apply path. A * plain decision function (no I/O) for testability: the caller resolves * $current_seo_info once via currentSeoInfo(). * * @param array $seo_meta Generated SEO fields (meta_title / meta_description / focus_keyword). * @param array $current_seo_info SeoPluginDetector::get_seo_info() shape, or []. * @param string $overwrite 'replace' | 'empty_only'. * @return array Same shape as $seo_meta, with already-filled fields removed under empty_only. */ private function filterSeoMetaForOverwrite(array $seo_meta, array $current_seo_info, string $overwrite): array { if ('empty_only' !== $overwrite) { return $seo_meta; } $info_key_for = [ 'meta_title' => 'meta_title', 'meta_description' => 'meta_description', 'focus_keyword' => 'focus_keyword', ]; foreach ($info_key_for as $seo_meta_key => $info_key) { if (!isset($seo_meta[$seo_meta_key])) { continue; } $current_value = trim(SeoFieldValueNormalizer::flatten($current_seo_info[$info_key] ?? '')); if ('' !== $current_value) { unset($seo_meta[$seo_meta_key]); } } return $seo_meta; } /** * 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 ($current_alt === $alt_text) { continue; } if ('empty_only' === $overwrite && '' !== trim($current_alt)) { 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; \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision($attachment_id); } } if ($alt_changed) { ContentMarkService::mark($product_id, 'image_alt', $this->automationMarkMeta($job_id)); \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision($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); } }