ai_client_factory = $ai_client_factory;
$this->style_descriptions = $style_descriptions;
$this->title_generator_service = $title_generator_service ?? new TitleGeneratorService();
$this->governing_blueprint_resolver = $governing_blueprint_resolver ?? new GoverningBlueprintResolver();
}
/**
* Generate product description
*
* @param array $params Generation parameters (product_id, is_short, improveExistingDescription, keepExistingDescription)
* @return array|\WP_Error Generated content or error
*/
public function generateDescription( array $params ) {
try {
$product_id = $params['product_id'];
$is_short = isset( $params['is_short'] ) ? $params['is_short'] : false;
$execution_path = BlueprintIntegration::executionPath( BlueprintGenerators::DESCRIPTION, array() );
if ( BlueprintIntegration::PATH_BLUEPRINT === $execution_path['path'] ) {
return $this->generateDescriptionBlueprint( (int) $product_id, (bool) $is_short, $params );
}
$api_provider = get_option( 'aipt_api_provider', 'openai' );
$model = $this->ai_client_factory->getDefaultModel( $api_provider );
$model = get_option( 'aipt_model', $model );
$model = $this->ai_client_factory->normalizeModel( $api_provider, $model );
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$permission_error = $this->checkProductPermission( (int) $product_id );
if ( null !== $permission_error ) {
return $permission_error;
}
$language = get_option( 'aipt_language', Activator::get_default_value( 'language' ) );
$writing_style = get_option( 'aipt_writing_style', Activator::get_default_value( 'writing_style' ) );
$max_length = (int) ( $is_short ?
get_option( 'aipt_max_short_length', Activator::get_default_value( 'max_short_length' ) ) :
get_option( 'aipt_max_length', Activator::get_default_value( 'max_length' ) ) );
$prompt_type = $is_short ? CustomPrompts::SHORT : CustomPrompts::FULL;
$custom_prompt = CustomPrompts::stored( $prompt_type );
if ( '' === trim( $custom_prompt ) ) {
$custom_prompt = CustomPrompts::defaultFor( $prompt_type );
}
$style_description = isset( $this->style_descriptions[ $writing_style ] )
? $this->style_descriptions[ $writing_style ]
: $this->style_descriptions['Professional'];
$product_info = $this->getProductInfo( $product );
$attributes_string = ! empty( $product_info['attributes'] )
? implode( ', ', array_map(
function ( $k, $v ) {
return "$k: $v";
},
array_keys( $product_info['attributes'] ),
$product_info['attributes']
) )
: '';
$categories_string = implode( ', ', $product_info['categories'] );
$tags_string = implode( ', ', $product_info['tags'] );
$safe_variables = VariableConverter::convertVariables(
array(
'{max_length}' => intval( $max_length ),
'{SKU}' => $product_info['sku'],
'{ATTRIBUTES}' => $attributes_string,
'{CATEGORIES}' => $categories_string,
'{TAGS}' => $tags_string,
'{PRICE}' => $product_info['price'],
'{REGULAR_PRICE}' => $product_info['regular_price'],
'{SALE_PRICE}' => $product_info['sale_price'],
'{SHORT_DESCRIPTION}' => $product_info['short_description'],
'{LONG_DESCRIPTION}' => $product_info['description'],
'{language}' => sanitize_text_field( $language ),
'{style}' => sanitize_text_field( $style_description ),
'{title}' => $product_info['name'],
)
);
$custom_prompt = str_replace( array_keys( $safe_variables ), array_values( $safe_variables ), $custom_prompt );
$provider_data = ProductDataProvider::get( (int) $product_id, false );
$custom_variables = is_array( $provider_data['custom_variables'] ?? null ) ? $provider_data['custom_variables'] : array();
$custom_prompt = PromptFormatter::replaceCustomVariables( $custom_prompt, $custom_variables );
$client = $this->ai_client_factory->create();
$custom_prompt = $this->cleanPromptContent( $custom_prompt, $product_info );
$brand_context_block = \AIPT\Api\BulkGenerator\Common\BrandContext::block();
$system_prompt = '' !== $brand_context_block
? $brand_context_block
: 'You are a professional product copywriter for an online store.';
$system_prompt .= " Ensure the output is formatted in HTML (using
,
, - , , etc.). Do not use Markdown.";
$system_prompt .= " NEVER include literal prices, price ranges, or currency amounts in the description. Prices change frequently and make descriptions outdated.";
if ( isset( $params['improveExistingDescription'] ) && $params['improveExistingDescription'] ) {
$existing_description = $is_short ? $product->get_short_description() : $product->get_description();
if ( ! empty( $existing_description ) ) {
$existing_description = HtmlToText::convert( $existing_description );
$custom_prompt .= "\n\nYOU SHOULD CONSIDER THE EXISTING PRODUCT DESCRIPTION: " . $existing_description;
}
}
$description = $client->generate_description( $system_prompt, $custom_prompt, $model, $max_length );
$formatted_description = PromptFormatter::formatAiResponseForWordPress( $description );
if ( isset( $params['keepExistingDescription'] ) && $params['keepExistingDescription'] ) {
$existing_description = $is_short ? $product->get_short_description() : $product->get_description();
if ( ! empty( $existing_description ) ) {
$formatted_description = $existing_description . "\n\n" . $formatted_description;
}
}
$free_defaults = BlueprintIntegration::advancedResponseFields();
return array( 'description' => $formatted_description, 'blueprint' => $free_defaults['blueprint'], 'plan_limits' => $free_defaults['appliedFreeDefaults'] );
} catch ( \Throwable $e ) {
if ( $e instanceof ProviderCallException ) {
return self::providerErrorResponse( $e );
}
$message = ErrorHandler::sanitize_error_for_display( $e->getMessage() );
$status = ErrorHandler::extract_http_status_from_message( $message, 500 );
ErrorHandler::log_error( sprintf( '[generateDescription] %s', $e->getMessage() ), 'error' );
return new \WP_Error( 'generation_failed', $message, array( 'status' => $status ) );
}
}
/**
* Generate product title
*
* @param array $params Generation parameters (product_id, max_length, keywords, tone, mode, titleSources)
* @return array|\WP_Error Generated title or error
*/
public function generateTitle( array $params ) {
try {
$product_id = $params['product_id'];
$execution_path = BlueprintIntegration::executionPath( BlueprintGenerators::TITLE, array() );
if ( BlueprintIntegration::PATH_BLUEPRINT === $execution_path['path'] ) {
return $this->generateTitleBlueprint( (int) $product_id, $params );
}
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$permission_error = $this->checkProductPermission( (int) $product_id );
if ( null !== $permission_error ) {
return $permission_error;
}
$title_service = $this->title_generator_service;
$provider = get_option( 'aipt_api_provider', 'openai' );
$selected_model = get_option( 'aipt_model', $this->ai_client_factory->getDefaultModel( $provider ) );
$selected_model = $this->ai_client_factory->normalizeModel( $provider, $selected_model );
$options = array(
'provider' => $provider,
'model' => $selected_model,
'variantCount' => 1,
'maxLength' => $params['max_length'] ?? 60,
'keywords' => $params['keywords'] ?? '',
'tone' => $params['tone'] ?? 'SEO-Focused',
'mode' => $params['mode'] ?? 'rewrite',
'titleSources' => $params['titleSources'] ?? array( 'product_description' ),
);
$results = $title_service->bulk_generate( array( $product_id ), $options );
if ( empty( $results ) || ! isset( $results[0] ) ) {
throw new \Exception( 'Title generation failed to produce a result.' );
}
$result = $results[0];
if ( is_array( $result['providerError'] ?? null ) && '' !== (string) ( $result['providerError']['reason'] ?? '' ) ) {
return self::providerErrorFromArray( $result['providerError'], (string) ( $result['api_error'] ?? '' ) );
}
$error_message = $result['api_error'] ?? $result['error'] ?? null;
if ( ! empty( $error_message ) ) {
throw new \Exception( (string) $error_message );
}
if ( empty( $result['text'] ) ) {
throw new \Exception( 'No valid title was generated.' );
}
$free_defaults = BlueprintIntegration::advancedResponseFields();
return array( 'title' => $result['text'], 'blueprint' => $free_defaults['blueprint'], 'plan_limits' => $free_defaults['appliedFreeDefaults'] );
} catch ( \Throwable $e ) {
if ( $e instanceof ProviderCallException ) {
return self::providerErrorResponse( $e );
}
$message = $e->getMessage();
$status = ErrorHandler::extract_http_status_from_message( $message, 500 );
ErrorHandler::log_error( sprintf( '[generateTitle] %s', $e->getMessage() ), 'error' );
return new \WP_Error( 'generation_failed', $message, array( 'status' => $status ) );
}
}
/**
* Generate product tags
*
* @param array $params Generation parameters (product_id, max_tags, keep_existing)
* @return array|\WP_Error Generated tags or error
*/
public function generateTags( array $params ) {
try {
$product_id = $params['product_id'];
$max_tags = $params['max_tags'] ?? 5;
$keep_existing = $params['keep_existing'] ?? false;
$execution_path = BlueprintIntegration::executionPath( BlueprintGenerators::DESCRIPTION, array() );
if ( BlueprintIntegration::PATH_BLUEPRINT === $execution_path['path'] ) {
return $this->generateTagsBlueprint( (int) $product_id, (int) $max_tags, $params );
}
$api_provider = get_option( 'aipt_api_provider', 'openai' );
$model = $this->ai_client_factory->getDefaultModel( $api_provider );
$model = get_option( 'aipt_model', $model );
$model = $this->ai_client_factory->normalizeModel( $api_provider, $model );
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$permission_error = $this->checkProductPermission( (int) $product_id );
if ( null !== $permission_error ) {
return $permission_error;
}
$language = get_option( 'aipt_language', Activator::get_default_value( 'language' ) );
$product_info = $this->getProductInfo( $product );
$system_prompt = 'You are a professional e-commerce SEO expert specialized in creating relevant product tags that improve searchability and categorization. Your task is to generate accurate, specific, and search-friendly tags for products.';
$user_prompt = "Generate {max_tags} relevant product tags in {language} language for the following product. ";
$user_prompt .= 'Tags should be specific, search-friendly, and help customers find this product. ';
$user_prompt .= 'Include material, style, use case, and feature-based tags where applicable. ';
$user_prompt .= "Return only the tags separated by commas, without any additional text or explanations.\n\n";
if ( $keep_existing && ! empty( $product_info['tags'] ) ) {
$user_prompt .= "Existing tags: {TAGS}\n";
$user_prompt .= "Add new complementary tags that don't duplicate existing ones.\n\n";
}
$user_prompt .= "Product name: {title}\n";
$user_prompt .= "Categories: {CATEGORIES}\n";
$user_prompt .= "Attributes: {ATTRIBUTES}\n";
$user_prompt .= "Short description: {short_description}\n";
$variables = array( '{max_tags}', '{language}', '{title}', '{CATEGORIES}', '{ATTRIBUTES}', '{TAGS}', '{short_description}' );
$values = array(
$max_tags,
$language,
$product_info['name'],
implode( ', ', $product_info['categories'] ),
! empty( $product_info['attributes'] ) ? implode(
', ',
array_map(
function ( $k, $v ) {
return "$k: $v";
},
array_keys( $product_info['attributes'] ),
$product_info['attributes']
)
) : '',
implode( ', ', $product_info['tags'] ),
$product_info['short_description'],
);
$system_prompt = str_replace( $variables, $values, $system_prompt );
$user_prompt = str_replace( $variables, $values, $user_prompt );
$client = $this->ai_client_factory->create();
$tags_text = $client->generate_description( $system_prompt, $user_prompt, $model, 200 );
$tags = array_map( 'trim', explode( ',', $tags_text ) );
$tags = array_filter(
$tags,
function ( $tag ) {
return ! empty( $tag ) && ! preg_match( '/[<>{}()\\[\\]\\/\\\\]/', $tag ) && strlen( $tag ) <= 100;
}
);
$tags = TagListSanitizer::sanitize( array_values( $tags ), count( $tags ), $keep_existing ? ( $product_info['tags'] ?? array() ) : array() );
$tags = array_slice( $tags, 0, $max_tags );
if ( empty( $tags ) ) {
throw new \Exception( 'No valid tags were generated' );
}
$free_defaults = BlueprintIntegration::advancedResponseFields();
return array(
'tags' => $tags,
'tags_text' => implode( ', ', $tags ),
'blueprint' => $free_defaults['blueprint'],
'plan_limits' => $free_defaults['appliedFreeDefaults'],
);
} catch ( \Throwable $e ) {
if ( $e instanceof ProviderCallException ) {
return self::providerErrorResponse( $e );
}
$message = $e->getMessage();
$status = ErrorHandler::extract_http_status_from_message( $message, 500 );
ErrorHandler::log_error( sprintf( '[generateTags] %s', $e->getMessage() ), 'error' );
return new \WP_Error( 'generation_failed', $message, array( 'status' => $status ) );
}
}
/**
* Content structure description/short-description generation for the
* metabox/Abilities. Mirrors generateDescription()'s
* keepExistingDescription response shaping so callers see the same
* `{description: string}` contract regardless of execution path.
*
* @param int $product_id Product ID.
* @param bool $is_short Short description instead of full.
* @param array $params Generation parameters (improveExistingDescription, keepExistingDescription, blueprintRun, blueprintId).
* @return array|\WP_Error
*/
private function generateDescriptionBlueprint( int $product_id, bool $is_short, array $params ) {
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$result = BlueprintIntegration::run(
BlueprintGenerators::DESCRIPTION,
array( 'type' => 'product', 'id' => $product_id ),
array(
'blueprintRun' => $params['blueprintRun'] ?? 0,
'blueprintId' => $params['blueprintId'] ?? 0,
),
array(
'companions' => array( 'shortDescription' => $is_short, 'tags' => false ),
'wantSections' => ! $is_short,
'allowExistingDescription' => ! empty( $params['improveExistingDescription'] ),
),
(string) ( $params['origin'] ?? 'metabox' )
);
if ( is_wp_error( $result ) ) {
return $result;
}
$outputs = is_array( $result['outputs'] ?? null ) ? $result['outputs'] : array();
$description = $is_short ? (string) ( $outputs['shortDescription'] ?? '' ) : (string) ( $outputs['description'] ?? '' );
$fields = BlueprintIntegration::responseFields( $result );
if ( '' === trim( $description ) ) {
if ( is_array( $result['providerError'] ?? null ) && '' !== (string) ( $result['providerError']['reason'] ?? '' ) ) {
return self::providerErrorFromArray( $result['providerError'], '' );
}
$reason = ContentGenerator::blueprintTypeErrorMessage( $is_short ? 'short_description' : 'description', $fields );
if ( null !== $reason ) {
return new \WP_Error( 'generation_failed', $reason, array( 'status' => 500 ) );
}
return new \WP_Error( 'generation_failed', __( 'No content was generated.', 'ai-product-tools' ), array( 'status' => 500 ) );
}
$blocked = self::noAiContentError( $result, $fields );
if ( null !== $blocked ) {
return $blocked;
}
$formatted_description = PromptFormatter::formatAiResponseForWordPress( $description );
if ( ! empty( $params['keepExistingDescription'] ) ) {
$existing_description = $is_short ? $product->get_short_description() : $product->get_description();
if ( ! empty( $existing_description ) ) {
$formatted_description = $existing_description . "\n\n" . $formatted_description;
}
}
return array( 'description' => $formatted_description, 'blueprint' => $fields['blueprint'], 'plan_limits' => $fields['appliedFreeDefaults'], 'resultKey' => $fields['resultKey'] );
}
/**
* Content structure title generation for the metabox/Abilities.
* Legacy prompt-shaping params (tone, keywords,
* mode, titleSources, max_length) do not apply in Blueprint mode — the
* Blueprint's own TitleStructure owns parts/separator/length instead.
*
* @param int $product_id Product ID.
* @param array $params Generation parameters (blueprintRun, blueprintId).
* @return array|\WP_Error
*/
private function generateTitleBlueprint( int $product_id, array $params ) {
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$result = BlueprintIntegration::run(
BlueprintGenerators::TITLE,
array( 'type' => 'product', 'id' => $product_id ),
array(
'blueprintRun' => $params['blueprintRun'] ?? 0,
'blueprintId' => $params['blueprintId'] ?? 0,
),
array(),
(string) ( $params['origin'] ?? 'metabox' )
);
if ( is_wp_error( $result ) ) {
return $result;
}
$title = trim( (string) ( $result['outputs']['title'] ?? '' ) );
if ( '' === $title ) {
if ( is_array( $result['providerError'] ?? null ) && '' !== (string) ( $result['providerError']['reason'] ?? '' ) ) {
return self::providerErrorFromArray( $result['providerError'], '' );
}
return new \WP_Error( 'generation_failed', __( 'No valid title was generated.', 'ai-product-tools' ), array( 'status' => 500 ) );
}
$fields = BlueprintIntegration::responseFields( $result );
$blocked = self::noAiContentError( $result, $fields );
if ( null !== $blocked ) {
return $blocked;
}
return array( 'title' => $title, 'blueprint' => $fields['blueprint'], 'plan_limits' => $fields['appliedFreeDefaults'], 'resultKey' => $fields['resultKey'] );
}
/**
* Content structure tags generation for the metabox/Abilities, via the
* description generator's `tags` companion. The companion schema has no
* "avoid these existing tags" concept, so `keep_existing` only affects
* the apply step the caller performs afterwards, not what the model is
* asked to avoid.
*
* @param int $product_id Product ID.
* @param int $max_tags Maximum tags to return.
* @param array $params Generation parameters (blueprintRun, blueprintId).
* @return array|\WP_Error
*/
private function generateTagsBlueprint( int $product_id, int $max_tags, array $params ) {
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$subject_error = $this->invalidGenerationSubjectError( $product );
if ( null !== $subject_error ) {
return $subject_error;
}
$result = BlueprintIntegration::run(
BlueprintGenerators::DESCRIPTION,
array( 'type' => 'product', 'id' => $product_id ),
array(
'blueprintRun' => $params['blueprintRun'] ?? 0,
'blueprintId' => $params['blueprintId'] ?? 0,
),
array(
'companions' => array( 'shortDescription' => false, 'tags' => true ),
'wantSections' => false,
),
(string) ( $params['origin'] ?? 'metabox' )
);
if ( is_wp_error( $result ) ) {
return $result;
}
$tags = is_array( $result['outputs']['tags'] ?? null ) ? array_values( array_filter( array_map( 'strval', $result['outputs']['tags'] ) ) ) : array();
$tags = array_slice( $tags, 0, max( 1, $max_tags ) );
if ( empty( $tags ) ) {
if ( is_array( $result['providerError'] ?? null ) && '' !== (string) ( $result['providerError']['reason'] ?? '' ) ) {
return self::providerErrorFromArray( $result['providerError'], '' );
}
return new \WP_Error( 'generation_failed', __( 'No valid tags were generated.', 'ai-product-tools' ), array( 'status' => 500 ) );
}
$fields = BlueprintIntegration::responseFields( $result );
$blocked = self::noAiContentError( $result, $fields );
if ( null !== $blocked ) {
return $blocked;
}
return array(
'tags' => $tags,
'tags_text' => implode( ', ', $tags ),
'blueprint' => $fields['blueprint'],
'plan_limits' => $fields['appliedFreeDefaults'],
'resultKey' => $fields['resultKey'],
);
}
/**
* Apply description to product
*
* @param int $product_id Product ID.
* @param string $description Description content.
* @param string $type Description type (full|short).
* @param array $context Additive content structure context: {@type bool $blueprint When true, route the write through
* the EXISTING Desc\ContentGenerator::applyContent() apply path (DescriptionApplyAdapter) so snapshot
* staging, per-field finalize and ContentMarkService::mark() happen exactly as the bulk path's — fixing
* this route's missing content marking for Blueprint output. Omitted/false keeps
* today's direct-write behavior byte-for-byte, so every existing caller of this method is unaffected.
* @type string $overwrite 'replace'|'empty_only', used only when $blueprint is true.}
* @return array|\WP_Error Success response or error
*/
public function applyContent( int $product_id, string $description, string $type = 'full', array $context = array() ) {
if ( 'title' === $type ) {
return $this->applyTitle( $product_id, $description );
}
if ( 'tags' === $type ) {
return $this->applyTags( $product_id, $description );
}
if ( ! empty( $context['blueprint'] ) ) {
return $this->applyContentStructure( $product_id, $description, $type, $context );
}
$snapshot_staged = false;
try {
$product = wc_get_product( $product_id );
if ( ! $product ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
$is_short = ( $type === 'short' );
$current = $is_short ? $product->get_short_description() : $product->get_description();
if ( (string) $current === $description ) {
return array( 'success' => true );
}
$snapshot_fields = $is_short
? array( 'short_desc' => $description )
: array( 'description' => $description );
\AIPT\Api\Rollback\ContentApplyDispatcher::before( $product_id, $snapshot_fields, 'description' );
$snapshot_staged = true;
if ( $is_short ) {
$product->set_short_description( \AIPT\Utils\DescriptionSanitizer::clean( $description ) );
} else {
$product->set_description( \AIPT\Utils\DescriptionSanitizer::clean( $description ) );
}
$saved = \AIPT\Api\Helpers\ProductSaveVerifier::save( $product );
if ( ! $saved['landed'] ) {
$snapshot_staged = false;
\AIPT\Api\Rollback\ContentApplyDispatcher::after( $product_id, false );
return new \WP_Error( 'update_failed', 'Failed to save product.', array( 'status' => 500 ) );
}
$snapshot_staged = false;
\AIPT\Api\Rollback\ContentApplyDispatcher::after( $product_id, true );
return array( 'success' => true );
} catch ( \Throwable $e ) {
if ( $snapshot_staged ) {
$snapshot_staged = false;
\AIPT\Api\Rollback\ContentApplyDispatcher::after( $product_id, false );
}
return new \WP_Error( 'update_failed', esc_html($e->getMessage()), array( 'status' => 500 ) );
}
}
/**
* Blueprint-mode write for applyContent(): routes through the EXISTING
* Desc\ContentGenerator::applyContent() apply path via
* DescriptionApplyAdapter, so snapshot staging, per-field finalize and
* ContentMarkService::mark() happen exactly as the bulk Description
* path's, never a second, parallel write.
*
* @param int $product_id Product ID.
* @param string $description Description content.
* @param string $type 'full' | 'short'.
* @param array $context {@see applyContent()}'s $context.
* @return array|\WP_Error
*/
private function applyContentStructure( int $product_id, string $description, string $type, array $context ) {
if ( ! wc_get_product( $product_id ) ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
if ( '' === trim( $description ) ) {
return array( 'success' => true );
}
$output_key = ( 'short' === $type ) ? 'shortDescription' : 'description';
$adapter_context = array(
'productId' => $product_id,
'overwrite' => 'empty_only' === ( $context['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace',
'userId' => (int) ( $context['userId'] ?? ( function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0 ) ),
);
$governing = $this->governing_blueprint_resolver->resolveForProducts( BlueprintGenerators::DESCRIPTION, array( $product_id ) );
$resolution = $governing[ $product_id ] ?? array( 'conflict' => true );
if ( empty( $resolution['conflict'] ) ) {
$adapter_context['blueprintId'] = $resolution['blueprintId'];
$adapter_context['blueprintName'] = (string) $resolution['name'];
$adapter_context['blueprintRevision'] = $resolution['revision'];
$adapter_context['blueprintBuiltin'] = (bool) $resolution['builtin'];
}
$adapter = new DescriptionApplyAdapter();
$outcome = $adapter->apply( array( $output_key => $description ), $adapter_context );
if ( 'applied' === $outcome['status'] ) {
return array( 'success' => true );
}
return new \WP_Error( 'update_failed', (string) $outcome['message'], array( 'status' => 500 ) );
}
/**
* Apply a custom-prompts title insert through the EXISTING `title`
* Content Review applier — the same write path Content Review's own
* title approval and content structure's `TitleApplyAdapter` already
* use, so this insert snapshots and marks AI provenance exactly as
* theirs do.
*
* @param int $product_id Product ID.
* @param string $title Title text.
* @return array|\WP_Error
*/
private function applyTitle( int $product_id, string $title ) {
$title = trim( $title );
if ( '' === $title ) {
return array( 'success' => true );
}
$row = array(
'product_id' => $product_id,
'generated_value' => $title,
'apply_context' => wp_json_encode( array( 'update_slug' => false ) ),
);
try {
$ok = ContentReviewApplierFactory::forTool( 'title' )->apply( $row );
} catch ( ContentReviewApplyRefusedException $e ) {
return new \WP_Error( 'update_failed', esc_html( $e->getMessage() ), array( 'status' => 400 ) );
}
if ( ! $ok ) {
return new \WP_Error( 'update_failed', 'Failed to save product.', array( 'status' => 500 ) );
}
return array( 'success' => true );
}
/**
* Apply a custom-prompts tags insert through the EXISTING
* `Desc\ContentGenerator::applyContent()` write path — the same one
* `DescriptionApplyAdapter` uses for its own `tags` field — so this
* insert snapshots and marks AI provenance exactly as theirs does.
*
* @param int $product_id Product ID.
* @param string $tags_csv Comma-separated tag names.
* @return array|\WP_Error
*/
private function applyTags( int $product_id, string $tags_csv ) {
if ( ! wc_get_product( $product_id ) ) {
return new \WP_Error( 'invalid_product', 'Invalid product ID', array( 'status' => 404 ) );
}
if ( '' === trim( $tags_csv ) ) {
return array( 'success' => true );
}
$ok = ( new ContentGenerator() )->applyContent(
$product_id,
array( 'tags' => $tags_csv ),
array( 'keepExistingDescription' => false, 'keepExistingTags' => false )
);
if ( ! $ok ) {
return new \WP_Error( 'update_failed', 'Failed to save product.', array( 'status' => 500 ) );
}
return array( 'success' => true );
}
/**
* Per-product permission check for the custom-prompts (Advanced) path:
* the content structure path already gets this for free from
* ExecutionContextBuilder::checkObjectPermission() (every Blueprint run
* loads its subject through that check), but the Advanced path below
* bypasses the Blueprint engine entirely and had no permission check of
* its own. Reuses the SAME check (and the same error shape) rather than
* a second, drifting copy.
*
* @param int $product_id Product ID.
* @return \WP_Error|null
*
* @since 2.8.0
*/
private function checkProductPermission( int $product_id ): ?\WP_Error {
return ( new ExecutionContextBuilder() )->checkObjectPermission( array( 'type' => 'product', 'id' => $product_id ) );
}
/**
* The shared product eligibility guard ({@see ProductEligibility}),
* reused for every direct `wc_get_product()` lookup this service makes
* itself (both the Blueprint-path helpers above and the Advanced path
* below). A variation's `get_attributes()` returns plain strings instead
* of `WC_Product_Attribute` objects, which `getProductInfo()` cannot
* format, and a trashed product is not a subject any caller should be
* able to (re)generate content for.
*
* @param \WC_Product $product Resolved product.
* @return \WP_Error|null
*/
private function invalidGenerationSubjectError( \WC_Product $product ): ?\WP_Error {
$refusal = ProductEligibility::refusalMessage( $product );
return null === $refusal ? null : new \WP_Error( 'invalid_product', $refusal, array( 'status' => 400 ) );
}
/**
* A run in which no AI section produced anything can still return the
* sections that need no AI call (a fixed text or an attributes table).
* The engine blocks such a run (`ai_generation_failed`), and so does
* every bulk and automation surface ({@see ProviderErrorMessage::isGenerationFailure()}):
* those sections are not generated content, and applying them would
* replace the product's own text while hiding the real failure.
*
* @param array $result The engine's result.
* @param array $fields BlueprintIntegration::responseFields() of $result.
* @return \WP_Error|null The run's classified provider failure when known, else the engine's own reason; null for a run with AI content.
*/
private static function noAiContentError( array $result, array $fields ): ?\WP_Error {
if ( ! ProviderErrorMessage::isGenerationFailure( $fields ) ) {
return null;
}
if ( is_array( $result['providerError'] ?? null ) && '' !== (string) ( $result['providerError']['reason'] ?? '' ) ) {
return self::providerErrorFromArray( $result['providerError'], '' );
}
$reason = ProviderErrorMessage::generationFailureMessage( $fields );
return new \WP_Error(
'generation_failed',
null !== $reason && '' !== trim( $reason ) ? $reason : __( 'No content was generated.', 'ai-product-tools' ),
array( 'status' => 500 )
);
}
/**
* The WP_Error for a classified provider failure: the merchant sentence
* as the message, the structured fields a caller needs to decide
* whether to retry, and the technical text only in error_details —
* never shown to a merchant.
*
* @param ProviderCallException $e Caught provider failure.
* @return \WP_Error
*
* @since 2.8.0
*/
private static function providerErrorResponse( ProviderCallException $e ): \WP_Error {
$fallback_provider = (string) get_option( 'aipt_api_provider', 'openai' );
return self::providerErrorFromArray( $e->toResponseArray( $fallback_provider ), $e->getMessage() );
}
/**
* The same WP_Error built from a providerError a generator already put
* on its result row (TitleGeneratorService reports a failure that way
* instead of throwing).
*
* @param array $provider_error ProviderCallException::toResponseArray() shape.
* @param string $details Text for data.error_details.
* @return \WP_Error
*
* @since 2.8.0
*/
private static function providerErrorFromArray( array $provider_error, string $details ): \WP_Error {
$reason = (string) ( $provider_error['reason'] ?? '' );
return new \WP_Error(
(string) ( $provider_error['code'] ?? 'aipt_provider_error' ),
(string) ( $provider_error['message'] ?? '' ),
array(
'status' => ProviderCallException::httpStatusFor( $reason ),
'reason' => $reason,
'retryable' => ! empty( $provider_error['retryable'] ),
'runWide' => ! empty( $provider_error['runWide'] ),
'retryAfter' => $provider_error['retryAfter'] ?? null,
'provider' => (string) ( $provider_error['provider'] ?? '' ),
'helpUrl' => ProviderCallException::helpUrl( $reason ),
'error_details' => $details,
)
);
}
/**
* Get product information
*
* @param \WC_Product $product Product instance
* @return array Product information array
*/
private function getProductInfo( $product ): array {
$categories = array_values(
array_filter(
array_map(
function ( $term ) {
return ProductCategories::isDefault( (int) $term->term_id ) ? null : $term->name;
},
get_the_terms( $product->get_id(), 'product_cat' ) ?: array()
),
function ( $name ) {
return null !== $name;
}
)
);
$tags = array_map(
function ( $term ) {
return $term->name;
},
get_the_terms( $product->get_id(), 'product_tag' ) ?: array()
);
$attributes = array();
foreach ( $product->get_attributes() as $attribute ) {
if ( $attribute->is_taxonomy() ) {
$terms = get_the_terms( $product->get_id(), $attribute->get_name() );
if ( $terms && ! is_wp_error( $terms ) ) {
$attributes[ wc_attribute_label( $attribute->get_name() ) ] = implode(
', ',
array_map(
function ( $term ) {
return $term->name;
},
$terms
)
);
}
} else {
$attributes[ wc_attribute_label( $attribute->get_name() ) ] = implode( ', ', $attribute->get_options() );
}
}
$prices = ProductPrices::regularAndSale( $product );
return array(
'name' => $product->get_name(),
'sku' => $product->get_sku() ?: 'N/A',
'price' => wc_price( $product->get_price() ),
'regular_price' => '' !== $prices['regular'] ? wc_price( $prices['regular'] ) : 'N/A',
'sale_price' => '' !== $prices['sale'] ? wc_price( $prices['sale'] ) : 'N/A',
'categories' => $categories,
'tags' => $tags,
'attributes' => $attributes,
'short_description' => HtmlToText::convert( $product->get_short_description() ),
'description' => HtmlToText::convert( $product->get_description() ),
);
}
/**
* Clean prompt content
*
* @param string $prompt Prompt text
* @param array $product_info Product information
* @return string Cleaned prompt
*/
private function cleanPromptContent( string $prompt, array $product_info ): string {
$formatted = trim( $prompt );
$formatted = preg_replace( '/\s+/', ' ', $formatted );
$formatted = preg_replace( '/\n+/', "\n", $formatted );
return $formatted;
}
}