get_products * POST product-editor/products/batch -> batch_save * POST product-editor/selection/resolve -> resolve_selection * GET product-editor/views -> get_views * POST product-editor/views -> save_view * DELETE product-editor/views/{id} -> delete_view * GET product-editor/prefs -> get_prefs * POST product-editor/prefs -> save_prefs * * @package AIPT\Api\ProductEditor * @since 2.6.5 */ namespace AIPT\Api\ProductEditor; defined( 'ABSPATH' ) || exit; use AIPT\Api\BulkGenerator\BaseBulkGeneratorController; use AIPT\Utils\ProductFilter\ProductFilterBuilder; use AIPT\Utils\ProductFilter\ProductFilterMapper; use WP_REST_Request; use WP_REST_Response; use WP_REST_Server; /** * AI Bulk Product Editor REST controller. * * @since 2.6.5 */ class ProductEditorController extends BaseBulkGeneratorController { /** * Rate-limit scope isolating the editor's batch-save window. */ protected const RATE_LIMIT_SCOPE = 'product_editor'; /** * Maximum patches accepted in a single batch save. */ private const MAX_PATCHES = 50; /** * Maximum product ids accepted by one hydrate request. Mirrors the client's * SELECTION_BATCH_SIZE so one batch of resolved allFiltered ids hydrates in a * single call; a larger request is rejected rather than silently fanned out. */ private const MAX_HYDRATE_IDS = 100; /** * Batch-save rate limit (requests per window) and window length (seconds). */ private const BATCH_RATE_LIMIT = 30; private const BATCH_RATE_WINDOW = 60; /** * Default selection-resolve page size when the client omits `limit`. */ private const DEFAULT_SELECTION_LIMIT = 200; /** * Upper bound on the client-requested selection-resolve page size. Guards * against an absurd `limit` before it reaches SelectionResolver (which caps * again at its own hard MAX_LIMIT). */ private const MAX_SELECTION_LIMIT = 1000; /** * Displayable-but-not-editable field ids the grid may request alongside the * registry's editable fields. Any `fields` value outside this set ∪ * FieldRegistry::editable_field_ids() is dropped. */ private const READ_ONLY_FIELD_IDS = array( 'product', 'productType', 'featuredImage', 'gallery', 'gallerySummary', 'missingAltCount', 'aiStatus', 'lastGenerated', 'reviewStatus', 'validationIssues', 'seoPlugin', ); /** * SEO field ids a save may carry even when the detected SEO plugin has no * meta key for one of them (The SEO Framework has no focus keyword). Such a * field reaches the registry and comes back as a per-field failure instead of * being dropped, which would report the product as saved and fail the whole * request when it is the only field. */ private const SEO_FIELD_IDS = array( 'seoTitle', 'metaDescription', 'focusKeyword' ); /** * @var FieldRegistry */ private $field_registry; /** * @var RowAssembler */ private $row_assembler; /** * @var BatchSaveService */ private $batch_save_service; /** * @var SelectionResolver */ private $selection_resolver; /** * @var ViewsService */ private $views_service; /** * @var PrefsService */ private $prefs_service; /** * Optional products-query override: ( array $params ) => builder result * array{products:array,total:int,total_pages:int}. Null uses the shared * ProductFilter pipeline. Injected in tests to avoid booting WP_Query. * * @var callable|null */ private $products_query; /** * All dependencies are optional and default to real, side-effect-free * services so production callers can `new ProductEditorController()`, while * tests inject doubles (mirrors BatchSaveService's constructor style). * * @param FieldRegistry|null $field_registry Field adapter registry. * @param RowAssembler|null $row_assembler Row hydrator. * @param BatchSaveService|null $batch_save_service Batch writer. * @param SelectionResolver|null $selection_resolver Keyset selection resolver. * @param ViewsService|null $views_service Saved-views persistence. * @param PrefsService|null $prefs_service Preferences persistence. * @param callable|null $products_query Optional products-query override. */ public function __construct( ?FieldRegistry $field_registry = null, ?RowAssembler $row_assembler = null, ?BatchSaveService $batch_save_service = null, ?SelectionResolver $selection_resolver = null, ?ViewsService $views_service = null, ?PrefsService $prefs_service = null, ?callable $products_query = null ) { $this->field_registry = $field_registry ?? new FieldRegistry(); $this->row_assembler = $row_assembler ?? new RowAssembler( $this->field_registry ); $this->batch_save_service = $batch_save_service ?? new BatchSaveService( $this->field_registry ); $this->selection_resolver = $selection_resolver ?? new SelectionResolver(); $this->views_service = $views_service ?? new ViewsService(); $this->prefs_service = $prefs_service ?? new PrefsService(); $this->products_query = $products_query; } /** * Register every editor route under the shared `aipt/v1` namespace. * * @return void */ public function register_routes(): void { register_rest_route( self::REST_NAMESPACE, '/product-editor/products', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_products' ), 'permission_callback' => array( $this, 'check_permissions' ), 'args' => $this->get_products_args(), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/products/batch', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'batch_save' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/products/hydrate', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'hydrate_products' ), 'permission_callback' => array( $this, 'check_permissions' ), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/selection/resolve', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'resolve_selection' ), 'permission_callback' => array( $this, 'check_permissions' ), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/views', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_views' ), 'permission_callback' => array( $this, 'check_permissions' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'save_view' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/views/(?P[a-zA-Z0-9._\-]+)', array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_view' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'id' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); register_rest_route( self::REST_NAMESPACE, '/product-editor/prefs', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_prefs' ), 'permission_callback' => array( $this, 'check_permissions' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'save_prefs' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ), ) ); } /** * Hydrate a page of editor rows for the requested fields + filter set. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error `{ rows, rowCount, pageCount }`, or an error. */ public function get_products( WP_REST_Request $request ) { $params = (array) $request->get_params(); $field_ids = $this->sanitize_field_ids( isset( $params['fields'] ) ? $params['fields'] : array() ); $builder_result = $this->run_products_query( $params ); if ( isset( $builder_result['error'] ) && is_string( $builder_result['error'] ) && '' !== $builder_result['error'] ) { return $this->error_response( 'aipt_product_query_failed', (string) $builder_result['error'], 500 ); } $assembled = $this->row_assembler->assemble_response( $builder_result, $field_ids ); return $this->success_response( array( 'rows' => ( isset( $assembled['rows'] ) && is_array( $assembled['rows'] ) ) ? $assembled['rows'] : array(), 'rowCount' => isset( $assembled['rowCount'] ) ? (int) $assembled['rowCount'] : 0, 'pageCount' => isset( $assembled['pageCount'] ) ? (int) $assembled['pageCount'] : 0, ) ); } /** * Hydrate editor rows for an explicit product-id list. * * Backs the client's fetch-on-miss during allFiltered / cross-page AI runs: * a generator needs a full row for a product outside the loaded page, so it * requests one here instead of failing. Reads only (same capability as * get_products); RowAssembler silently skips ids that are not products. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error `{ rows }`, or a 400 error. */ public function hydrate_products( WP_REST_Request $request ) { $body = $request->get_json_params(); if ( ! is_array( $body ) ) { $body = array(); } $ids = $this->sanitize_id_list( isset( $body['ids'] ) ? $body['ids'] : array() ); if ( empty( $ids ) ) { return $this->error_response( 'no_ids', __( 'No product ids were provided.', 'ai-product-tools' ), 400 ); } if ( count( $ids ) > self::MAX_HYDRATE_IDS ) { return $this->error_response( 'too_many_ids', sprintf( /* translators: %d: maximum number of ids allowed per hydrate request. */ __( 'A hydrate request may contain at most %d ids.', 'ai-product-tools' ), self::MAX_HYDRATE_IDS ), 400 ); } $field_ids = $this->sanitize_field_ids( isset( $body['fields'] ) ? $body['fields'] : array() ); return $this->success_response( array( 'rows' => $this->row_assembler->assemble_rows( $ids, $field_ids ), ) ); } /** * Persist a batch of per-product field patches. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error Per-product results envelope, or a 400/429 error. */ public function batch_save( WP_REST_Request $request ) { $body = $request->get_json_params(); if ( ! is_array( $body ) ) { $body = array(); } $raw_patches = ( isset( $body['patches'] ) && is_array( $body['patches'] ) ) ? $body['patches'] : array(); if ( empty( $raw_patches ) ) { return $this->error_response( 'no_patches', __( 'No patches were provided.', 'ai-product-tools' ), 400 ); } if ( count( $raw_patches ) > self::MAX_PATCHES ) { return $this->error_response( 'too_many_patches', sprintf( /* translators: %d: maximum number of patches allowed per batch. */ __( 'A batch may contain at most %d patches.', 'ai-product-tools' ), self::MAX_PATCHES ), 400 ); } $allowed_fields = array_values( array_unique( array_merge( $this->field_registry->editable_field_ids(), self::SEO_FIELD_IDS ) ) ); $patches = array(); foreach ( $raw_patches as $raw_patch ) { $patch = $this->sanitize_patch( is_array( $raw_patch ) ? $raw_patch : array(), $allowed_fields ); if ( null === $patch ) { return $this->error_response( 'invalid_patch', __( 'Each patch requires a valid product id and at least one editable field.', 'ai-product-tools' ), 400 ); } $patches[] = $patch; } $user_id = (int) get_current_user_id(); $rate_check = $this->checkRateLimit( $user_id, static::RATE_LIMIT_SCOPE, self::BATCH_RATE_LIMIT, self::BATCH_RATE_WINDOW ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $force = ! empty( $body['force'] ); $result = $this->batch_save_service->save_patches( $patches, $force, $user_id ); return $this->success_response( $result ); } /** * Resolve one keyset page of an `allFiltered` selection into product ids. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error `{ ids, nextCursor, total }`, or a 400 error. */ public function resolve_selection( WP_REST_Request $request ) { $body = $request->get_json_params(); if ( ! is_array( $body ) ) { $body = array(); } $filters = ( isset( $body['filters'] ) && is_array( $body['filters'] ) ) ? $body['filters'] : array(); $filters = PrefsService::sanitize_filters( $filters ); $negative_probe = new ProductFilterBuilder(); ProductFilterMapper::applyToBuilder( $negative_probe, ProductFilterMapper::fromRequest( $filters ) ); if ( $negative_probe->hasNegativeFilters() || $negative_probe->hasContentFilters() ) { return $this->error_response( 'aipt_selection_exclusion_filter_unsupported', __( 'Select all is unavailable while an exclusion or content filter (e.g. no image, no tags, or a description/content filter) is active. Refine the filter or select rows individually.', 'ai-product-tools' ), 400 ); } $excluded_ids = $this->sanitize_id_list( isset( $body['excludedIds'] ) ? $body['excludedIds'] : array() ); $cursor = isset( $body['cursor'] ) ? absint( $body['cursor'] ) : 0; $limit_raw = isset( $body['limit'] ) ? absint( $body['limit'] ) : self::DEFAULT_SELECTION_LIMIT; $limit = 0 === $limit_raw ? self::DEFAULT_SELECTION_LIMIT : min( $limit_raw, self::MAX_SELECTION_LIMIT ); $result = $this->selection_resolver->resolve( $filters, $excluded_ids, $cursor, $limit ); $next_cursor = ( isset( $result['next_cursor'] ) && null !== $result['next_cursor'] ) ? (int) $result['next_cursor'] : null; return $this->success_response( array( 'ids' => ( isset( $result['ids'] ) && is_array( $result['ids'] ) ) ? array_map( 'intval', $result['ids'] ) : array(), 'nextCursor' => $next_cursor, 'total' => isset( $result['total'] ) ? (int) $result['total'] : 0, ) ); } /** * List the current user's saved editor views. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response A list of saved views. */ public function get_views( WP_REST_Request $request ): WP_REST_Response { unset( $request ); $views = $this->views_service->get_views( (int) get_current_user_id() ); return $this->success_response( array_values( $views ) ); } /** * Create or update a saved editor view. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error The persisted view, or a 400 error. */ public function save_view( WP_REST_Request $request ) { $body = $request->get_json_params(); if ( ! is_array( $body ) ) { $body = array(); } $result = $this->views_service->save_view( (int) get_current_user_id(), $body ); if ( empty( $result['success'] ) ) { $message = ( isset( $result['message'] ) && '' !== (string) $result['message'] ) ? (string) $result['message'] : __( 'The view could not be saved.', 'ai-product-tools' ); return $this->error_response( 'view_save_failed', $message, 400 ); } return $this->success_response( is_array( $result['view'] ) ? $result['view'] : array() ); } /** * Delete a saved editor view by its path-param id. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error Success envelope, or a 400/404 error. */ public function delete_view( WP_REST_Request $request ) { $view_id = sanitize_text_field( (string) $request->get_param( 'id' ) ); if ( '' === $view_id ) { return $this->error_response( 'invalid_view_id', __( 'A valid view id is required.', 'ai-product-tools' ), 400 ); } $deleted = $this->views_service->delete_view( (int) get_current_user_id(), $view_id ); if ( ! $deleted ) { return $this->error_response( 'view_not_found', __( 'The requested view was not found.', 'ai-product-tools' ), 404 ); } return $this->success_response( array() ); } /** * Read the current user's persisted editor preferences. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response The saved preferences (empty when unset). */ public function get_prefs( WP_REST_Request $request ): WP_REST_Response { unset( $request ); $prefs = $this->prefs_service->get_prefs( (int) get_current_user_id() ); return $this->success_response( $prefs ); } /** * Persist the current user's editor preferences. * * @param WP_REST_Request $request The REST request. * @return WP_REST_Response|\WP_Error Success envelope, or a 400 error. */ public function save_prefs( WP_REST_Request $request ) { $body = $request->get_json_params(); if ( ! is_array( $body ) ) { $body = array(); } $saved = $this->prefs_service->save_prefs( (int) get_current_user_id(), $body ); if ( ! $saved ) { return $this->error_response( 'prefs_save_failed', __( 'Your preferences could not be saved.', 'ai-product-tools' ), 400 ); } return $this->success_response( array() ); } /** * Run the products query, mapping the request through the shared * ProductFilter pipeline unless an override callable was injected. * * @param array $params Raw request params (filter grammar + pagination). * @return array Builder result `{ products, total, total_pages }`. */ private function run_products_query( array $params ): array { if ( isset( $params['orderby'] ) && 'price' === $params['orderby'] ) { $params['orderby'] = 'regular-price'; } if ( null !== $this->products_query ) { return (array) call_user_func( $this->products_query, $params ); } $mapped = ProductFilterMapper::fromRequest( $params ); $builder = new ProductFilterBuilder(); ProductFilterMapper::applyToBuilder( $builder, $mapped ); return (array) $builder->getProducts(); } /** * Parse the `fields` CSV (or array) and drop anything outside the allow-list * of editable + read-only field ids, preserving request order. * * @param mixed $raw CSV string or array of field ids. * @return array Allow-listed, de-duplicated field ids. */ private function sanitize_field_ids( $raw ): array { $candidates = is_array( $raw ) ? $raw : explode( ',', (string) $raw ); $allowed = $this->allowed_field_ids(); $result = array(); foreach ( $candidates as $candidate ) { if ( ! is_string( $candidate ) && ! is_numeric( $candidate ) ) { continue; } $field = sanitize_text_field( trim( (string) $candidate ) ); if ( '' === $field ) { continue; } if ( in_array( $field, $allowed, true ) && ! in_array( $field, $result, true ) ) { $result[] = $field; } } return $result; } /** * The complete set of requestable field ids: registry-editable ∪ read-only. * * @return array */ private function allowed_field_ids(): array { return array_values( array_unique( array_merge( $this->field_registry->editable_field_ids(), self::READ_ONLY_FIELD_IDS ) ) ); } /** * Sanitize one batch patch: absint id (> 0) + non-empty allow-listed fields. * * @param array $patch Raw patch payload. * @param array $allowed_fields Editable field ids. * @return array{id:int,token:string,fields:array}|null Sanitized patch, or null when invalid. */ private function sanitize_patch( array $patch, array $allowed_fields ): ?array { $id = isset( $patch['id'] ) ? absint( $patch['id'] ) : 0; if ( $id <= 0 ) { return null; } $raw_fields = ( isset( $patch['fields'] ) && is_array( $patch['fields'] ) ) ? $patch['fields'] : array(); $fields = array(); foreach ( $raw_fields as $field_id => $value ) { if ( is_string( $field_id ) && in_array( $field_id, $allowed_fields, true ) ) { $fields[ $field_id ] = $value; } } if ( empty( $fields ) ) { return null; } $raw_ai_fields = ( isset( $patch['aiFields'] ) && is_array( $patch['aiFields'] ) ) ? $patch['aiFields'] : array(); $ai_fields = array(); foreach ( $raw_ai_fields as $field_id ) { if ( is_string( $field_id ) && in_array( $field_id, $allowed_fields, true ) && array_key_exists( $field_id, $fields ) ) { $ai_fields[] = $field_id; } } $sanitized = array( 'id' => $id, 'token' => isset( $patch['token'] ) ? (string) $patch['token'] : '', 'fields' => $fields, ); if ( ! empty( $ai_fields ) ) { $sanitized['aiFields'] = array_values( array_unique( $ai_fields ) ); } return $sanitized; } /** * Coerce a raw id list to unique positive ints (absint, drop 0/negatives). * * @param mixed $raw Raw id list. * @return array */ private function sanitize_id_list( $raw ): array { $ids = array(); if ( ! is_array( $raw ) ) { return $ids; } foreach ( $raw as $value ) { $id = absint( $value ); if ( $id > 0 && ! in_array( $id, $ids, true ) ) { $ids[] = $id; } } return $ids; } /** * REST argument schema for the products listing (mirrors the bulk-generator * filter grammar; `per_page` is capped at 1000 to match the footer pager's * custom-input ceiling). * * @return array */ private function get_products_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', ), 'status' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'descriptionFilter' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'product_type' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'sku_status' => array( 'type' => 'string', 'required' => false, 'enum' => array( 'has_sku', 'no_sku' ), 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), 'featured' => array( 'type' => 'boolean', 'required' => false, ), 'on_sale' => array( 'type' => 'boolean', 'required' => false, ), 'has_image' => array( 'type' => 'boolean', 'required' => false, ), 'has_gallery' => array( 'type' => 'boolean', 'required' => false, ), 'filter_logic' => array( 'type' => 'string', 'required' => false, 'default' => 'and', 'enum' => array( 'and', 'or' ), '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' => 'rest_validate_request_arg', ), 'ai_processed_type' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), 'page' => array( 'type' => 'integer', 'required' => false, 'default' => 1, 'sanitize_callback' => 'absint', ), 'per_page' => array( 'type' => 'integer', 'required' => false, 'default' => 25, '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', ), 'fields' => array( 'type' => 'string', 'required' => false, 'sanitize_callback' => 'sanitize_text_field', ), ); } }