buildFromWCProduct( $product, $attributes, $prefetched_attributes, $included_fields ); } return $this->buildFromRawData( $product, $attributes, $prefetched_attributes, $included_fields ); } /** * Build profiles for multiple products (batch). * * Primes the post meta cache for the batch and asks * `aipt_store_index_batch_attributes` for data fetched once for all of it. * * @param array $products Array of products or raw DB rows. * @param array $attributes Attribute slugs to include. * @param array $included_fields Fields to include in the profile. * @return array Map of product_id => AIProfile. */ public function buildBatch( array $products, array $attributes = array(), array $included_fields = array() ): array { $profiles = array(); if ( empty( $included_fields ) ) { $included_fields = ProfileManager::getDefaultIncludedFields(); } $included_fields = ProfileManager::ensureMandatoryFields( $included_fields ); $product_ids = array(); foreach ( $products as $product ) { if ( $product instanceof \WC_Product ) { $product_ids[] = $product->get_id(); } else { $product_ids[] = (int) $product->ID; } } if ( ! empty( $product_ids ) ) { update_meta_cache( 'post', $product_ids ); } /** * Filter the data fetched once for the whole batch, per product. * * The Premium build fetches the selected attributes here; each * product's entry reaches `aipt_store_index_profile`. * * @param array $batch_attributes Map of product ID => data. Default empty. * @param int[] $product_ids Product IDs of the batch. * @param array $attributes Attribute slugs selected for the index. * @param array $included_fields Fields included in the profiles. */ $batch_attributes = apply_filters( 'aipt_store_index_batch_attributes', array(), $product_ids, $attributes, $included_fields ); $batch_attributes = is_array( $batch_attributes ) ? $batch_attributes : array(); foreach ( $products as $product ) { $product_id = $product instanceof \WC_Product ? $product->get_id() : (int) $product->ID; $prefetched = $batch_attributes[ $product_id ] ?? array(); $profile = $this->build( $product, $attributes, is_array( $prefetched ) ? $prefetched : array(), $included_fields ); $profiles[ $profile['id'] ] = $profile; } return $profiles; } /** * Generate summary from product description. * * Prefers short description, falls back to truncated long description. * * @param string $short_description Short description. * @param string $long_description Long description. * @param int $max_length Maximum summary length (default 200). * @return string Truncated summary. */ public function generateSummary( string $short_description, string $long_description, int $max_length = self::MAX_SUMMARY_LENGTH ): string { $text = ! empty( $short_description ) ? $short_description : $long_description; $text = wp_strip_all_tags( $this->keepWordBoundaries( $text ) ); $text = html_entity_decode( $text, ENT_QUOTES, 'UTF-8' ); $text = preg_replace( '/\s+/', ' ', $text ); $text = trim( $text ); if ( mb_strlen( $text ) > $max_length ) { $text = mb_substr( $text, 0, $max_length ); if ( preg_match( '/^.*(?= )/su', $text, $before_last_space ) === 1 ) { $last_space = mb_strlen( $before_last_space[0] ); if ( $last_space > ( $max_length * 0.7 ) ) { $text = $before_last_space[0]; } } $text = rtrim( $text, '.,!? ' ) . '...'; } return $text; } /** * Build profile from WC_Product object. * * @param \WC_Product $product WooCommerce product object. * @param array $attributes Attribute slugs selected for the index. * @param array $prefetched_attributes This product's entry of `aipt_store_index_batch_attributes` (optional). * @param array $included_fields Fields to include in the profile. * @return array AIProfile structure. */ private function buildFromWCProduct( \WC_Product $product, array $attributes = array(), array $prefetched_attributes = array(), array $included_fields = array() ): array { $product_id = $product->get_id(); $profile = array( 'id' => $product_id, ); if ( in_array( 'title', $included_fields, true ) ) { $profile['title'] = $product->get_name(); } if ( in_array( 'short_description', $included_fields, true ) ) { $profile['short_description'] = wp_strip_all_tags( $this->keepWordBoundaries( $product->get_short_description() ) ); } if ( in_array( 'description', $included_fields, true ) ) { $profile['description'] = wp_strip_all_tags( $this->keepWordBoundaries( $product->get_description() ) ); } if ( in_array( 'price', $included_fields, true ) ) { $profile['price'] = (float) $product->get_price(); if ( $product->is_type( 'variable' ) ) { $price_fields = $this->derivePriceFieldsForVariable( $product ); $profile['regular_price'] = $price_fields['regular_price']; if ( isset( $price_fields['sale_price'] ) ) { $profile['sale_price'] = $price_fields['sale_price']; } if ( isset( $price_fields['sale_scope'] ) ) { $profile['sale_scope'] = $price_fields['sale_scope']; } if ( isset( $price_fields['sale_attribute'] ) ) { $profile['sale_attribute'] = $price_fields['sale_attribute']; } } elseif ( $product->is_type( 'grouped' ) ) { $price_fields = $this->derivePriceFieldsForGrouped( $product ); $profile['regular_price'] = $price_fields['regular_price']; if ( isset( $price_fields['sale_price'] ) ) { $profile['sale_price'] = $price_fields['sale_price']; } $profile['price_max'] = $price_fields['price_max']; $profile['grouped_children'] = $price_fields['children']; } else { $profile['regular_price'] = (float) $product->get_regular_price(); $sale_price = $product->get_sale_price(); if ( ! empty( $sale_price ) && $product->is_on_sale() ) { $profile['sale_price'] = (float) $sale_price; } } } if ( in_array( 'stock_status', $included_fields, true ) ) { $profile['stock_status'] = $product->get_stock_status(); } if ( in_array( 'categories', $included_fields, true ) ) { $profile['categories'] = $this->getProductCategoryIds( $product_id ); } if ( in_array( 'tags', $included_fields, true ) ) { $profile['tags'] = $this->getProductTagIds( $product_id ); } if ( in_array( 'short_description', $included_fields, true ) || in_array( 'description', $included_fields, true ) ) { $profile['summary'] = $this->generateSummary( $product->get_short_description(), $product->get_description() ); } $profile = array_merge( $profile, ProductRatings::forProduct( $product ) ); /** * Filter the AI profile before indexing. * * The Premium build adds the Business fields (sku, stock_quantity, * attributes) the profile includes. * * @param array $profile The generated profile. * @param int $product_id The product ID. * @param array $included_fields Fields included in this profile. * @param \WC_Product|object $product Product object or raw DB row. * @param array $attributes Attribute slugs selected for the index. * @param array $prefetched_attributes This product's entry of `aipt_store_index_batch_attributes`. */ return apply_filters( 'aipt_store_index_profile', $profile, $product_id, $included_fields, $product, $attributes, $prefetched_attributes ); } /** * A variable product's regular/sale price, read from its variations * ({@see ProductPrices::regularAndSale()}): the parent's own fields are * always empty. When the cheapest pair is a sale, also resolves whether * that sale covers every purchasable variation or only some of them, so * the prompt never implies a flat storewide discount for one that does * not share it. * * @param \WC_Product $product A variable product (is_type('variable') true). * @return array{regular_price: float, sale_price?: float, sale_scope?: string, sale_attribute?: string} */ private function derivePriceFieldsForVariable( \WC_Product $product ): array { $prices = ProductPrices::regularAndSale( $product ); $fields = array( 'regular_price' => '' !== $prices['regular'] ? (float) $prices['regular'] : 0.0, ); if ( '' !== $prices['sale'] ) { $fields['sale_price'] = (float) $prices['sale']; $scope = ProductPrices::variationSaleScope( $product ); if ( $scope['mixed'] ) { $fields['sale_scope'] = 'some'; if ( '' !== $scope['cheap_label'] ) { $fields['sale_attribute'] = $scope['cheap_label']; } } } return $fields; } /** * A grouped product's price range and composition, read from its * visible children ({@see ProductPrices::visibleGroupedChildren()}): * the parent itself has no price or child list a customer can act on * without this -- get_price() alone reports only the cheapest child's * price, understating what completing the set costs. * * @param \WC_Product $product A grouped product (is_type('grouped') true). * @return array{regular_price: float, sale_price?: float, price_max: float, children: string[]} */ private function derivePriceFieldsForGrouped( \WC_Product $product ): array { $prices = ProductPrices::regularAndSale( $product ); $fields = array( 'regular_price' => '' !== $prices['regular'] ? (float) $prices['regular'] : 0.0, 'price_max' => 0.0, 'children' => array(), ); if ( '' !== $prices['sale'] ) { $fields['sale_price'] = (float) $prices['sale']; } $max_price = null; foreach ( ProductPrices::visibleGroupedChildren( $product ) as $child ) { $fields['children'][] = $child->get_name(); $child_price = $child->get_price(); if ( '' === $child_price ) { continue; } $price_value = (float) $child_price; if ( null === $max_price || $price_value > $max_price ) { $max_price = $price_value; } } $fields['price_max'] = $max_price ?? $fields['regular_price']; return $fields; } /** * A space inserted at block-level tag boundaries before wp_strip_all_tags() * runs, so a multi-paragraph or list description reads as separate words * ("Sentence one. Item A Item B") instead of wp_strip_all_tags()'s own * bare concatenation ("Sentence one.Item AItem B"). A local step rather * than a shared cross-module helper, so this and the content-structure * engine's own equivalent fix stay independent of each other's change. * * @param string $html Raw HTML (possibly empty). * @return string The same markup with a trailing space after each * boundary, still to be passed through wp_strip_all_tags(). */ private function keepWordBoundaries( string $html ): string { if ( '' === $html ) { return $html; } return (string) preg_replace( '#(|)#i', '$1 ', $html ); } /** * Build profile from raw database row. * * Used for batch processing with direct SQL queries. * * @param object $row Raw database row object. * @param array $attributes Attribute slugs selected for the index. * @param array $prefetched_attributes This product's entry of `aipt_store_index_batch_attributes` (optional). * @param array $included_fields Fields to include in the profile. * @return array AIProfile structure. */ private function buildFromRawData( object $row, array $attributes = array(), array $prefetched_attributes = array(), array $included_fields = array() ): array { $product_id = (int) $row->ID; $profile = array( 'id' => $product_id, ); if ( in_array( 'title', $included_fields, true ) ) { $profile['title'] = $row->post_title; } if ( in_array( 'short_description', $included_fields, true ) ) { $profile['short_description'] = wp_strip_all_tags( $this->keepWordBoundaries( $row->post_excerpt ?? '' ) ); } if ( in_array( 'description', $included_fields, true ) ) { $profile['description'] = wp_strip_all_tags( $this->keepWordBoundaries( $row->post_content ?? '' ) ); } if ( in_array( 'price', $included_fields, true ) ) { $profile['price'] = isset( $row->_price ) ? (float) $row->_price : 0.0; if ( $this->isVariableProduct( $product_id ) ) { $wc_product = wc_get_product( $product_id ); $price_fields = $wc_product instanceof \WC_Product ? $this->derivePriceFieldsForVariable( $wc_product ) : array( 'regular_price' => 0.0 ); $profile['regular_price'] = $price_fields['regular_price']; if ( isset( $price_fields['sale_price'] ) ) { $profile['sale_price'] = $price_fields['sale_price']; } if ( isset( $price_fields['sale_scope'] ) ) { $profile['sale_scope'] = $price_fields['sale_scope']; } if ( isset( $price_fields['sale_attribute'] ) ) { $profile['sale_attribute'] = $price_fields['sale_attribute']; } } elseif ( $this->isGroupedProduct( $product_id ) ) { $wc_product = wc_get_product( $product_id ); $price_fields = $wc_product instanceof \WC_Product ? $this->derivePriceFieldsForGrouped( $wc_product ) : array( 'regular_price' => 0.0, 'price_max' => 0.0, 'children' => array(), ); $profile['regular_price'] = $price_fields['regular_price']; if ( isset( $price_fields['sale_price'] ) ) { $profile['sale_price'] = $price_fields['sale_price']; } $profile['price_max'] = $price_fields['price_max']; $profile['grouped_children'] = $price_fields['children']; } else { $regular_price = get_post_meta( $product_id, '_regular_price', true ); $sale_price = get_post_meta( $product_id, '_sale_price', true ); $profile['regular_price'] = ! empty( $regular_price ) ? (float) $regular_price : 0.0; if ( ! empty( $sale_price ) && (float) $sale_price === $profile['price'] ) { $profile['sale_price'] = (float) $sale_price; } } } if ( in_array( 'stock_status', $included_fields, true ) ) { $profile['stock_status'] = isset( $row->_stock_status ) ? $row->_stock_status : 'instock'; } if ( in_array( 'categories', $included_fields, true ) ) { $profile['categories'] = $this->getProductCategoryIds( $product_id ); } if ( in_array( 'tags', $included_fields, true ) ) { $profile['tags'] = $this->getProductTagIds( $product_id ); } if ( in_array( 'short_description', $included_fields, true ) || in_array( 'description', $included_fields, true ) ) { $profile['summary'] = $this->generateSummary( $row->post_excerpt ?? '', $row->post_content ?? '' ); } $profile = array_merge( $profile, ProductRatings::forProductId( $product_id ) ); /** * Filter the AI profile before indexing. * * The Premium build adds the Business fields (sku, stock_quantity, * attributes) the profile includes. * * @see buildFromWCProduct() for the parameters. */ return apply_filters( 'aipt_store_index_profile', $profile, $product_id, $included_fields, $row, $attributes, $prefetched_attributes ); } /** * Get category IDs for a product. * * @param int $product_id Product ID. * @return array Array of category term IDs. */ private function getProductCategoryIds( int $product_id ): array { $terms = get_the_terms( $product_id, 'product_cat' ); if ( is_wp_error( $terms ) || empty( $terms ) ) { return array(); } return array_map( function ( $term ) { return (int) $term->term_id; }, $terms ); } /** * Whether a product is a variable product, without loading the full * WC_Product object. buildFromRawData() otherwise works entirely from * the raw row and postmeta to avoid constructing a WC_Product per row * on large catalogs; this reads the `product_type` taxonomy the same * way WC_Product_Data_Store_CPT::get_product_type() does, so that cost * is paid only for the variable subset of a batch. * * @param int $product_id Product ID. * @return bool */ private function isVariableProduct( int $product_id ): bool { $terms = get_the_terms( $product_id, 'product_type' ); if ( is_wp_error( $terms ) || empty( $terms ) ) { return false; } foreach ( $terms as $term ) { if ( 'variable' === $term->slug ) { return true; } } return false; } /** * Whether a product is a grouped product, without loading the full * WC_Product object. Mirrors isVariableProduct() -- see its docblock for * why buildFromRawData() checks the taxonomy term first. * * @param int $product_id Product ID. * @return bool */ private function isGroupedProduct( int $product_id ): bool { $terms = get_the_terms( $product_id, 'product_type' ); if ( is_wp_error( $terms ) || empty( $terms ) ) { return false; } foreach ( $terms as $term ) { if ( 'grouped' === $term->slug ) { return true; } } return false; } /** * Get tag IDs for a product. * * @param int $product_id Product ID. * @return array Array of tag term IDs. */ private function getProductTagIds( int $product_id ): array { $terms = get_the_terms( $product_id, 'product_tag' ); if ( is_wp_error( $terms ) || empty( $terms ) ) { return array(); } return array_map( function ( $term ) { return (int) $term->term_id; }, $terms ); } /** * Map stock status to standardized values. * * @param string|null $status Raw stock status. * @return string Normalized stock status. */ public function normalizeStockStatus( ?string $status ): string { $valid_statuses = array( 'instock', 'outofstock', 'onbackorder' ); if ( $status && in_array( $status, $valid_statuses, true ) ) { return $status; } return 'instock'; } }