generator = $generator ?? new ContentGenerator(); $this->productFilterService = $productFilterService ?? new ProductFilterService(); } public function register_routes(): void { register_rest_route( self::REST_NAMESPACE, '/products', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_products' ), 'permission_callback' => array( $this, 'check_permissions' ), 'args' => $this->get_product_args(), ) ); register_rest_route( self::REST_NAMESPACE, '/categories', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_categories' ), 'permission_callback' => array( $this, 'check_permissions' ), ) ); register_rest_route( self::REST_NAMESPACE, '/tags', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_tags' ), 'permission_callback' => array( $this, 'check_permissions' ), ) ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/generate', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'generate_single' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); $bulk_generate_endpoint = array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_generate' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/bulk-generate', $bulk_generate_endpoint ); $editor_bulk_generate_endpoint = $bulk_generate_endpoint; $editor_bulk_generate_endpoint['permission_callback'] = array( $this, 'check_permissions_editor_bulk_write' ); register_rest_route( self::REST_NAMESPACE . '/description-generator', '/editor-bulk-generate', $editor_bulk_generate_endpoint ); } public function get_products( WP_REST_Request $request ): WP_REST_Response { try { $response = $this->productFilterService->fetchFilteredProducts( (array) $request->get_params() ); if ( isset( $response['products'] ) && is_array( $response['products'] ) ) { $response['products'] = \AIPT\Core\ContentMarking\AiMarkReader::annotateProducts( $response['products'] ); } return new WP_REST_Response( $response, 200 ); } catch ( \Throwable $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { } return new WP_REST_Response( array( 'success' => false, 'products' => array(), 'total' => 0, 'totalPages' => 0, 'page' => absint( $request->get_param( 'page' ) ?: 1 ), 'perPage' => absint( $request->get_param( 'per_page' ) ?: 10 ), 'error' => 'An error occurred while fetching products.', ), 200 ); } } public function get_categories(): WP_REST_Response { try { $categories = ProductFilterMapper::getCategories(); return new WP_REST_Response( $categories, 200 ); } catch ( \Throwable $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { } return new WP_REST_Response( array(), 200 ); } } public function get_tags(): WP_REST_Response { try { $tags = ProductFilterMapper::getTags(); return new WP_REST_Response( $tags, 200 ); } catch ( \Throwable $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { } return new WP_REST_Response( array(), 200 ); } } public function generate_single( WP_REST_Request $request ) { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { return $ai_gate; } $rate_check = $this->checkRateLimit( (int) get_current_user_id(), static::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $data = $request->get_json_params(); $product_id = absint( $data['productId'] ?? 0 ); $options = $this->sanitize_generation_options( $data['options'] ?? array() ); $options = $this->enforce_generation_mode( $options ); if ( ! $product_id ) { return $this->error_response( 'invalid_product', __( 'Invalid product ID', 'ai-product-tools' ), 400 ); } if ( ! get_post( $product_id ) ) { return $this->error_response( 'rest_not_found', sprintf( /* translators: %d: product ID */ __( 'Product ID %d does not exist.', 'ai-product-tools' ), $product_id ), 404 ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return $this->error_response( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), 403 ); } $content_types = $this->extract_content_types( $options ); if ( empty( $content_types ) ) { return $this->error_response( 'no_content_types', __( 'No content types selected', 'ai-product-tools' ), 400 ); } $result = $this->generator->generateForProduct( $product_id, $content_types, $options ); if ( ! $result->success ) { $error_msg = ! empty( $result->errors ) ? implode( ', ', $result->errors ) : __( 'Generation failed', 'ai-product-tools' ); if ( $result->reviewStageFailed ) { return $this->error_response( 'review_stage_error', $error_msg, 409 ); } return $this->error_response( 'generation_failed', $error_msg, 500 ); } $response_data = $this->add_entitlement_signals( array( 'product_id' => $product_id, 'content' => $result->content, ), $options ); return $this->success_response( $response_data, __( 'Content generated successfully', 'ai-product-tools' ) ); } public function bulk_generate( WP_REST_Request $request ) { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { return $ai_gate; } $rate_check = $this->checkRateLimit( (int) get_current_user_id(), static::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $data = $request->get_json_params(); $product_ids = array_filter( array_map( 'absint', $data['productIds'] ?? array() ) ); $options = $this->sanitize_generation_options( $data['options'] ?? array() ); $options = $this->enforce_generation_mode( $options ); if ( empty( $product_ids ) ) { return $this->error_response( 'no_products', __( 'No products selected', 'ai-product-tools' ), 400 ); } $authorized_ids = array(); $denied_ids = array(); $not_found_ids = array(); foreach ( $product_ids as $product_id ) { if ( ! get_post( $product_id ) ) { $not_found_ids[] = (int) $product_id; continue; } if ( current_user_can( 'edit_post', $product_id ) ) { $authorized_ids[] = $product_id; continue; } $denied_ids[] = (int) $product_id; } if ( empty( $authorized_ids ) ) { if ( empty( $denied_ids ) && ! empty( $not_found_ids ) ) { return $this->error_response( 'rest_not_found', __( 'None of the selected products could be found.', 'ai-product-tools' ), 404 ); } return $this->error_response( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), 403 ); } $content_types = $this->extract_content_types( $options ); if ( empty( $content_types ) ) { return $this->error_response( 'no_content_types', __( 'No content types selected', 'ai-product-tools' ), 400 ); } $result = $this->generator->generate( $authorized_ids, $content_types, $options ); if ( (int) $result->successCount > 0 ) { $first_product_id = (int) ( $authorized_ids[ array_key_first( $authorized_ids ) ] ?? 0 ); \AIPT\Core\Services\UsageTracker::record_event( 'advanced_desc', 'generated', (int) $result->successCount, array( 'product_id' => $first_product_id ) ); if ( 'immediate' === ( $options['generationMode'] ?? 'client_preview' ) ) { \AIPT\Core\Services\UsageTracker::record_event( 'advanced_desc', 'applied', (int) $result->successCount, array( 'product_id' => $first_product_id ) ); } } $formatted_results = $this->format_bulk_results( $result, $content_types, $options ); foreach ( $denied_ids as $denied_id ) { foreach ( $content_types as $type ) { $formatted_results[] = array( 'product_id' => $denied_id, 'success' => false, 'type' => $this->map_type_to_db( $type ), 'status' => 'failed', 'api_error' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); } } foreach ( $not_found_ids as $not_found_id ) { foreach ( $content_types as $type ) { $formatted_results[] = array( 'product_id' => $not_found_id, 'success' => false, 'type' => $this->map_type_to_db( $type ), 'status' => 'failed', 'api_error' => sprintf( /* translators: %d: product ID */ __( 'Product ID %d does not exist.', 'ai-product-tools' ), $not_found_id ), ); } } $response_data = $this->add_entitlement_signals( array( 'success' => true, 'results' => $formatted_results, 'summary' => array( 'total' => count( $product_ids ), 'successful' => $result->successCount, 'failed' => $result->failureCount + count( $denied_ids ) + count( $not_found_ids ), 'processingTime' => round( $result->processingTime, 2 ), ), ), $options ); return new WP_REST_Response( $response_data, 200 ); } /** * Report paid behavior this run could not use. * * - applied_free_defaults: always empty for Description now that Example * Mode has merged into the single Custom prompt (2.8.1) — kept on the * response so it matches the other generators' contract. * - downgraded_mode (+ downgraded_mode_reason): server_review fell back to * client_preview (content-bank plan, todo 3). * * @param array $response_data Response payload. * @param array $options Enforced generation options. * @return array */ private function add_entitlement_signals( array $response_data, array $options ): array { $response_data['applied_free_defaults'] = array(); if ( ! empty( $options['downgraded_mode'] ) ) { $response_data['downgraded_mode'] = true; $response_data['downgraded_mode_reason'] = PlanDenial::reason( 'contentReview', PlanDenial::PLAN_BUSINESS ); } return $response_data; } private function enforce_generation_mode( array $options ): array { if ( 'server_review' === ( $options['generationMode'] ?? '' ) && ! apply_filters( 'aipt_content_review_enabled', false ) ) { $options['generationMode'] = 'client_preview'; $options['downgraded_mode'] = true; } return $options; } private function format_bulk_results( $result, array $content_types, array $options ): array { $formatted = array(); $success_status = ( isset( $options['generationMode'] ) && 'immediate' === $options['generationMode'] ) ? 'applied' : 'pending'; foreach ( $result->results as $product_id => $product_result ) { $blueprint_fields = ! empty( $product_result->blueprintInfo ) ? $product_result->blueprintInfo : BlueprintIntegration::advancedResponseFields(); $provider_error = $product_result->providerError ?? $blueprint_fields['providerError'] ?? null; $row_status = $product_result->status ?? $success_status; if ( $product_result->success ) { foreach ( $content_types as $type ) { $db_type = $this->map_type_to_db( $type ); if ( isset( $product_result->content[ $type ] ) ) { $formatted[] = array_merge( array( 'product_id' => $product_id, 'success' => true, 'type' => $db_type, 'text' => $product_result->content[ $type ], 'status' => $row_status, 'review_id' => $product_result->review_ids[ $type ] ?? null, ), $blueprint_fields ); continue; } if ( isset( $product_result->skipped ) && is_array( $product_result->skipped ) && in_array( $type, $product_result->skipped, true ) ) { $formatted[] = array_merge( array( 'product_id' => $product_id, 'success' => false, 'type' => $db_type, 'status' => 'skipped', 'api_error' => __( 'Kept the existing text: this field already has content and Fill empty only is on.', 'ai-product-tools' ), ), $blueprint_fields ); continue; } $per_type_error = ''; if ( is_array( $product_result->errors ) && isset( $product_result->errors[ $type ] ) && is_string( $product_result->errors[ $type ] ) && '' !== trim( $product_result->errors[ $type ] ) ) { $per_type_error = trim( $product_result->errors[ $type ] ); } if ( '' === $per_type_error ) { $per_type_error = __( 'Content type was not generated', 'ai-product-tools' ); } $formatted[] = array_merge( array( 'product_id' => $product_id, 'success' => false, 'type' => $db_type, 'status' => 'failed', 'api_error' => $per_type_error, ), $blueprint_fields, array( 'providerError' => $provider_error ) ); } } else { $raw_error = ''; if ( is_string( $product_result->errors ) && trim( $product_result->errors ) !== '' ) { $raw_error = $product_result->errors; } elseif ( is_wp_error( $product_result->errors ) ) { $raw_error = $product_result->errors->get_error_message(); } elseif ( is_iterable( $product_result->errors ) ) { foreach ( $product_result->errors as $candidate ) { if ( is_string( $candidate ) && trim( $candidate ) !== '' ) { $raw_error = $candidate; break; } if ( is_wp_error( $candidate ) ) { $candidate_message = $candidate->get_error_message(); if ( trim( $candidate_message ) !== '' ) { $raw_error = $candidate_message; break; } } } } if ( '' === $raw_error ) { $raw_error = __( 'Description generation failed', 'ai-product-tools' ); } foreach ( $content_types as $content_type ) { $db_type = $this->map_type_to_db( $content_type ); $formatted[] = array_merge( array( 'product_id' => $product_id, 'success' => false, 'type' => $db_type, 'api_error' => $raw_error, ), $blueprint_fields, array( 'providerError' => $provider_error ) ); } } } return $formatted; } private function map_type_to_db( string $type ): string { $mapping = array( 'short_description' => 'short', 'description' => 'full', 'tags' => 'tags', ); return $mapping[ $type ] ?? $type; } private function get_product_args(): array { return array( 'search' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'category' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'tag' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'status' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'stock_status' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'instock', 'outofstock', 'onbackorder' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'descriptionFilter' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'with_both', 'with_full', 'with_short', 'without_both', 'without_full', 'without_short', 'with_tags', 'without_tags', 'without_seo_meta', 'without_faq' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ( $value ) { return self::is_valid_enum_or_list( $value, array( 'with_both', 'with_full', 'with_short', 'without_both', 'without_full', 'without_short', 'with_tags', 'without_tags', 'without_seo_meta', 'without_faq' ) ); }, ), 'product_type' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'simple', 'variable', 'grouped', 'external' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ( $value ) { return self::is_valid_enum_or_list( $value, array( 'simple', 'variable', 'grouped', 'external' ) ); }, ), 'featured' => array( 'type' => 'boolean', 'required' => false, ), 'on_sale' => array( 'type' => 'boolean', 'required' => false, ), 'price_min' => array( 'type' => 'number', 'required' => false, 'sanitize_callback' => static function ( $value ) { return (float) $value; }, ), 'price_max' => array( 'type' => 'number', 'required' => false, 'sanitize_callback' => static function ( $value ) { return (float) $value; }, ), 'date_after' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'date_before' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'id_after' => array( 'type' => 'integer', 'required' => false, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'filter_logic' => array( 'type' => 'string', 'required' => false, 'default' => 'and', 'enum' => array( 'and', 'or' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'has_image' => array( 'type' => 'boolean', 'required' => false, ), 'has_gallery' => array( 'type' => 'boolean', 'required' => false, ), 'sku_status' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'has_sku', 'no_sku' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'catalog_visibility' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'all', 'visible', 'hidden' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'stock_qty_min' => array( 'type' => 'integer', 'required' => false, 'sanitize_callback' => 'absint', ), 'stock_qty_max' => array( 'type' => 'integer', 'required' => false, 'sanitize_callback' => 'absint', ), 'page' => array( 'type' => 'integer', 'required' => false, 'default' => 1, 'sanitize_callback' => 'absint', ), 'per_page' => array( 'type' => 'integer', 'required' => false, 'default' => 10, 'minimum' => 1, 'maximum' => 1000, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'orderby' => array( 'type' => 'string', 'required' => false, 'default' => 'date', 'sanitize_callback' => 'sanitize_text_field', ), 'order' => array( 'type' => 'string', 'required' => false, 'default' => 'DESC', 'enum' => array( 'ASC', 'DESC' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'ai_processed' => array( 'type' => 'string', 'required' => false, 'enum' => array( '', 'processed', 'unprocessed' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ( $value ) { return in_array( $value, array( '', 'processed', 'unprocessed' ), true ); }, ), 'ai_processed_type' => array( 'type' => 'string', 'required' => false, 'enum' => array( '', 'description', 'tags', 'seo_meta', 'faq', 'image_alt', 'title' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => function ( $value ) { return in_array( $value, array( '', 'description', 'tags', 'seo_meta', 'faq', 'image_alt', 'title' ), true ); }, ), ); } /** * Validates a REST arg that accepts either a single allowed value or a * comma-separated list / array of them (the multi-select convention * ProductFilterMapper::fromRequest() applies to descriptionFilter and * product_type) - every part must be a member of $allowed. An absent/empty * value is valid (the arg is optional). * * @param mixed $value Raw request value. * @param string[] $allowed Allowed single values. * @return bool */ private static function is_valid_enum_or_list( $value, array $allowed ): bool { if ( '' === $value || null === $value ) { return true; } $parts = is_array( $value ) ? $value : explode( ',', (string) $value ); foreach ( $parts as $part ) { if ( ! is_scalar( $part ) || ! in_array( trim( (string) $part ), $allowed, true ) ) { return false; } } return true; } }