'POST', 'callback' => array( __CLASS__, 'resolve' ), 'permission_callback' => array( __CLASS__, 'check_permissions' ), ), ) ); } /** * POST /automation-jobs/resolve-blueprint-scope * body: `{ generator: string, productFilter: object }` * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function resolve( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return new WP_Error( 'aipt_automation_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $filter = isset( $body['productFilter'] ) && is_array( $body['productFilter'] ) ? $body['productFilter'] : array(); if ( ! empty( JobEntitlementGuard::unhonoredFilterKeys( $filter ) ) ) { return new WP_REST_Response( array( 'success' => true, 'data' => array( 'groups' => array(), 'total' => 0, 'sampleSize' => 0, 'truncated' => false, ), ) ); } $matches = static::matchingProductIds( $filter, self::SAMPLE_CAP ); $result = static::scope()->resolveForProducts( $generator, $matches['ids'] ); $result['total'] = $matches['total']; $result['sampleSize'] = count( $matches['ids'] ); $result['truncated'] = $result['truncated'] || $matches['truncated']; return new WP_REST_Response( array( 'success' => true, 'data' => $result ) ); } /** * Tool-level write permission: `manage_woocommerce` plus a valid REST * nonce, matching every other Automation Jobs write route * (AutomationJobsController::check_permissions_write()) — this route * accepts an arbitrary, not-yet-saved filter and runs several queries * against it, so it needs the same CSRF protection as a write even * though it changes nothing. * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_permissions( WP_REST_Request $request ) { if ( ! current_user_can( 'manage_woocommerce' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to manage automation jobs.', 'ai-product-tools' ), array( 'status' => 403 ) ); } if ( \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } $nonce = is_string( $nonce ) ? $nonce : ''; if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new WP_Error( 'rest_invalid_nonce', __( 'Invalid or missing security nonce.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } return true; } /** * Resolve a job's own product filter into matching product ids, bounded, * plus the TRUE total match count. Mirrors the same filter dimensions * (and the same Free/Business category/tag/stock/product status gate, * `aipt_automation_filter_options`) as * AutomationJobsController::calculateTotalProducts() — the wizard's own * "N products match" estimate — so the two numbers never disagree for * the same filter. * * Content-based filters (e.g. "missing a description") are deliberately * not reproduced here: this route is a Blueprint-resolution PREVIEW, not * the job's actual run, and omitting them only ever narrows the preview * toward real matches, never claims the wrong Blueprint for one. * * @param array $filter Raw product filter, same shape the wizard already builds. * @param int $limit Hard cap on returned ids. * @return array{ids:int[], total:int, truncated:bool} */ private static function matchingProductIds( array $filter, int $limit ): array { global $wpdb; $categories = ! empty( $filter['categories'] ) && is_array( $filter['categories'] ) ? array_values( array_filter( array_map( 'absint', $filter['categories'] ) ) ) : array(); $tags = ! empty( $filter['tags'] ) && is_array( $filter['tags'] ) ? array_values( array_filter( array_map( 'absint', $filter['tags'] ) ) ) : array(); $stock_status = isset( $filter['stockStatus'] ) && in_array( $filter['stockStatus'], array( 'instock', 'outofstock', 'onbackorder' ), true ) ? (string) $filter['stockStatus'] : 'all'; $product_status = JobEntitlementGuard::productStatus( $filter ); $granted = apply_filters( 'aipt_automation_filter_options', array( 'categories' => array(), 'tags' => array(), 'stock_status' => 'all', 'product_status' => JobEntitlementGuard::DEFAULT_PRODUCT_STATUS ), $categories, $tags, $stock_status, $product_status ); $granted = is_array( $granted ) ? $granted : array(); $categories = is_array( $granted['categories'] ?? null ) ? array_map( 'absint', $granted['categories'] ) : array(); $tags = is_array( $granted['tags'] ?? null ) ? array_map( 'absint', $granted['tags'] ) : array(); $stock_status = is_string( $granted['stock_status'] ?? null ) ? $granted['stock_status'] : 'all'; $product_status = JobEntitlementGuard::productStatus( array( 'status' => $granted['product_status'] ?? null ) ); $include_ids = self::idList( $filter['includeIds'] ?? null ); $exclude_ids = self::idList( $filter['excludeIds'] ?? null ); $min_price = isset( $filter['priceRange']['min'] ) && '' !== $filter['priceRange']['min'] && is_numeric( $filter['priceRange']['min'] ) ? (float) $filter['priceRange']['min'] : null; $max_price = isset( $filter['priceRange']['max'] ) && '' !== $filter['priceRange']['max'] && is_numeric( $filter['priceRange']['max'] ) ? (float) $filter['priceRange']['max'] : null; $where = "p.post_type = 'product' AND p.post_status = %s"; $params = array( $product_status ); $paid_conditions = PaidFilterConditions::forGranted( $categories, $tags, $stock_status ); foreach ( $paid_conditions['where'] as $condition ) { $where .= ' AND ' . $condition; } $params = array_merge( $params, $paid_conditions['params'] ); if ( null !== $min_price || null !== $max_price ) { $price_conditions = array(); if ( null !== $min_price ) { $price_conditions[] = 'CAST(pm.meta_value AS DECIMAL(10,2)) >= %f'; $params[] = $min_price; } if ( null !== $max_price ) { $price_conditions[] = 'CAST(pm.meta_value AS DECIMAL(10,2)) <= %f'; $params[] = $max_price; } $where .= " AND p.ID IN ( SELECT post_id FROM {$wpdb->postmeta} pm WHERE pm.meta_key = '_price' AND " . implode( ' AND ', $price_conditions ) . ' )'; } if ( ! empty( $include_ids ) ) { $placeholders = implode( ',', array_fill( 0, count( $include_ids ), '%d' ) ); $where .= " AND p.ID IN ({$placeholders})"; $params = array_merge( $params, $include_ids ); } if ( ! empty( $exclude_ids ) ) { $placeholders = implode( ',', array_fill( 0, count( $exclude_ids ), '%d' ) ); $where .= " AND p.ID NOT IN ({$placeholders})"; $params = array_merge( $params, $exclude_ids ); } $select_sql = "SELECT DISTINCT p.ID FROM {$wpdb->posts} p WHERE {$where} ORDER BY p.ID ASC LIMIT " . ( $limit + 1 ); $rows = empty( $params ) ? $wpdb->get_col( $select_sql ) : $wpdb->get_col( $wpdb->prepare( $select_sql, $params ) ); $ids = array_map( 'intval', (array) $rows ); if ( count( $ids ) <= $limit ) { return array( 'ids' => $ids, 'total' => count( $ids ), 'truncated' => false ); } $ids = array_slice( $ids, 0, $limit ); $count_sql = "SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p WHERE {$where}"; $total = empty( $params ) ? (int) $wpdb->get_var( $count_sql ) : (int) $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) ); return array( 'ids' => $ids, 'total' => $total, 'truncated' => true ); } /** * Normalize a request's `includeIds`/`excludeIds` value (comma-separated * string or array) into a list of positive ints, mirroring * AutomationJobsController::calculateTotalProducts()'s own handling of * the same two fields. * * @param mixed $raw Raw includeIds/excludeIds value. * @return int[] */ private static function idList( $raw ): array { if ( is_array( $raw ) ) { return array_values( array_filter( array_map( 'absint', $raw ) ) ); } if ( is_string( $raw ) && '' !== $raw ) { return array_values( array_filter( array_map( 'absint', array_map( 'trim', explode( ',', $raw ) ) ) ) ); } return array(); } /** * @return AssignmentScope */ protected static function scope(): AssignmentScope { return new AssignmentScope(); } }