discovery_service = $discovery_service ?: new TaxonomyDiscoveryService(); $this->data_formatter = $data_formatter ?: new TaxonomyDataFormatter( $this->discovery_service ); $this->prompt_factory = $prompt_factory ?: new TaxonomyPromptFactory(); $this->client_factory = $client_factory ?: new RestAPIClientFactory(); } /** * @param array $term_ids Term IDs. * @param string $taxonomy Taxonomy name. * @param array $sources Selected context sources. * @param array $options Runtime generation options. * * @return array{results: array, errors: array, skipped: array, applied_free_defaults: array} */ public function generate( array $term_ids, string $taxonomy, array $sources, array $options ): array { $taxonomy = (string) sanitize_key( $taxonomy ); $normalized_term_ids = array_values( array_unique( array_filter( array_map( 'absint', $term_ids ) ) ) ); $normalized_sources = $this->normalize_sources( $sources ); $requested_sources = $normalized_sources; $requested_options = $options; $controlled = $this->applyPremiumControls( $normalized_sources, $options ); $normalized_sources = $controlled['sources']; $options = $controlled['options']; $applied_defaults = $this->detectAppliedFreeDefaults( $requested_sources, $requested_options, $normalized_sources, $options ); $skip_existing = ! empty( $options['skipExisting'] ); $provider = isset( $options['provider'] ) && is_string( $options['provider'] ) ? sanitize_key( $options['provider'] ) : sanitize_key( (string) get_option( 'aipt_api_provider', 'openai' ) ); $provider = (string) $provider; $selected_model = isset( $options['model'] ) && is_string( $options['model'] ) ? sanitize_text_field( $options['model'] ) : ''; if ( '' === $selected_model ) { $selected_model = $this->client_factory->getDefaultModel( $provider ); } $model = $this->client_factory->normalizeModel( $provider, $selected_model ); $results = []; $errors = []; $skipped = []; $execution_path = BlueprintIntegration::executionPath( BlueprintGenerators::TAXONOMY, [] ); $use_blueprint = BlueprintIntegration::PATH_BLUEPRINT === $execution_path['path']; foreach ( $normalized_term_ids as $term_id ) { try { $term = $this->discovery_service->getTermById( $term_id, $taxonomy ); if ( ! is_array( $term ) ) { throw new \RuntimeException( __( 'Term could not be loaded.', 'ai-product-tools' ) ); } if ( $skip_existing && ! empty( $term['description'] ) ) { $skipped[] = [ 'term_id' => (int) $term_id, 'term_name' => (string) ( $term['name'] ?? '' ), 'taxonomy' => $taxonomy, 'reason' => __( 'Term already has a description.', 'ai-product-tools' ), ]; continue; } if ( $use_blueprint ) { $results[] = $this->generateTermBlueprint( $term_id, $taxonomy, $term, $requested_options ); continue; } $term_context = $this->data_formatter->formatTermContext( $term_id, $taxonomy, $normalized_sources, $options ); $taxonomy_obj = call_user_func( 'get_taxonomy', $taxonomy ); if ( $taxonomy_obj && ! empty( $taxonomy_obj->label ) ) { $term_context['taxonomy_label'] = (string) $taxonomy_obj->label; } $filtered_options = apply_filters( 'aipt_taxonomy_generator_options', $options, $term_context ); if ( ! is_array( $filtered_options ) ) { $filtered_options = $options; } $prompt_pair = $this->prompt_factory->buildPrompt( $term_context, $filtered_options ); $client = $this->client_factory->create( $provider ); $generated_content = $client->generate_description( (string) $prompt_pair['system'], (string) $prompt_pair['user'], $model, null ); $sanitized_content = wp_kses_post( $generated_content ); $results[] = array_merge( [ 'term_id' => (int) $term_id, 'term_name' => (string) ( $term['name'] ?? '' ), 'taxonomy' => $taxonomy, 'content' => $sanitized_content, 'status' => 'pending', 'originalContent' => $sanitized_content, 'existingDescription' => (string) ( $term['description'] ?? '' ), ], BlueprintIntegration::advancedResponseFields() ); } catch ( \Throwable $throwable ) { $errors[] = [ 'term_id' => (int) $term_id, 'taxonomy' => $taxonomy, 'message' => ProviderCallException::displayMessage( $throwable, $provider ), 'providerError' => ProviderCallException::providerErrorFor( $throwable, $provider ), ]; } } $response = [ 'results' => $results, 'errors' => $errors, 'skipped' => $skipped, 'applied_free_defaults' => $applied_defaults, ]; if ( ! empty( $applied_defaults ) ) { $response['applied_free_defaults_reason'] = PlanDenial::reason( $this->paidOptionFeature( $applied_defaults[0] ), PlanDenial::PLAN_PAID ); } return $response; } /** * Content structure term generation. Runs the shared engine via * {@see BlueprintIntegration} with the term's subject scope (never a * product id), then returns the SAME `TaxonomyGenerationResult` shape * the Advanced path returns so `applyDescriptions()` (the EXISTING * term write path) needs no change. * * The "custom purpose" Free/Business gate (a Blueprint 'custom' AI * section lets the user's own instruction become * the task framing, exactly like the legacy `purpose: 'custom'`) is * enforced by the engine's own `Engine\Policy\EntitlementPolicy` now, * BEFORE any provider call — not here, and not after the call returns. * A non-entitled 'custom' section is disabled by that policy pre-flight, * so it can never come back as an included AI unit and never spends a * call; this method only surfaces that outcome via * `appliedFreeDefaults`, it never throws for it. * * @param int $term_id Term id. * @param string $taxonomy Taxonomy name. * @param array $term Term row from TaxonomyDiscoveryService::getTermById(). * @param array $requested_options Raw (not Free/Business-controlled) request options. * @return array * @throws \RuntimeException On a Blueprint error. */ private function generateTermBlueprint( int $term_id, string $taxonomy, array $term, array $requested_options ): array { $run_options = array(); foreach ( array( 'language', 'provider', 'model' ) as $key ) { if ( isset( $requested_options[ $key ] ) && is_string( $requested_options[ $key ] ) && '' !== $requested_options[ $key ] ) { $run_options[ $key ] = $requested_options[ $key ]; } } $result = BlueprintIntegration::run( BlueprintGenerators::TAXONOMY, array( 'type' => 'term', 'id' => $term_id ), array( 'blueprintRun' => isset( $requested_options['blueprintRun'] ) ? (int) $requested_options['blueprintRun'] : 0, 'blueprintId' => isset( $requested_options['blueprintId'] ) ? (int) $requested_options['blueprintId'] : 0, 'overwrite' => isset( $requested_options['overwrite'] ) ? (string) $requested_options['overwrite'] : 'replace', ), $run_options, 'bulk' ); if ( is_wp_error( $result ) ) { throw new \RuntimeException( $result->get_error_message() ); } $sanitized_content = wp_kses_post( (string) ( $result['outputs']['termDescription'] ?? '' ) ); $blueprint_fields = BlueprintIntegration::responseFields( $result ); if ( ProviderErrorMessage::isGenerationFailure( $blueprint_fields ) ) { $message = ProviderErrorMessage::generationFailureMessage( $blueprint_fields ) ?? __( 'Term description generation failed.', 'ai-product-tools' ); throw new \RuntimeException( $message ); } return array_merge( array( 'term_id' => $term_id, 'term_name' => (string) ( $term['name'] ?? '' ), 'taxonomy' => $taxonomy, 'content' => $sanitized_content, 'status' => 'pending', 'originalContent' => $sanitized_content, 'existingDescription' => (string) ( $term['description'] ?? '' ), ), $blueprint_fields, array( 'appliedFreeDefaults' => is_array( $result['appliedFreeDefaults'] ?? null ) ? $result['appliedFreeDefaults'] : array() ) ); } /** * @param array $applications Requested apply payload. Each item may carry * a `blueprint` array `{id,name,revision,builtin}` * (already sanitized/trusted by the caller) when * a Blueprint run wrote the description; absent * for a custom-prompts write. * * @return array> */ public function applyDescriptions( array $applications ): array { $results = []; foreach ( $applications as $application ) { $term_id = isset( $application['term_id'] ) ? absint( $application['term_id'] ) : 0; $taxonomy = isset( $application['taxonomy'] ) ? sanitize_key( (string) $application['taxonomy'] ) : ''; $content = isset( $application['content'] ) ? wp_kses_post( (string) $application['content'] ) : ''; $write_mode = isset( $application['writeMode'] ) ? sanitize_key( (string) $application['writeMode'] ) : 'overwrite'; $blueprint = isset( $application['blueprint'] ) && is_array( $application['blueprint'] ) ? $application['blueprint'] : null; if ( ! in_array( $write_mode, [ 'overwrite', 'append' ], true ) ) { $write_mode = 'overwrite'; } if ( $term_id <= 0 || '' === $taxonomy ) { $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => false, 'message' => __( 'Invalid term application payload.', 'ai-product-tools' ), ]; continue; } if ( ! current_user_can( 'edit_term', $term_id ) ) { $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => false, 'message' => __( 'You are not allowed to edit this term.', 'ai-product-tools' ), ]; continue; } $term = $this->discovery_service->getTermById( $term_id, $taxonomy ); if ( ! is_array( $term ) ) { $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => false, 'message' => __( 'Term could not be loaded.', 'ai-product-tools' ), ]; continue; } $final_content = $content; if ( 'append' === $write_mode ) { $existing_content = isset( $term['description'] ) ? (string) $term['description'] : ''; $final_content = '' !== trim( $existing_content ) ? $existing_content . "\n\n" . $content : $content; } $snapshot_fields = [ 'term_description' => $final_content ]; 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::beforeTerm( $term_id, $taxonomy, $snapshot_fields, 'taxonomy' ); try { $update_result = \AIPT\Utils\TermDescriptionWriter::write( $term_id, $taxonomy, $final_content ); } catch ( \Throwable $e ) { \AIPT\Api\Rollback\ContentApplyDispatcher::afterTerm( $term_id, $taxonomy, false ); $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => false, 'message' => sanitize_text_field( $e->getMessage() ), ]; continue; } $write_succeeded = ! is_wp_error( $update_result ); \AIPT\Api\Rollback\ContentApplyDispatcher::afterTerm( $term_id, $taxonomy, $write_succeeded ); if ( ! $write_succeeded ) { $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => false, 'message' => sanitize_text_field( $update_result->get_error_message() ), ]; continue; } \AIPT\Core\ContentSnapshots\TermEditorConcurrencyToken::bump_revision( $term_id ); $results[] = [ 'term_id' => $term_id, 'taxonomy' => $taxonomy, 'success' => true, 'message' => __( 'Description applied successfully.', 'ai-product-tools' ), 'mode' => $write_mode, ]; } return $results; } /** * @param array $sources Raw source values. * * @return array */ private function normalize_sources( array $sources ): array { $normalized = []; foreach ( $sources as $source ) { if ( ! is_string( $source ) ) { continue; } $key = sanitize_key( $source ); if ( '' !== $key ) { $normalized[] = $key; } } if ( ! in_array( 'term_name', $normalized, true ) ) { $normalized[] = 'term_name'; } return array_values( array_unique( $normalized ) ); } /** * Free-tier allowed data sources. * * @var string[] */ private const FREE_SOURCES = [ 'term_name', 'parent_context', 'term_description', 'product_categories', 'product_names', 'product_prices', 'product_tags', ]; /** * Free-tier allowed generation purposes. * * @var string[] */ private const FREE_PURPOSES = [ 'seo_description', 'marketing_overview', 'technical_summary', 'brand_story', ]; /** * Free-tier maximum product samples. * * @var int */ private const FREE_MAX_SAMPLES = 10; /** * Paid data sources (restored by the premium module for paid plans). * * @var string[] */ private const PREMIUM_SOURCES = [ 'product_descriptions', 'product_attributes', ]; /** * Paid generation purposes (restored by the premium module for paid plans). * * @var string[] */ private const PREMIUM_PURPOSES = [ 'custom', ]; /** * List the paid options that were requested but replaced by Free defaults. * * Only a real downgrade is reported: an unknown source, a free value or a * cap an entitled plan applies is not. The stored site-level prompt is * reported when it exists and the additional-prompt gate skips it; it is * read here only to report, never applied. * * @param string[] $requested_sources Normalized requested sources. * @param array $requested_options Request options. * @param string[] $applied_sources Sources after applyPremiumControls(). * @param array $applied_options Options after applyPremiumControls(). * @return string[] Reported option keys. */ private function detectAppliedFreeDefaults( array $requested_sources, array $requested_options, array $applied_sources, array $applied_options ): array { $dropped = array(); foreach ( $requested_sources as $source ) { if ( in_array( $source, self::PREMIUM_SOURCES, true ) && ! in_array( $source, $applied_sources, true ) ) { $dropped[] = 'source:' . $source; } } $requested_purpose = isset( $requested_options['purpose'] ) ? sanitize_key( (string) $requested_options['purpose'] ) : ''; if ( in_array( $requested_purpose, self::PREMIUM_PURPOSES, true ) && $requested_purpose !== sanitize_key( (string) ( $applied_options['purpose'] ?? '' ) ) ) { $dropped[] = 'purpose'; } $requested_samples = $requested_options['maxProductSamples'] ?? null; if ( is_numeric( $requested_samples ) && absint( $requested_samples ) > self::FREE_MAX_SAMPLES && self::FREE_MAX_SAMPLES === absint( $applied_options['maxProductSamples'] ?? 0 ) ) { $dropped[] = 'maxProductSamples'; } if ( ! BlueprintIntegration::usesBlueprint( BlueprintGenerators::TAXONOMY, array() ) && ! apply_filters( 'aipt_taxonomy_additional_prompt_allowed', false ) && '' !== trim( (string) get_option( 'aipt_taxonomy_additional_prompt', '' ) ) ) { $dropped[] = 'siteAdditionalPrompt'; } return $dropped; } /** * Feature key for a reported option (all are paid-plan features). * * @param string $option_key Key from detectAppliedFreeDefaults(). * @return string */ private function paidOptionFeature( string $option_key ): string { if ( 0 === strpos( $option_key, 'source:' ) ) { return 'taxonomyPremiumSources'; } $features = array( 'purpose' => 'taxonomyPremiumPurpose', 'maxProductSamples' => 'taxonomySamplesSlider', 'siteAdditionalPrompt' => 'taxonomyAdditionalPrompt', ); return $features[ $option_key ] ?? 'taxonomyAdditionalPrompt'; } /** * Apply premium feature controls to generation parameters. * * Enforces free-tier defaults for sources, purpose, and sample limit. * Premium module hooks into the apply_filters calls to restore premium values. * * @param array $sources Raw sources from request. * @param array $options Raw options from request. * @return array{sources: array, options: array} Controlled parameters. */ private function applyPremiumControls( array $sources, array $options ): array { /** * Filter allowed taxonomy sources. * * Premium module hooks here to add premium sources * (product_descriptions, product_attributes). * * @since 2.5.0 * @param string[] $allowed_sources Free-tier allowed sources. */ $allowed_sources = apply_filters( 'aipt_taxonomy_allowed_sources', self::FREE_SOURCES ); if ( ! is_array( $allowed_sources ) ) { $allowed_sources = self::FREE_SOURCES; } $controlled_sources = array_values( array_intersect( $sources, $allowed_sources ) ); if ( ! in_array( 'term_name', $controlled_sources, true ) ) { $controlled_sources[] = 'term_name'; } /** * Filter allowed taxonomy purposes. * * Premium module hooks here to add custom purpose. * * @since 2.5.0 * @param string[] $allowed_purposes Free-tier allowed purposes. */ $allowed_purposes = apply_filters( 'aipt_taxonomy_allowed_purposes', self::FREE_PURPOSES ); if ( ! is_array( $allowed_purposes ) ) { $allowed_purposes = self::FREE_PURPOSES; } $controlled_options = $options; if ( isset( $controlled_options['purpose'] ) ) { $purpose = sanitize_key( (string) $controlled_options['purpose'] ); if ( ! in_array( $purpose, $allowed_purposes, true ) ) { $controlled_options['purpose'] = self::FREE_PURPOSES[0]; } } /** * Filter maximum product samples for taxonomy generation. * * Premium module hooks here to increase the sample limit. * * @since 2.5.0 * @param int $max_samples Free-tier maximum samples. */ $max_samples = apply_filters( 'aipt_taxonomy_max_samples', self::FREE_MAX_SAMPLES ); if ( ! is_int( $max_samples ) || $max_samples < 1 ) { $max_samples = self::FREE_MAX_SAMPLES; } if ( isset( $controlled_options['maxProductSamples'] ) ) { $requested = absint( $controlled_options['maxProductSamples'] ); $controlled_options['maxProductSamples'] = min( $requested, $max_samples ); } return [ 'sources' => $controlled_sources, 'options' => $controlled_options, ]; } }