prompt_factory = $prompt_factory ?? new FAQPromptFactory(); } /** * Generate FAQs for a set of products. * * @param array $product_ids * @param array $options * @return array */ public function bulk_generate(array $product_ids, array $options): array { $results = []; $faq_count = self::normalize_faq_count($options['faqCount'] ?? self::DEFAULT_FAQ_COUNT); $format = $this->normalize_format($options['faqFormat'] ?? self::DEFAULT_FORMAT); $mode = $this->normalize_mode($options['faqMode'] ?? self::DEFAULT_MODE); $write_mode = $this->normalize_write_mode($options['writeMode'] ?? self::DEFAULT_WRITE_MODE); $sources = $this->normalize_sources($options['faqSources'] ?? ['product_description']); $language = isset($options['language']) && is_string($options['language']) && '' !== trim($options['language']) ? sanitize_text_field($options['language']) : get_option('aipt_language', 'English'); $exclude_questions = $this->normalize_exclude_questions($options['excludeQuestions'] ?? []); $default_faq_options = array( 'global_additional_prompt' => '', ); /** * Filter FAQ generator options. * * Allows premium module to extend FAQ generation with additional prompt from settings. * In free version, global_additional_prompt remains empty string. * * @param array $default_options Default free options. * @param array $options Options passed from request. * @return array Modified options. */ $filtered_faq_options = apply_filters( 'aipt_faq_generator_options', $default_faq_options, $options ); $global_additional_prompt = isset( $filtered_faq_options['global_additional_prompt'] ) ? PromptFormatter::cleanOutboundPrompt( $filtered_faq_options['global_additional_prompt'] ) : ''; $provider = isset($options['provider']) && is_string($options['provider']) ? sanitize_text_field($options['provider']) : get_option('aipt_api_provider', 'openai'); $model = isset($options['model']) && is_string($options['model']) ? sanitize_text_field($options['model']) : null; $use_blueprint = BlueprintIntegration::usesBlueprint(Generators::FAQ, BlueprintIntegration::jobTrustedFacts()); foreach ($product_ids as $product_id) { $product_id = absint($product_id); if ($product_id <= 0) { continue; } $product = wc_get_product($product_id); if (!ProductEligibility::isEligible($product)) { $results[] = [ 'product_id' => $product_id, 'error' => __('Product could not be loaded', 'ai-product-tools'), ]; continue; } if ($use_blueprint) { $results[] = $this->generateViaBlueprint( $product_id, $options, 'append' === $write_mode ? $this->merge_saved_questions($product_id, $exclude_questions) : $exclude_questions ); continue; } try { $product_data = ProductDataFormatter::getFormattedProductData($product); $prompt_payload = $this->prompt_factory->build_prompt_payload([ 'format' => $format, 'mode' => $mode, 'faq_count' => $faq_count, 'language' => $language, 'write_mode' => $write_mode, 'sources' => $sources, 'global_additional_prompt' => $global_additional_prompt, 'exclude_questions' => 'append' === $write_mode ? $this->merge_saved_questions($product_id, $exclude_questions) : $exclude_questions, ], $product_data, $product); $client = AIClientFactory::create($provider, [ 'category' => $product_data['categories'] ?? '', 'generation_type' => 'faq', 'model' => $model, ]); $raw_output = $client->generate_faq_content( $prompt_payload['system_prompt'], $prompt_payload['user_prompt'], $model ); if ($this->is_no_faq_answer($raw_output)) { $results[] = array_merge(BlueprintIntegration::advancedResponseFields(), [ 'product_id' => $product_id, 'faqs' => [], 'format' => $format, 'mode' => $mode, 'raw' => '', 'error' => __('No FAQs were written: the product data does not answer any customer question. Add product details or select more sources, then try again.', 'ai-product-tools'), ]); continue; } $parsed = $this->parse_faq_response($raw_output, $format, $this->modeParts($mode), $faq_count); $item = [ 'product_id' => $product_id, 'faqs' => $parsed['faqs'], 'format' => $format, 'mode' => $mode, 'raw' => $parsed['raw'], ]; if (empty($parsed['faqs'])) { $item['error'] = __('The AI response did not contain any FAQ items.', 'ai-product-tools'); } $results[] = array_merge(BlueprintIntegration::advancedResponseFields(), $item); } catch (\Exception $exception) { $results[] = array_merge( BlueprintIntegration::advancedResponseFields(), [ 'product_id' => $product_id, 'error' => ProviderCallException::displayMessage($exception, $provider), 'providerError' => ProviderCallException::providerErrorFor($exception, $provider), ] ); } } return $results; } /** * Generate one product's FAQ through the content structure engine. * Returns the EXACT per-product shape the legacy branch returns * (`faqs` flat `[{question,answer}]`, `format`, * `mode`, `raw`), plus the additional Blueprint response fields, so the * controller's existing review-staging/apply/writeMode handling needs no * changes. A Blueprint legitimately producing zero questions (every * group disabled or skipped by condition/missing data) is NOT treated as * a failure, matching the legacy parser's own tolerance for an empty * result. * * @since 2.8.0 * * @param int $product_id WooCommerce product id. * @param array $options Request options (generationMode, provider, model, language, blueprintRun, blueprintId, overwrite). * @param string[] $exclude_questions Questions the run must not ask again (an appending run includes the product's saved ones). * @return array */ private function generateViaBlueprint(int $product_id, array $options, array $exclude_questions = []): array { $run_options = [ 'language' => (isset($options['language']) && is_string($options['language']) && '' !== trim($options['language'])) ? $options['language'] : 'store', 'provider' => isset($options['provider']) && is_string($options['provider']) ? $options['provider'] : '', 'model' => isset($options['model']) && is_string($options['model']) ? $options['model'] : '', 'excludeQuestions' => $exclude_questions, ]; $result = BlueprintIntegration::run( Generators::FAQ, [ 'type' => 'product', 'id' => $product_id ], $options, $run_options, 'bulk' ); if (is_wp_error($result)) { return [ 'product_id' => $product_id, 'error' => $result->get_error_message(), ]; } $faqs = []; foreach ((array) ($result['outputs']['faq'] ?? []) as $pair) { if (is_array($pair) && isset($pair['question'], $pair['answer'])) { $faqs[] = [ 'question' => (string) $pair['question'], 'answer' => (string) $pair['answer'] ]; } } $generation_mode = is_string($options['generationMode'] ?? null) ? $options['generationMode'] : 'client_preview'; $destination = BlueprintIntegration::destinationForMode($generation_mode); $held_back = BlueprintIntegration::isHeldBack($result, $destination); $item = [ 'product_id' => $product_id, 'faqs' => $faqs, 'format' => 'text', 'mode' => 'both', 'raw' => '', ]; $blueprint_fields = BlueprintIntegration::responseFields($result); $item = array_merge($item, $blueprint_fields); if ($held_back && !empty($faqs)) { $item['status'] = 'needs_review'; } if (empty($faqs)) { foreach ((array) ($result['units'] ?? []) as $unit) { if (is_array($unit) && 'skipped_missing_data' === ($unit['status'] ?? '') && is_string($unit['reason'] ?? null) && '' !== $unit['reason']) { $item['skippedReason'] = $unit['reason']; break; } } } if (ProviderErrorMessage::isGenerationFailure($blueprint_fields)) { $item['error'] = ProviderErrorMessage::generationFailureMessage($blueprint_fields) ?? __('FAQ generation failed for this product.', 'ai-product-tools'); } return $item; } /** * Normalize a faqCount request value: a non-numeric value (including * one already mangled into 0 by an upstream absint()/(int) cast) falls * back to DEFAULT_FAQ_COUNT, otherwise the value is clamped to * [MIN_FAQ_COUNT, MAX_FAQ_COUNT]. The single source of truth for that * fallback, called here and by every other entry point that accepts a * raw faqCount value (FAQGeneratorController::sanitizeOptions(), * OptionsTranslator's automation job translation) so a non-numeric * value is never coerced to int before reaching this check. * * @param mixed $count Raw faqCount value. * @return int */ public static function normalize_faq_count($count): int { $value = is_numeric($count) ? (int) $count : self::DEFAULT_FAQ_COUNT; if ($value < self::MIN_FAQ_COUNT) { $value = self::MIN_FAQ_COUNT; } if ($value > self::MAX_FAQ_COUNT) { $value = self::MAX_FAQ_COUNT; } return $value; } private function normalize_format($format): string { $value = is_string($format) ? strtolower($format) : self::DEFAULT_FORMAT; return in_array($value, self::SUPPORTED_FORMATS, true) ? $value : self::DEFAULT_FORMAT; } private function normalize_mode($mode): string { $value = is_string($mode) ? strtolower($mode) : self::DEFAULT_MODE; return null !== $this->registeredModeParts($value) ? $value : self::DEFAULT_MODE; } /** * Which halves of each FAQ a mode asks the model for. Public: also used * by FAQGeneratorController to re-check a result's required half before * its own direct-write apply path, the single source of truth for what * a mode name means shared with the generation-time filter above. * * @param string $mode Normalized generation mode. * @return array{question:bool,answer:bool} */ public function modeParts(string $mode): array { return $this->registeredModeParts($mode) ?? ['question' => true, 'answer' => true]; } /** * The halves of each FAQ a mode asks for, or null for a mode nobody * registered. The default question-and-answer pairs ask for both; the * Premium build registers its questions-only and answers-only modes on * `aipt_faq_mode_parts`. * * @param string $mode Generation mode. * @return array{question:bool,answer:bool}|null */ private function registeredModeParts(string $mode): ?array { if (self::DEFAULT_MODE === $mode) { return ['question' => true, 'answer' => true]; } /** * Filter the halves of each FAQ a generation mode asks for. * * @since 2.8.0 * @param array{question:bool,answer:bool}|null $parts Null for an unknown mode. * @param string $mode Generation mode. */ $parts = apply_filters('aipt_faq_mode_parts', null, $mode); if (!is_array($parts) || !isset($parts['question'], $parts['answer']) || (!$parts['question'] && !$parts['answer'])) { return null; } return ['question' => (bool) $parts['question'], 'answer' => (bool) $parts['answer']]; } private function normalize_write_mode($write_mode): string { $value = is_string($write_mode) ? strtolower($write_mode) : self::DEFAULT_WRITE_MODE; return in_array($value, self::SUPPORTED_WRITE_MODES, true) ? $value : self::DEFAULT_WRITE_MODE; } private function normalize_sources($sources): array { $normalized = []; if (is_array($sources)) { foreach ($sources as $source) { $key = sanitize_key($source); if (!empty($key)) { $normalized[] = $key; } } } if (!in_array('product_description', $normalized, true)) { $normalized[] = 'product_description'; } return array_values(array_unique($normalized)); } /** * @param mixed $questions * @return array */ private function normalize_exclude_questions($questions): array { if (!is_array($questions)) { return []; } $clean = []; foreach ($questions as $question) { if (!is_string($question)) { continue; } $value = sanitize_text_field($question); if ('' !== $value) { $clean[] = $value; } } return array_values(array_slice(array_unique($clean), 0, self::MAX_EXCLUDE_QUESTIONS)); } /** * Merge a product's already-saved FAQ questions into the caller-supplied * exclude list. * * The client builds `excludeQuestions` from whatever FAQ content it * currently has loaded for the product; a client that has not loaded * the product's saved FAQ yet (or any caller other than the FAQ * Generator UI) can send an empty list even though the product already * has live questions. Reading `_aipt_faq_data` here closes that gap * server-side, so a request can never ask the AI to repeat a question * the product already shows live, regardless of what the client sent. * * @param int $product_id * @param array $exclude_questions Already-normalized exclude list from the request. * @return array */ private function merge_saved_questions(int $product_id, array $exclude_questions): array { $saved_questions = SavedFaqQuestions::forProduct($product_id); if (empty($saved_questions)) { return $exclude_questions; } return $this->normalize_exclude_questions(array_merge($saved_questions, $exclude_questions)); } /** * @param string $raw_output * @param string $format * @param array{question:bool,answer:bool} $mode_parts Halves of each FAQ the mode asked for. * @param int $faq_count * @return array{faqs:array>,raw:string} */ private function parse_faq_response(string $raw_output, string $format, array $mode_parts, int $faq_count): array { $clean_output = $this->strip_code_fences(PromptFormatter::cleanContent($raw_output)); $faqs = []; if ($format === 'text') { $faqs = $this->parse_text_output($clean_output, $mode_parts); } else { $faqs = $this->parse_html_output($clean_output, $mode_parts); } $faqs = array_map( function (array $faq_item) use ($format): array { return $this->sanitize_faq_item($faq_item, $format); }, $faqs ); $faqs = array_slice( array_values(array_filter($faqs, static function (array $faq) use ($mode_parts): bool { return (!$mode_parts['question'] || '' !== trim(wp_strip_all_tags($faq['question']))) && (!$mode_parts['answer'] || '' !== trim(wp_strip_all_tags($faq['answer']))); })), 0, $faq_count ); return [ 'faqs' => $faqs, 'raw' => $format === 'html' ? wp_kses_post($clean_output) : sanitize_textarea_field($clean_output), ]; } private function parse_text_output(string $content, array $mode_parts): array { $inline_faqs = $this->parse_inline_text_output($content, $mode_parts); if (!empty($inline_faqs)) { return $inline_faqs; } $lines = preg_split('/\r\n|\r|\n/', $content); $faqs = []; $current = ['question' => '', 'answer' => '']; $question_pattern = '/^(?:Q(?:uestion)?)(?:\s*\d+)?\s*[:.\-]\s*(.*)$/i'; $answer_pattern = '/^(?:A(?:nswer)?)(?:\s*\d+)?\s*[:.\-]\s*(.*)$/i'; foreach ($lines as $line) { $trimmed = trim($line); if ($trimmed === '') { if (!empty($current['question']) || !empty($current['answer'])) { $faqs[] = $current; $current = ['question' => '', 'answer' => '']; } continue; } if (preg_match($question_pattern, $trimmed, $matches)) { if (!empty($current['question']) || !empty($current['answer'])) { $faqs[] = $current; $current = ['question' => '', 'answer' => '']; } $current['question'] = trim($matches[1]); continue; } if (preg_match($answer_pattern, $trimmed, $matches)) { if (!$mode_parts['question'] && (!empty($current['question']) || !empty($current['answer']))) { $faqs[] = $current; $current = ['question' => '', 'answer' => '']; } $current['answer'] = trim($matches[1]); continue; } if (!$mode_parts['question'] && empty($current['answer'])) { $current['answer'] = $trimmed; } elseif (!$mode_parts['answer'] && empty($current['question'])) { $current['question'] = $trimmed; } elseif (!empty($current['answer'])) { $current['answer'] .= ' ' . $trimmed; } else { $current['question'] .= (empty($current['question']) ? '' : ' ') . $trimmed; } } if (!empty($current['question']) || !empty($current['answer'])) { $faqs[] = $current; } return $faqs; } private function parse_inline_text_output(string $content, array $mode_parts): array { if (stripos($content, 'A:') === false && stripos($content, 'Answer:') === false) { return []; } $normalized = preg_replace('/\s+/', ' ', trim($content)); if ($normalized === '') { return []; } $pattern = '/(?:\bQ(?:uestion)?\b\s*\d*(?:[\.\-:])\s*)(.*?)(?:\s*\bA(?:nswer)?\b\s*\d*(?:[\.\-:])\s*)(.*?)(?=\bQ(?:uestion)?\b\s*\d*(?:[\.\-:])|\z)/is'; preg_match_all($pattern, $normalized, $matches, PREG_SET_ORDER); if (empty($matches)) { return []; } $faqs = []; foreach ($matches as $match) { $question = isset($match[1]) ? trim($match[1]) : ''; $answer = isset($match[2]) ? trim($match[2]) : ''; if (!$mode_parts['answer']) { $answer = ''; } elseif (!$mode_parts['question']) { $question = ''; } if ($question === '' && $answer === '') { continue; } $faqs[] = [ 'question' => $question, 'answer' => $answer, ]; } return $faqs; } private function parse_html_output(string $content, array $mode_parts): array { $faqs = []; if (preg_match_all('/
(.*?)<\/dt>\s*
(.*?)<\/dd>/is', $content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $faqs[] = [ 'question' => wp_strip_all_tags($match[1]), 'answer' => wp_strip_all_tags($match[2]), ]; } return $faqs; } if (preg_match_all('/
  • (.*?)<\/li>/is', $content, $matches)) { foreach ($matches[1] as $match) { if (!$mode_parts['answer']) { $faqs[] = ['question' => wp_strip_all_tags($match), 'answer' => '']; continue; } $split = preg_split('/\?[\s\-:]*|[:\-]\s*/', wp_strip_all_tags($match), 2); if (!empty($split)) { $question = $split[0]; $answer = isset($split[1]) ? $split[1] : ''; $faqs[] = [ 'question' => $question, 'answer' => $answer, ]; } } return $faqs; } return $this->parse_text_output(wp_strip_all_tags($content), $mode_parts); } private function sanitize_faq_item(array $faq, string $format): array { if ($format === 'html') { $question = isset($faq['question']) ? wp_kses_post($faq['question']) : ''; $answer = isset($faq['answer']) ? wp_kses_post($faq['answer']) : ''; } else { $question = isset($faq['question']) ? sanitize_text_field($faq['question']) : ''; $answer = isset($faq['answer']) ? sanitize_textarea_field($faq['answer']) : ''; } return [ 'question' => $question, 'answer' => $answer, ]; } /** * Whether the answer is the prompt's reply for product data that * supports no FAQ (FAQPromptFactory::NO_FAQ), allowing for a code * fence, quotes or a sentence explaining it after the marker. * * @param string $raw_output The model's answer. * @return bool */ private function is_no_faq_answer(string $raw_output): bool { $answer = ltrim($this->strip_code_fences($raw_output), " \t\n\r\"'`*"); return 1 === preg_match('/^' . FAQPromptFactory::NO_FAQ . '\b/i', $answer); } private function strip_code_fences(string $content): string { $content = trim($content); if (preg_match('/^```[a-zA-Z0-9]*\n(.*)\n```$/s', $content, $matches)) { return trim($matches[1]); } return $content; } }