*/
private array $skippedFields = array();
public function __construct() {
$this->reviewStore = new ContentReviewStore();
$this->options = array();
}
/**
* Log debug message only when WP_DEBUG is enabled.
*
* @param string $message Debug message to log.
* @return void
*/
private function debugLog( string $message ): void {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
}
}
public function generate( array $productIds, array $contentTypes, array $options = array() ): GenerationResult {
$result = new GenerationResult();
$startTime = microtime( true );
$this->options = $this->normalizeOptions( $options );
$productIds = array_unique( array_map( 'absint', $productIds ) );
$contentTypes = $this->normalizeContentTypes( $contentTypes );
if ( empty( $productIds ) || empty( $contentTypes ) ) {
$result->errors[] = 'No products or content types specified';
return $result;
}
$chunks = array_chunk( $productIds, self::BATCH_SIZE );
foreach ( $chunks as $chunk ) {
$productsData = ProductDataProvider::bulkGet( $chunk, false );
foreach ( $chunk as $productId ) {
$productData = $productsData[ $productId ] ?? null;
if ( null === $productData ) {
$result->results[ $productId ] = new ProductResult( $productId );
$post_type = get_post_type( $productId );
$post_status = get_post_status( $productId );
if ( ! $post_type ) {
$result->results[ $productId ]->errors[] = sprintf(
'Product ID %d does not exist in the database.',
$productId
);
} elseif ( $post_type === 'product_variation' ) {
$parent_id = wp_get_post_parent_id( $productId );
$result->results[ $productId ]->errors[] = sprintf(
'Product ID %d is a variation (parent: %d). Use the parent product instead.',
$productId,
$parent_id ?: 0
);
} elseif ( ! in_array( $post_status, array( 'publish', 'draft', 'pending', 'private' ), true ) ) {
$result->results[ $productId ]->errors[] = sprintf(
'Product ID %d has status "%s" which is not supported. Supported statuses: publish, draft, pending, private.',
$productId,
$post_status ?: 'unknown'
);
} else {
$result->results[ $productId ]->errors[] = sprintf(
'Product ID %d could not be loaded (type: %s, status: %s). This may be a data integrity issue.',
$productId,
$post_type,
$post_status ?: 'unknown'
);
}
$result->failureCount++;
continue;
}
$productResult = $this->processProduct( $productId, $productData, $contentTypes );
$result->results[ $productId ] = $productResult;
if ( $productResult->success ) {
$result->successCount++;
} else {
$result->failureCount++;
}
}
unset( $productsData );
if ( function_exists( 'gc_collect_cycles' ) ) {
gc_collect_cycles();
}
}
$result->processingTime = microtime( true ) - $startTime;
return $result;
}
public function generateForProduct( int $productId, array $contentTypes, array $options = array() ): ProductResult {
$result = $this->generate( array( $productId ), $contentTypes, $options );
return $result->results[ $productId ] ?? new ProductResult( $productId );
}
private function processProduct( int $productId, array $productData, array $contentTypes ): ProductResult {
$trusted = BlueprintIntegration::jobTrustedFacts();
$trusted['legacyPrompts'] = $this->hasLegacyPromptOverride();
$executionPath = BlueprintIntegration::executionPath( BlueprintGenerators::DESCRIPTION, $trusted );
if ( BlueprintIntegration::PATH_BLUEPRINT === $executionPath['path'] ) {
return $this->processProductBlueprint( $productId, $contentTypes );
}
return $this->processProductAdvanced( $productId, $productData, $contentTypes );
}
/**
* True when this request carries a non-empty per-run prompt override
* (`options.prompts.{short,full}.custom_prompt`, or a legacy
* `system_prompt`/`user_prompt` pair merged the same way — see
* {@see CustomPrompts::runOverride()}). A caller that explicitly
* supplies a prompt for this run wants the Advanced path for it,
* regardless of the generator's stored execution mode.
*
* @return bool
*/
private function hasLegacyPromptOverride(): bool {
$prompts = $this->options['prompts'] ?? null;
foreach ( CustomPrompts::types() as $type ) {
if ( null !== CustomPrompts::runOverride( $prompts, $type ) ) {
return true;
}
}
return false;
}
/**
* Content structure generation for one product.
*
* Runs the shared engine via {@see BlueprintIntegration}, maps its
* outputs onto the existing `{description, short_description, tags}`
* shape, then continues through the EXISTING {@see stageReview()} /
* {@see applyContent()} so snapshots, per-field finalize, content
* marking and the concurrency token behave exactly as the Advanced path.
* A held-back result is never applied or staged.
*
* @param int $productId Product ID.
* @param array $contentTypes Requested content types (description|short_description|tags).
* @return ProductResult
*/
private function processProductBlueprint( int $productId, array $contentTypes ): ProductResult {
$result = new ProductResult( $productId );
$generationMode = $this->options['generationMode'] ?? 'client_preview';
$isImmediateMode = 'immediate' === $generationMode;
$isServerReview = 'server_review' === $generationMode;
$overwrite = 'empty_only' === ( $this->options['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace';
$runOptions = array(
'companions' => array(
'shortDescription' => in_array( 'short_description', $contentTypes, true ),
'tags' => in_array( 'tags', $contentTypes, true ),
),
'wantSections' => in_array( 'description', $contentTypes, true ),
'allowExistingDescription' => ! empty( $this->options['improveExistingDescription'] ),
'preserveContentImages' => ! empty( $this->options['preserveContentImages'] ),
'overwrite' => $overwrite,
);
if ( ! empty( $this->options['provider'] ) ) {
$runOptions['provider'] = (string) $this->options['provider'];
}
if ( ! empty( $this->options['model'] ) ) {
$runOptions['model'] = (string) $this->options['model'];
}
if ( ! empty( $this->options['language'] ) ) {
$runOptions['language'] = (string) $this->options['language'];
}
$blueprintResult = BlueprintIntegration::run(
BlueprintGenerators::DESCRIPTION,
array( 'type' => 'product', 'id' => $productId ),
array(
'blueprintRun' => $this->options['blueprintRun'] ?? 0,
'blueprintId' => $this->options['blueprintId'] ?? 0,
'overwrite' => $overwrite,
),
$runOptions,
'bulk'
);
if ( is_wp_error( $blueprintResult ) ) {
$result->errors[] = $blueprintResult->get_error_message();
return $result;
}
$result->executionPath = 'blueprint';
$result->blueprintInfo = BlueprintIntegration::responseFields( $blueprintResult );
$isGenerationFailure = ProviderErrorMessage::isGenerationFailure( $result->blueprintInfo );
$outputs = is_array( $blueprintResult['outputs'] ?? null ) ? $blueprintResult['outputs'] : array();
$mapped = array();
if ( in_array( 'description', $contentTypes, true ) && ! empty( $outputs['description'] ) ) {
$mapped['description'] = (string) $outputs['description'];
}
if ( in_array( 'short_description', $contentTypes, true ) && ! empty( $outputs['shortDescription'] ) ) {
$mapped['short_description'] = (string) $outputs['shortDescription'];
}
if ( in_array( 'tags', $contentTypes, true ) && ! empty( $outputs['tags'] ) && is_array( $outputs['tags'] ) ) {
$mapped['tags'] = implode( ', ', array_map( 'strval', $outputs['tags'] ) );
}
$result->content = $mapped;
if ( $isGenerationFailure ) {
$reason = ProviderErrorMessage::generationFailureMessage( $result->blueprintInfo )
?? __( 'Description generation failed', 'ai-product-tools' );
foreach ( $contentTypes as $type ) {
$result->errors[ $type ] = $reason;
}
} else {
foreach ( array_diff( $contentTypes, array_keys( $mapped ) ) as $missingType ) {
$reason = self::blueprintTypeErrorMessage( (string) $missingType, $result->blueprintInfo );
if ( null !== $reason ) {
$result->errors[ $missingType ] = $reason;
}
}
}
$destination = BlueprintIntegration::destinationForMode( $generationMode );
if ( BlueprintIntegration::isHeldBack( $blueprintResult, $destination ) ) {
$result->status = 'needs_review';
$result->success = ! $isGenerationFailure && ! empty( $mapped );
return $result;
}
if ( $isServerReview ) {
$refusedTypes = array();
foreach ( $mapped as $type => $text ) {
if ( ! $this->stageReview( $productId, $type, $text, $result ) ) {
$refusedTypes[] = $type;
}
}
foreach ( $refusedTypes as $refusedType ) {
unset( $result->content[ $refusedType ] );
}
$result->success = ! empty( $result->content );
return $result;
}
if ( $isImmediateMode && ! empty( $result->content ) ) {
$applyOptions = $this->options;
$applyOptions['overwrite'] = $overwrite;
$applyOptions['executionPath'] = 'blueprint';
if ( ! array_key_exists( 'keepExistingTags', $applyOptions ) && ! empty( $applyOptions['keepExistingDescription'] ) ) {
$applyOptions['keepExistingTags'] = true;
}
$blueprint = is_array( $result->blueprintInfo['blueprint'] ?? null ) ? $result->blueprintInfo['blueprint'] : null;
$textGroup = array_diff_key( $result->content, array( 'tags' => true ) );
$tagsGroup = array_intersect_key( $result->content, array( 'tags' => true ) );
$textOutcome = $this->applyContentGroup( $result, $productId, $textGroup, $applyOptions, $blueprint );
$tagsOutcome = $this->applyContentGroup( $result, $productId, $tagsGroup, $applyOptions, $blueprint );
$hasApplied = true === $textOutcome || true === $tagsOutcome;
$hasFailed = false === $textOutcome || false === $tagsOutcome;
$result->success = $hasApplied || ! $hasFailed;
return $result;
}
$result->success = ! $isGenerationFailure && ! empty( $result->content );
return $result;
}
/**
* The merchant-facing reason a requested content type produced nothing
* for a Blueprint-path run: the run's own `providerError` when known
* (the common case - one provider failure usually explains every
* missing type in the run), else that type's own unit finding, else the
* finding that blocked the whole run, else null so the caller falls
* back to its pre-existing generic text.
*
* `short_description` and `tags` are each a single companion unit with a
* stable id; `description` is composed of however many section units
* the blueprint defines, so it has no single unit id of its own - any
* non-companion unit's finding is this field's own cause.
*
* Public and static (uses no instance state) so every Blueprint-origin
* caller shares this one lookup instead of each re-deriving its own -
* ContentGenerationService's metabox/Abilities fork included.
*
* @param string $type Content type (description|short_description|tags).
* @param array $blueprintInfo BlueprintIntegration::responseFields() result.
* @return string|null
*/
public static function blueprintTypeErrorMessage( string $type, array $blueprintInfo ): ?string {
$providerError = is_array( $blueprintInfo['providerError'] ?? null ) ? $blueprintInfo['providerError'] : null;
if ( null !== $providerError && '' !== trim( (string) ( $providerError['message'] ?? '' ) ) ) {
return (string) $providerError['message'];
}
$findings = is_array( $blueprintInfo['findings'] ?? null ) ? $blueprintInfo['findings'] : array();
$companionUnitIds = array(
'short_description' => 'companion_short_description',
'tags' => 'companion_tags',
);
$unitId = $companionUnitIds[ $type ] ?? null;
foreach ( $findings as $finding ) {
if ( ! is_array( $finding ) || '' === trim( (string) ( $finding['message'] ?? '' ) ) ) {
continue;
}
$findingUnitId = (string) ( $finding['unitId'] ?? '' );
if ( null !== $unitId ) {
if ( $unitId === $findingUnitId ) {
return (string) $finding['message'];
}
continue;
}
if ( '' !== $findingUnitId && 0 !== strpos( $findingUnitId, 'companion_' ) ) {
return (string) $finding['message'];
}
}
foreach ( $findings as $finding ) {
if ( is_array( $finding ) && 'blocking' === (string) ( $finding['severity'] ?? '' ) && '' !== trim( (string) ( $finding['message'] ?? '' ) ) ) {
return (string) $finding['message'];
}
}
return null;
}
private function processProductAdvanced( int $productId, array $productData, array $contentTypes ): ProductResult {
$result = new ProductResult( $productId );
$factory = new PromptFactory( $productData, $this->options );
$generationMode = $this->options['generationMode'] ?? 'client_preview';
$isImmediateMode = 'immediate' === $generationMode;
$isServerReview = 'server_review' === $generationMode;
$refusedTypes = array();
$provider = (string) ( $this->options['provider'] ?? get_option( 'aipt_api_provider', 'openai' ) );
try {
$client = $this->createAIClient( $productData );
} catch ( \Throwable $e ) {
$this->recordAdvancedFailure( $result, $e, $provider, $contentTypes );
return $result;
}
$unifiedContent = null;
try {
$unifiedContent = $this->generateUnified( $client, $factory, $contentTypes );
} catch ( \Exception $e ) {
$this->recordAdvancedFailure( $result, $e, $provider, $contentTypes );
}
if ( null !== $unifiedContent ) {
foreach ( $contentTypes as $type ) {
if ( isset( $unifiedContent[ $type ] ) ) {
$content = $unifiedContent[ $type ];
$fieldImageMap = $factory->getImageMapForField( (string) $type );
$content = $this->restoreImagePlaceholders( $content, $fieldImageMap, $productId, (string) $type );
$validation = OutputValidator::validate( $content, $type, $this->options );
if ( $validation->isValid ) {
$sanitized = OutputValidator::sanitize( $content, $type, $this->options );
if ( 'tags' === $type ) {
$sanitized = $this->newAdvancedTagsOrFail( $sanitized, $productData, $result );
if ( null === $sanitized ) {
continue;
}
}
$result->content[ $type ] = $sanitized;
if ( $isServerReview && ! $this->stageReview( $productId, $type, $sanitized, $result ) ) {
$refusedTypes[] = (string) $type;
}
} else {
$fixed = $this->tryFixContent( $content, $type );
if ( null !== $fixed ) {
if ( 'tags' === $type ) {
$fixed = $this->newAdvancedTagsOrFail( $fixed, $productData, $result );
if ( null === $fixed ) {
continue;
}
}
$result->content[ $type ] = $fixed;
if ( $isServerReview && ! $this->stageReview( $productId, $type, $fixed, $result ) ) {
$refusedTypes[] = (string) $type;
}
} else {
$result->errors[ $type ] = sprintf(
/* translators: 1: content type, 2: validation errors, 3: response length, 4: validation strategy */
__( 'Validation failed for %1$s: %2$s (response length: %3$d bytes, validator: %4$s)', 'ai-product-tools' ),
$type,
implode( ', ', $validation->errors ),
strlen( (string) $content ),
$type
);
}
}
}
}
}
$missingTypes = array_diff( $contentTypes, array_keys( $result->content ) );
if ( ! empty( $missingTypes ) ) {
$sequentialResult = array( 'results' => array(), 'errors' => array(), 'imageMaps' => array() );
try {
$sequentialResult = $this->generateSequential( $client, $factory, $missingTypes );
} catch ( \Exception $e ) {
$this->recordAdvancedFailure( $result, $e, $provider, $missingTypes );
}
if ( ! empty( $sequentialResult['errors'] ) ) {
foreach ( $sequentialResult['errors'] as $error ) {
$result->errors[ $error['type'] ] = $error['message'];
if ( null === $result->providerError && ! empty( $error['providerError'] ) ) {
$result->providerError = $error['providerError'];
}
}
}
foreach ( $sequentialResult['results'] as $type => $content ) {
if ( ! isset( $result->content[ $type ] ) && ! empty( $content ) ) {
$fieldImageMap = $sequentialResult['imageMaps'][ $type ] ?? array();
$content = $this->restoreImagePlaceholders( $content, $fieldImageMap, $productId, (string) $type );
$sanitized = OutputValidator::sanitize( $content, $type, $this->options );
if ( 'tags' === $type ) {
$sanitized = $this->newAdvancedTagsOrFail( $sanitized, $productData, $result );
if ( null === $sanitized ) {
continue;
}
unset( $result->errors['tags'] );
}
$result->content[ $type ] = $sanitized;
if ( $isServerReview && ! $this->stageReview( $productId, $type, $sanitized, $result ) ) {
$refusedTypes[] = (string) $type;
}
}
}
}
foreach ( $refusedTypes as $refusedType ) {
unset( $result->content[ $refusedType ] );
}
if ( $isImmediateMode && ! empty( $result->content ) ) {
$applyOptions = $this->options;
$applyOptions['executionPath'] = 'advanced';
if ( ! array_key_exists( 'keepExistingTags', $applyOptions ) && ! empty( $applyOptions['keepExistingDescription'] ) ) {
$applyOptions['keepExistingTags'] = true;
}
$textGroup = array_diff_key( $result->content, array( 'tags' => true ) );
$tagsGroup = array_intersect_key( $result->content, array( 'tags' => true ) );
$textOutcome = $this->applyContentGroup( $result, $productId, $textGroup, $applyOptions, null );
$tagsOutcome = $this->applyContentGroup( $result, $productId, $tagsGroup, $applyOptions, null );
$hasApplied = true === $textOutcome || true === $tagsOutcome;
$hasFailed = false === $textOutcome || false === $tagsOutcome;
$result->success = $hasApplied || ! $hasFailed;
return $result;
}
$result->success = ! empty( $result->content );
return $result;
}
/**
* Stage generated content into the Content Review store.
*
* @param int $productId Product ID.
* @param string $type Content type (short_description|description|tags).
* @param string $content Generated content.
* @param ProductResult $result Result object to store the review ID.
* @return bool True when the content was staged for review; false when
* staging was refused (a previous approval is in flight).
*/
private function stageReview( int $productId, string $type, string $content, ProductResult $result ): bool {
if ( ! wc_get_product( $productId ) || ! current_user_can( 'edit_post', $productId ) ) {
$result->errors[] = __( 'This product could not be queued for review.', 'ai-product-tools' );
$result->reviewStageFailed = true;
return false;
}
$blueprint = is_array( $result->blueprintInfo['blueprint'] ?? null ) ? $result->blueprintInfo['blueprint'] : array();
$reviewId = $this->reviewStore->stage(
$productId,
'description',
$type,
0,
$content,
array(
'apply_context' => array(
'keepExistingDescription' => $this->options['keepExistingDescription'] ?? false,
'keepExistingTags' => $this->options['keepExistingTags'] ?? false,
'existingDescriptionPosition' => $this->options['existingDescriptionPosition'] ?? 'after',
'beforeContentText' => $this->options['beforeContentText'] ?? '',
'afterContentText' => $this->options['afterContentText'] ?? '',
'model' => $this->options['model'] ?? '',
'overwrite' => 'empty_only' === ( $this->options['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace',
),
'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'] ),
)
);
if ( null !== $reviewId ) {
$result->review_ids[ $type ] = $reviewId;
return true;
}
$result->errors[] = sprintf(
/* translators: %s: content type (description, short_description, tags) */
__( 'Could not stage %s for review: a previous approval for this product is still in progress. Try again shortly.', 'ai-product-tools' ),
$type
);
$result->reviewStageFailed = true;
return false;
}
/**
* @return array|null The parsed per-type content, never an empty array.
* @throws \Exception When the provider call fails (a ProviderCallException
* when it is a classified provider failure), the
* response is empty, or it could not be parsed into
* any requested field - always a real, plain sentence,
* never a silent null.
*/
private function generateUnified( $client, PromptFactory $factory, array $contentTypes ): ?array {
$prompts = $factory->buildUnified( $contentTypes, $this->options );
$model = (string) ( $this->options['model'] ?? '' );
try {
$response = $client->generate_description(
$prompts['system'],
$prompts['user'],
$model
);
if ( empty( $response ) ) {
throw new \Exception( __( 'The AI returned an empty response for this request.', 'ai-product-tools' ) );
}
$parseResult = ResponseParser::parseUnified( $response, $contentTypes, $this->options );
if ( $parseResult->success && ! empty( $parseResult->content ) ) {
return $parseResult->content;
}
throw new \Exception( __( 'The AI response could not be parsed into the requested fields.', 'ai-product-tools' ) );
} catch ( \Exception $e ) {
$sanitized_message = \AIPT\Core\ErrorHandler::sanitize_error_for_logging( $e->getMessage() );
$this->debugLog( sprintf( 'generateUnified failed: %s - %s (code: %d)', get_class( $e ), $sanitized_message, $e->getCode() ) );
throw $e;
}
}
private function generateSequential( $client, PromptFactory $factory, array $contentTypes ): array {
$results = array();
$errors = array();
$imageMaps = array();
$model = (string) ( $this->options['model'] ?? '' );
$provider = (string) ( $this->options['provider'] ?? get_option( 'aipt_api_provider', 'openai' ) );
foreach ( $contentTypes as $type ) {
$prompts = $factory->buildSingle( $type, $this->options );
$imageMaps[ $type ] = $factory->getImageMapForField( (string) $type );
try {
$response = $client->generate_description(
$prompts['system'],
$prompts['user'],
$model
);
if ( ! empty( $response ) ) {
$parseResult = ResponseParser::parseUnified( $response, array( $type ), $this->options );
if ( $parseResult->success && isset( $parseResult->content[ $type ] ) ) {
$results[ $type ] = $parseResult->content[ $type ];
} else {
$normalized = ResponseParser::normalizeContent( $response, $type, $this->options );
if ( ! empty( $normalized ) ) {
$results[ $type ] = $normalized;
}
}
}
if ( ! isset( $results[ $type ] ) ) {
$errors[] = array(
'type' => $type,
'message' => empty( $response )
? __( 'The AI returned an empty response for this field.', 'ai-product-tools' )
: __( 'The AI response could not be parsed into this field.', 'ai-product-tools' ),
);
}
} catch ( \Exception $e ) {
$sanitized_message = \AIPT\Core\ErrorHandler::sanitize_error_for_logging( $e->getMessage() );
$this->debugLog( sprintf( 'generateSequential failed for type %s: %s - %s (code: %d)', $type, get_class( $e ), $sanitized_message, $e->getCode() ) );
$errors[] = array(
'type' => $type,
'message' => ProviderCallException::displayMessage( $e, $provider ),
'providerError' => ProviderCallException::providerErrorFor( $e, $provider ),
);
}
}
if ( ! empty( $errors ) ) {
$this->debugLog( sprintf( 'generateSequential completed with %d error(s)', count( $errors ) ) );
}
return array(
'results' => $results,
'errors' => $errors,
'imageMaps' => $imageMaps,
);
}
/**
* Restore image placeholders in AI-generated content back to original
tags.
* Logs dropped placeholders when the AI fails to return them verbatim.
*
* @param string $content AI response content (may contain placeholders).
* @param array $imageMap Placeholder-to-tag map from PromptFactory::getImageMap().
* @param int $productId Product ID, for logging context.
* @param string $type Content type (description | short_description | tags), for logging context.
* @return string Content with placeholders restored (and missing images appended as fallback).
*/
private function restoreImagePlaceholders( string $content, array $imageMap, int $productId, string $type ): string {
if ( empty( $imageMap ) ) {
return $content;
}
$result = ImagePreserver::unmask( $content, $imageMap );
if ( ! empty( $result['missing'] ) ) {
$this->debugLog(
sprintf(
'Image preservation: %d of %d placeholders dropped by AI for product %d (type: %s), appended as fallback',
count( $result['missing'] ),
count( $imageMap ),
$productId,
$type
)
);
}
return $result['content'];
}
/**
* Record an Advanced-path failure for every given content type: the
* translated merchant sentence for a classified provider failure
* (ProviderCallException::displayMessage()), else the exception's own
* already-plain sentence - never the raw technical text and never a
* fake "{PROVIDER} API ERROR" wrap. The product's FIRST providerError is
* kept (a later call's failure does not overwrite it) so
* GenerationController can tell the page to stop the batch on a
* run-wide failure.
*
* @param ProductResult $result Result to update.
* @param \Throwable $e The caught failure.
* @param string $provider Run's requested provider id (never the site default when the run named one).
* @param string[] $types Content types this failure applies to.
*/
private function recordAdvancedFailure( ProductResult $result, \Throwable $e, string $provider, array $types ): void {
$message = ProviderCallException::displayMessage( $e, $provider );
foreach ( $types as $type ) {
$result->errors[ $type ] = $message;
}
if ( null === $result->providerError ) {
$result->providerError = ProviderCallException::providerErrorFor( $e, $provider );
}
}
/**
* Drop any Advanced-path tag that case-insensitively matches one of this
* product's existing tags, sharing TagListSanitizer with the Blueprint
* tags companion (GenerationRoundRunner) - a deterministic guarantee
* that holds even when a Keep-and-add run's model ignores its own "no
* duplicates" prompt instruction.
*
* A Replace-mode run (no keepExistingDescription) never tells the model
* about the existing tags to begin with
* (PromptFactory::getExistingContentInstructions()'s own `$keep` gate)
* and its apply step fully replaces them rather than merging, so a tag
* the model derived independently from the product data is not a real
* duplicate merely because it coincides with an old tag that is about to
* be discarded anyway - the existing-tag filter is skipped for it, while
* the model's own output still gets deduplicated against itself.
*
* @param string $tags_string Comma-separated tags, already character-sanitized.
* @param array $product_data This call's own loaded product data (reads 'tags_string').
* @return string Comma-separated tags, in the model's own order, with existing-tag duplicates removed.
*/
/**
* The Advanced tags answer without the product's existing tags, or null
* when nothing new is left: that is recorded as the tags field's own
* failure, never stored as an empty "success".
*
* @param string $tags Sanitized tags answer.
* @param array $product_data Product data.
* @param ProductResult $result Result that records the failure.
* @return string|null
*/
private function newAdvancedTagsOrFail( string $tags, array $product_data, ProductResult $result ): ?string {
$tags = $this->dropExistingAdvancedTags( $tags, $product_data );
if ( '' === trim( $tags ) ) {
$result->errors['tags'] = __( 'Every tag the AI suggested is already on this product.', 'ai-product-tools' );
return null;
}
return $tags;
}
private function dropExistingAdvancedTags( string $tags_string, array $product_data ): string {
$candidates = array_values( array_filter( array_map( 'trim', explode( ',', $tags_string ) ) ) );
if ( empty( $candidates ) ) {
return $tags_string;
}
$existing = ! empty( $this->options['keepExistingDescription'] )
? array_values( array_filter( array_map( 'trim', explode( ',', (string) ( $product_data['tags_string'] ?? '' ) ) ) ) )
: array();
return implode( ', ', TagListSanitizer::sanitize( $candidates, count( $candidates ), $existing ) );
}
private function tryFixContent( string $content, string $type ): ?string {
$sanitized = OutputValidator::sanitize( $content, $type, $this->options );
$validation = OutputValidator::validate( $sanitized, $type, $this->options );
if ( $validation->isValid ) {
return $sanitized;
}
$truncated = OutputValidator::truncateToLimit( $sanitized, $type, $this->options );
$validation = OutputValidator::validate( $truncated, $type, $this->options );
if ( $validation->isValid ) {
return $truncated;
}
if ( empty( $validation->errors ) && ! empty( $validation->warnings ) ) {
return $truncated;
}
return null;
}
/**
* @param array $productData Product data for the client's parameter optimization.
* @return object
* @throws ProviderCallException For an unsupported provider, AI turned off, or no saved key —
* propagated instead of swallowed, so the caller can show the
* real, actionable reason instead of a generic failure string.
*/
private function createAIClient( array $productData ) {
$provider = $this->options['provider'] ?? get_option( 'aipt_api_provider', 'openai' );
return AIClientFactory::create( $provider, array(
'category' => $productData['categories'] ?? '',
'generation_type' => 'unified',
'model' => $this->options['model'] ?? null,
) );
}
private function normalizeOptions( array $options ): array {
$defaults = array(
'provider' => get_option( 'aipt_api_provider', 'openai' ),
'model' => $this->defaultModel( $options ),
'language' => get_option( 'aipt_language', 'English' ),
'writing_style' => get_option( 'aipt_writing_style', 'Professional' ),
'content_length_preset' => get_option( 'aipt_content_length_preset', 'long' ),
'short_length_preset' => get_option( 'aipt_short_length_preset', 'standard' ),
'max_tags_count' => (int) get_option( 'aipt_max_tags_count', 3 ),
'improveExistingDescription' => false,
'keepExistingDescription' => false,
'additionalTagsCount' => 2,
'generationMode' => 'client_preview',
'outputFormat' => 'html',
'blueprintRun' => 0,
'blueprintId' => 0,
'overwrite' => 'replace',
'preserveContentImages' => $this->resolvePreserveContentImagesDefault( $options ),
);
return array_merge( $defaults, $options );
}
/**
* The saved model when it belongs to the provider this run uses, else
* that provider's default model. The saved model belongs to the saved
* provider, so a request that names another provider without a model
* must not send it the saved one.
*
* @param array $options Request options.
* @return string
*/
private function defaultModel( array $options ): string {
$provider = strtolower( trim( (string) ( $options['provider'] ?? '' ) ) );
if ( '' === $provider ) {
$provider = (string) get_option( 'aipt_api_provider', 'openai' );
}
return ModelCatalog::normalize_model( $provider, (string) get_option( 'aipt_model', '' ) );
}
/**
* Default for `preserveContentImages` ("Keep images in descriptions")
* when the request does not send that exact camelCase key.
*
* Automation's OptionsTranslator, and any other caller that mirrors
* the Advanced path's own option name, sends the snake_case
* `preserve_content_images` instead; without this, the Blueprint path
* (ContentGenerator.php's own `preserveContentImages` read) never saw
* that value and silently behaved as if the toggle were off.
*
* @param array $options Raw options passed to generate()/applyContent().
* @return bool
*/
private function resolvePreserveContentImagesDefault( array $options ): bool {
if ( array_key_exists( 'preserve_content_images', $options ) ) {
return (bool) $options['preserve_content_images'];
}
return (bool) get_option( 'aipt_preserve_content_images', true );
}
private function normalizeContentTypes( array $types ): array {
$mapping = array(
'generateShortDescription' => 'short_description',
'generateDescription' => 'description',
'generateTags' => 'tags',
'short' => 'short_description',
'full' => 'description',
);
$normalized = array();
foreach ( $types as $key => $value ) {
if ( is_string( $key ) && $value === true ) {
$type = $mapping[ $key ] ?? $key;
if ( in_array( $type, array( 'short_description', 'description', 'tags' ), true ) ) {
$normalized[] = $type;
}
} elseif ( is_string( $value ) ) {
$type = $mapping[ $value ] ?? $value;
if ( in_array( $type, array( 'short_description', 'description', 'tags' ), true ) ) {
$normalized[] = $type;
}
}
}
return array_unique( $normalized );
}
/**
* @param int $productId Product id.
* @param array $content Content map (description/short_description/tags).
* @param array $options Apply options.
* @param array|null $blueprint Blueprint attribution `{id,name,revision,builtin}` for the
* Content Bank snapshot this apply stages, or null for a
* custom-prompts write, which records nothing (every caller
* but the Blueprint apply adapter omits this).
* @return bool
*/
public function applyContent( int $productId, array $content, array $options = array(), ?array $blueprint = null ): bool {
$this->debugLog( "applyContent: START - productId={$productId}, content_keys=" . implode( ',', array_keys( $content ) ) );
$this->skippedFields = array();
try {
$product = wc_get_product( $productId );
if ( ! $product ) {
$this->debugLog( "applyContent: Product not found for ID {$productId}" );
return false;
}
$this->debugLog( "applyContent: Product found, type=" . get_class( $product ) );
$keepExisting = ! empty( $options['keepExistingDescription'] );
$position = $options['existingDescriptionPosition'] ?? 'after';
$beforeText = $options['beforeContentText'] ?? '';
$afterText = $options['afterContentText'] ?? '';
$overwriteEmptyOnly = 'empty_only' === ( $options['overwrite'] ?? 'replace' );
$appliedAny = false;
$descriptionApplied = false;
$tagsApplied = false;
$tagsFailed = false;
$snapshot_fields = array();
foreach ( $content as $ct => $txt ) {
if ( empty( $txt ) ) {
continue;
}
if ( 'short_description' === $ct ) {
$snapshot_fields['short_desc'] = true;
} elseif ( 'description' === $ct ) {
$snapshot_fields['description'] = true;
} elseif ( 'tags' === $ct ) {
$snapshot_fields['tags'] = array( true );
}
}
if ( ! empty( $snapshot_fields ) ) {
if ( null !== $blueprint ) {
$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'] );
}
\AIPT\Api\Rollback\ContentApplyDispatcher::before( $productId, $snapshot_fields, 'description' );
}
foreach ( $content as $type => $text ) {
$this->debugLog( "applyContent: Processing type={$type}, content_length=" . strlen( $text ) );
if ( empty( $text ) ) {
$this->debugLog( "applyContent: Skipping empty content for type={$type}" );
continue;
}
if ( $overwriteEmptyOnly && ! $keepExisting && $this->isNotEmptyForOverwrite( $product, $productId, $type, $options ) ) {
$this->skippedFields[] = array( 'field' => $type, 'reason' => 'not_empty' );
$this->debugLog( "applyContent: overwrite=empty_only, skipping non-empty field={$type}" );
continue;
}
if ( $type === 'tags' ) {
$tagsOutcome = $this->applyTags( $productId, $text, $options );
if ( true === $tagsOutcome ) {
$appliedAny = true;
$tagsApplied = true;
} elseif ( false === $tagsOutcome ) {
$tagsFailed = true;
}
continue;
}
$finalContent = $text;
if ( ! empty( $beforeText ) || ! empty( $afterText ) ) {
$finalContent = $beforeText . $finalContent . $afterText;
}
$finalContent = \AIPT\Utils\DescriptionSanitizer::clean( $finalContent );
if ( $keepExisting ) {
$existing = $type === 'short_description'
? $product->get_short_description()
: $product->get_description();
if ( ! empty( $existing ) ) {
$finalContent = $position === 'before'
? $finalContent . "\n\n" . $existing
: $existing . "\n\n" . $finalContent;
}
}
if ( $type === 'short_description' ) {
$this->debugLog( "applyContent: Setting short_description for product {$productId}, content_length=" . strlen( $finalContent ) );
$product->set_short_description( $finalContent );
$appliedAny = true;
$descriptionApplied = true;
} elseif ( $type === 'description' ) {
$this->debugLog( "applyContent: Setting description for product {$productId}, content_length=" . strlen( $finalContent ) );
$product->set_description( $finalContent );
$appliedAny = true;
$descriptionApplied = true;
} else {
$this->debugLog( "applyContent: Unknown type={$type}, skipping" );
}
}
if ( $appliedAny ) {
$this->debugLog( "applyContent: About to save product {$productId}" );
try {
$save_outcome = $descriptionApplied
? \AIPT\Api\Helpers\ProductSaveVerifier::save( $product )
: array( 'result' => true, 'landed' => true );
} catch ( \Throwable $save_error ) {
$this->debugLog( "applyContent: Product {$productId} save threw: " . $save_error->getMessage() );
$save_outcome = array(
'result' => new \WP_Error( 'aipt_product_save_failed', $save_error->getMessage() ),
'landed' => false,
);
}
$save_result = $save_outcome['result'];
$descriptionWriteSucceeded = $save_outcome['landed'];
$write_succeeded = $descriptionWriteSucceeded && ! $tagsFailed;
$this->debugLog( "applyContent: Product saved, result=" . wp_json_encode( $save_result ) );
\AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField(
$productId,
array(
'tags' => $tagsApplied,
'description' => $descriptionApplied && $descriptionWriteSucceeded,
'short_description' => $descriptionApplied && $descriptionWriteSucceeded,
)
);
ProductDataProvider::clearCache( $productId );
$this->debugLog( "applyContent: Cache cleared for product {$productId}" );
if ( $descriptionApplied && $descriptionWriteSucceeded ) {
ContentMarkService::mark(
$productId,
'description',
array(
'gen' => MetaKeys::GEN_BULK_ADVANCED,
'model' => (string) ( $this->options['model'] ?? '' ),
)
);
}
return $write_succeeded;
}
\AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $productId, array() );
$this->debugLog( "applyContent: Nothing was applied for product {$productId}" );
return false;
} catch ( \Throwable $e ) {
\AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStagedByField( $productId, array() );
$sanitized_message = \AIPT\Core\ErrorHandler::sanitize_error_for_logging( $e->getMessage() );
$sanitized_trace = \AIPT\Core\ErrorHandler::sanitize_error_for_logging( $e->getTraceAsString() );
$this->debugLog( "applyContent: EXCEPTION - " . $sanitized_message );
$this->debugLog( "applyContent: Stack trace - " . $sanitized_trace );
return false;
}
}
/**
* Fields the most recent applyContent() call skipped because
* `overwrite === 'empty_only'` found a live, non-empty value.
*
* @return array
*/
public function getSkippedFields(): array {
return $this->skippedFields;
}
/**
* Apply one immediate-mode group of a generated result's content — the
* text fields (description/short_description) or tags — and reconcile
* $result accordingly, so a genuine failure in one group is never
* reported as if a sibling group's own landed (or validly skipped)
* content had failed too.
*
* Dispatched as an independent applyContent() call per group (mirrors
* {@see \AIPT\Api\ContentStructure\Apply\DescriptionApplyAdapter::apply()}'s
* own split over this same applyContent(): text fields land via
* WC_Product::save() and tags via wp_set_object_terms(), two unrelated
* writes folded into one boolean when sent together).
*
* A field skipped for `overwrite: empty_only` (the live product already
* had a value) is moved from $result->content to $result->skipped —
* never a failure. A field this call actually attempted and failed to
* write is removed from $result->content and recorded in
* $result->errors[type] instead, so the merchant sees that field's own
* true outcome rather than stale generated text that was never written.
*
* @param ProductResult $result Carries ->content in; mutated in place.
* @param int $productId Product id.
* @param array $group This call's own content map (a subset of $result->content).
* @param array $applyOptions Apply options.
* @param array|null $blueprint Blueprint attribution, or null for the Advanced path.
* @return bool|null True when this group wrote something, false when it genuinely failed to, null for an empty or fully-skipped group (a no-op, never a failure).
*/
private function applyContentGroup( ProductResult $result, int $productId, array $group, array $applyOptions, ?array $blueprint ): ?bool {
if ( empty( $group ) ) {
return null;
}
$applied = $this->applyContent( $productId, $group, $applyOptions, $blueprint );
$skippedFields = array();
foreach ( $this->getSkippedFields() as $skippedField ) {
$field = (string) ( $skippedField['field'] ?? '' );
$skippedFields[ $field ] = true;
unset( $result->content[ $field ] );
$result->skipped[] = $field;
}
$remaining = array_diff_key( $group, $skippedFields );
if ( empty( $remaining ) ) {
return null;
}
if ( $applied ) {
return true;
}
foreach ( array_keys( $remaining ) as $failedType ) {
unset( $result->content[ $failedType ] );
$result->errors[ $failedType ] = __( 'Generated content could not be applied to the product.', 'ai-product-tools' );
}
return false;
}
/**
* Whether `$type`'s LIVE value is already non-empty, for the
* `overwrite === 'empty_only'` re-check. Tags are checked against the
* product's current `product_tag` terms (unless the run also asks to
* keep/append existing tags, in which case emptiness does not apply).
*
* @param \WC_Product $product Loaded product.
* @param int $productId Product ID.
* @param string $type Content type (description|short_description|tags).
* @param array $options applyContent() options.
* @return bool
*/
private function isNotEmptyForOverwrite( $product, int $productId, string $type, array $options ): bool {
if ( 'tags' === $type ) {
if ( ! empty( $options['keepExistingTags'] ) ) {
return false;
}
$existingTags = function_exists( 'wp_get_post_terms' ) ? wp_get_post_terms( $productId, 'product_tag', array( 'fields' => 'ids' ) ) : array();
return is_array( $existingTags ) && ! empty( $existingTags );
}
$existing = 'short_description' === $type ? $product->get_short_description() : $product->get_description();
return '' !== trim( wp_strip_all_tags( (string) $existing ) );
}
/**
* @return bool|null True when the tags write landed, false when
* wp_set_object_terms() failed, or null when there
* was nothing parseable to write (a no-op, not a
* failure).
*/
private function applyTags( int $productId, string $tagsString, array $options ): ?bool {
$executionPath = (string) ( $options['executionPath'] ?? 'advanced' );
$maxTags = 'blueprint' === $executionPath ? PHP_INT_MAX : (int) ( $this->options['max_tags_count'] ?? 5 );
$tags = ResponseParser::parseTags( $tagsString, $maxTags );
if ( empty( $tags ) ) {
return null;
}
$append = ! empty( $options['keepExistingTags'] );
$term_result = wp_set_object_terms( $productId, $tags, 'product_tag', $append );
clean_object_term_cache( $productId, 'product' );
if ( is_wp_error( $term_result ) ) {
return false;
}
if ( ! empty( $term_result ) ) {
ContentMarkService::mark( $productId, 'tags', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) );
\AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $productId );
}
return true;
}
}
class GenerationResult {
public array $results = array();
public int $successCount = 0;
public int $failureCount = 0;
public array $errors = array();
public float $processingTime = 0.0;
}
class ProductResult {
public int $productId;
public array $content = array();
public array $errors = array();
public bool $success = false;
/**
* Content types the apply step left untouched because the live product
* already had a value and `overwrite` was `empty_only`. They are removed
* from $content, so format_bulk_results() reports them as kept rather
* than as not generated.
*
* @var string[]
*/
public array $skipped = array();
/**
* Review row IDs staged during server_review mode.
* Keyed by content type (short_description|description|tags).
*
* @var array
*/
public array $review_ids = array();
/**
* True when stageReview() refused to stage at least one generated field -
* a missing/unauthorized product, or a row already in_progress/applied for
* this product. The content itself WAS generated; only filing it for
* review was refused, which is a distinct, recoverable condition from a
* true generation failure (a bad response from the provider, a validation
* failure, ...). $errors already carries the specific reason.
*/
public bool $reviewStageFailed = false;
/**
* Content structure per-item response fields.
* 'advanced' (the default) for the legacy path; set to 'blueprint' by
* processProductBlueprint(), along with $blueprintInfo.
*/
public string $executionPath = 'advanced';
/**
* {executionPath, blueprint, findings, eligibility} from
* BlueprintIntegration::responseFields(), merged into the formatted
* bulk row by GenerationController::format_bulk_results(). Empty for
* the Advanced path.
*
* @var array
*/
public array $blueprintInfo = array();
/**
* Status override for the formatted bulk row
* (`status: 'needs_review'` for a held-back Blueprint result). Null
* keeps format_bulk_results()'s existing applied/pending logic.
*/
public ?string $status = null;
/**
* The Advanced path's own provider failure, when processProductAdvanced()
* caught one: {@see \AIPT\Api\ProviderCallException::toResponseArray()}.
* Merged into every formatted row for this product by
* GenerationController::format_bulk_results() so the page can stop a
* batch on `runWide`, the same way the Blueprint path's own
* `blueprintInfo['providerError']` already does. Null for a non-provider
* failure or a successful product.
*
* @var array|null
*/
public ?array $providerError = null;
public function __construct( int $productId ) {
$this->productId = $productId;
}
}