*/ private array $frontend_results_by_signature = []; /** * Constructor * * @param Settings|null $settings Optional; falls back to a fresh (statically cached) Settings. */ public function __construct( ?Settings $settings = null ) { $this->settings = $settings ?? new Settings(); parent::__construct( 'wc-product-search', 'Search WooCommerce products by keyword, name, SKU, category, or attributes. Returns compact product summaries (id, title, price, stock, image, type). Call this whenever a shopper asks about products. Pass an EMPTY query to list the store\'s available products (use for broad requests like "what do you have").' ); } /** * Define tool properties * * @return array */ protected function properties(): array { return [ new ToolProperty( name: 'query', type: PropertyType::STRING, description: 'Search keywords — product name, description, category, or attributes. Omit or pass an empty string to list the store\'s available products.', required: false ), new ToolProperty( name: 'category', type: PropertyType::STRING, description: 'Product category slug to filter by.', required: false ), new ToolProperty( name: 'min_price', type: PropertyType::NUMBER, description: 'Minimum price filter.', required: false ), new ToolProperty( name: 'max_price', type: PropertyType::NUMBER, description: 'Maximum price filter.', required: false ), new ToolProperty( name: 'per_page', type: PropertyType::NUMBER, description: 'Maximum number of products to return. The store caps this to its configured recommendation limit.', required: false ), ]; } /** * Execute the tool * * @param string|null $query Search keywords. NeuronAI passes null (not '') * when the model omits this optional property, so * the type must be nullable or the call TypeErrors. * @param string|null $category Product category slug to filter by. * @param float|null $min_price Minimum price filter. * @param float|null $max_price Maximum price filter. * @param int|null $per_page Maximum results. * @return array */ public function __invoke( ?string $query = '', ?string $category = null, ?float $min_price = null, ?float $max_price = null, ?int $per_page = 10 ): array { if ( ! function_exists( 'wc_get_products' ) ) { return [ 'error' => 'WooCommerce is not active.' ]; } // Catch \Throwable, not just \Exception — WC internals (get_available_variations) can raise Errors too. try { $sanitized_query = sanitize_text_field( (string) ( $query ?? '' ) ); // Merchant's configured limit is the ceiling; hard cap of 12 guards a misconfigured value. $recommended = (int) ( new Public_Agent_Settings( $this->settings ) ) ->integration( 'woocommerce', 'recommendedLimit', 3 ); $recommended = min( max( 1, $recommended ), 12 ); $limit = min( max( 1, $per_page ?? $recommended ), $recommended ); // Tell the model when its count was capped, so a short result isn't read as "the store only has N products". $clamp_note = ( null !== $per_page && $per_page > $limit ) ? sprintf( 'Requested %d results but the store limit is %d.', $per_page, $limit ) : ''; // Slugify to match WC term slugs (a display name like "Clothing" won't match) and reject unknown categories explicitly. $category_slug = ''; if ( ! empty( $category ) ) { $category_slug = sanitize_title( $category ); if ( ! term_exists( $category_slug, 'product_cat' ) ) { return [ 'error' => 'Category slug "' . $category_slug . '" was not found in this store. Try a different category or search without a category filter.' ]; } } // Non-positive prices mean "no filter"; an unsatisfiable range (min > max) is rejected explicitly rather than silently returning 0 products. $min_price = ( null !== $min_price && (float) $min_price > 0 ) ? (float) $min_price : null; $max_price = ( null !== $max_price && (float) $max_price > 0 ) ? (float) $max_price : null; if ( null !== $min_price && null !== $max_price && $min_price > $max_price ) { return [ 'error' => 'Price range is invalid: minimum (' . $min_price . ') exceeds maximum (' . $max_price . '). Swap them or remove one filter.' ]; } $cache_inputs = strtolower( $sanitized_query ) . '_' . $limit . '_' . $category_slug . '_' . ( $min_price ?? '' ) . '_' . ( $max_price ?? '' ); $signature = md5( $cache_inputs ); $cache_key = 'aisentic_wc_search_' . $signature; $cached = get_transient( $cache_key ); if ( false !== $cached ) { if ( '' !== $clamp_note ) { $cached['note'] = $clamp_note; } return $this->finalize_result( $cached ); } $args = [ 'limit' => $limit, 'status' => 'publish', 's' => $sanitized_query, 'orderby' => 'relevance', // Default has no visibility filter, which would leak 'hidden' products. 'visibility' => 'visible', ]; if ( '' !== $category_slug ) { $args['category'] = [ $category_slug ]; } if ( null !== $min_price || null !== $max_price ) { $meta_query = [ 'relation' => 'AND' ]; if ( null !== $min_price ) { $meta_query[] = [ 'key' => '_price', 'value' => (float) $min_price, 'compare' => '>=', 'type' => 'NUMERIC', ]; } if ( null !== $max_price ) { $meta_query[] = [ 'key' => '_price', 'value' => (float) $max_price, 'compare' => '<=', 'type' => 'NUMERIC', ]; } $args['meta_query'] = $meta_query; } $products = wc_get_products( $args ); $summaries = []; foreach ( $products as $product ) { $summaries[] = $this->format_product_summary( $product ); } $result = [ 'products' => $summaries, 'total' => count( $summaries ), 'query' => $sanitized_query, // Hint for which rich UI to render; lets future result shapes switch renderer. 'ui_hint' => 'product_carousel', // Keys the rich payload so multiple searches in one turn never cross results (query alone is ambiguous). 'signature' => $signature, ]; $configured_ttl = (int) ( new Public_Agent_Settings( $this->settings ) ) ->integration( 'woocommerce', 'searchCacheTtlSeconds', 300 ); // Floor at 60s: absint() would turn 0/negative into 0, and set_transient( ..., 0 ) means NO expiration. $ttl = max( 60, absint( apply_filters( 'aisentic_wc_search_cache_ttl', $configured_ttl ) ) ); // Never cache an empty result — would poison every retry within the TTL with a stale "no results" answer. if ( ! empty( $summaries ) ) { set_transient( $cache_key, $result, $ttl ); } // Applied after caching so this note doesn't stick to an entry shared across different requested counts. if ( '' !== $clamp_note ) { $result['note'] = $clamp_note; } return $this->finalize_result( $result ); } catch ( \Throwable $e ) { // Log the real cause for the operator; the model gets a generic non-retry message. Log::error( 'WC product search failed: ' . $e->getMessage() ); return [ 'error' => 'Product search is temporarily unavailable. Do not retry — tell the shopper you could not look that up right now.' ]; } } /** * Stash the rich result for the SSE layer; strip attributes/variations for the leaner agent-facing copy. * * @param array $result The full (rich) search result. * @return array The lean result to return to the agent. */ private function finalize_result( array $result ): array { $this->last_frontend_result = $result; if ( ! empty( $result['signature'] ) ) { $this->frontend_results_by_signature[ (string) $result['signature'] ] = $result; } if ( ! empty( $result['products'] ) && is_array( $result['products'] ) ) { $result['products'] = array_map( static function ( $product ) { if ( is_array( $product ) ) { unset( $product['available_attributes'], $product['variations'] ); } return $product; }, $result['products'] ); } return $result; } /** * Rich result of the last search, or null if none has run. * * @return array|null */ public function get_last_frontend_result(): ?array { return $this->last_frontend_result; } /** * Rich result for a specific search, matched by its input signature (query string alone is ambiguous when several ran in one turn). * * @param string $signature Signature from the tool result's `signature` field. * @return array|null Rich result, or null when no search with that signature ran. */ public function get_frontend_result( string $signature ): ?array { return $this->frontend_results_by_signature[ $signature ] ?? null; } /** * Format a product into a compact summary array * * @param \WC_Product $product The product. * @return array */ private function format_product_summary( \WC_Product $product ): array { $image_id = $product->get_image_id(); $image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' ) : ''; $summary = [ 'id' => $product->get_id(), 'title' => $product->get_title(), 'price_html' => $product->get_price_html(), 'regular_price' => $product->get_regular_price(), 'sale_price' => $product->get_sale_price(), 'on_sale' => $product->is_on_sale(), 'stock_status' => $product->get_stock_status(), 'in_stock' => $product->is_in_stock(), 'permalink' => $product->get_permalink(), 'image_url' => $image_url, 'short_attributes' => $this->format_attributes( $product ), 'type' => $product->get_type(), 'has_variations' => $product->is_type( 'variable' ), 'sku' => $product->get_sku(), 'short_description' => wp_trim_words( wp_strip_all_tags( (string) $product->get_short_description() ), 30, '…' ), ]; // Only variable products need attribute/variation data for the picker. if ( $product->is_type( 'variable' ) ) { $variation_data = $this->format_variations( $product ); $summary['available_attributes'] = $variation_data['available_attributes']; $summary['variations'] = $variation_data['variations']; } return $summary; } /** * Build selectable attributes and concrete variation combinations for a variable product. * * @param \WC_Product $product The variable product. * @return array{available_attributes: array, variations: array} */ private function format_variations( \WC_Product $product ): array { $empty = [ 'available_attributes' => [], 'variations' => [], ]; if ( ! $product instanceof \WC_Product_Variable ) { return $empty; } $available_attributes = []; foreach ( $product->get_variation_attributes() as $attribute_name => $option_values ) { $options = []; foreach ( (array) $option_values as $value ) { $value = (string) $value; if ( '' === $value ) { continue; } $options[] = [ 'value' => $value, 'label' => $this->attribute_option_label( (string) $attribute_name, $value ), ]; } if ( empty( $options ) ) { continue; } // Sanitize to match variation keys below (`attribute_` . sanitize_title( name )); otherwise custom attributes never match. $available_attributes[] = [ 'name' => sanitize_title( (string) $attribute_name ), 'label' => wc_attribute_label( (string) $attribute_name ), 'options' => $options, ]; } $variations = []; foreach ( $product->get_available_variations() as $variation ) { if ( empty( $variation['variation_id'] ) ) { continue; } // Strip the `attribute_` prefix to match `available_attributes` names. $attrs = []; foreach ( (array) ( $variation['attributes'] ?? [] ) as $key => $value ) { $attrs[ preg_replace( '/^attribute_/', '', (string) $key ) ] = (string) $value; } $variation_image = ''; if ( ! empty( $variation['image_id'] ) ) { $variation_image = (string) wp_get_attachment_image_url( (int) $variation['image_id'], 'woocommerce_thumbnail' ); } if ( '' === $variation_image && ! empty( $variation['image']['src'] ) ) { $variation_image = (string) $variation['image']['src']; } $variations[] = [ 'variation_id' => (int) $variation['variation_id'], 'attributes' => $attrs, 'price_html' => (string) ( $variation['price_html'] ?? '' ), 'image_url' => $variation_image, 'in_stock' => ! empty( $variation['is_in_stock'] ), ]; } return [ 'available_attributes' => $available_attributes, 'variations' => $variations, ]; } /** * Resolve a taxonomy term slug to its display name (e.g. "red" -> "Red"); custom attributes pass through. * * @param string $attribute_name Attribute name (e.g. `pa_color` or `Size`). * @param string $value Raw option value (term slug or literal). * @return string */ private function attribute_option_label( string $attribute_name, string $value ): string { if ( taxonomy_exists( $attribute_name ) ) { $term = get_term_by( 'slug', $value, $attribute_name ); if ( $term && ! is_wp_error( $term ) ) { return $term->name; } } return $value; } /** * Format product attributes as a string * * @param \WC_Product $product The product. * @return string|null */ private function format_attributes( \WC_Product $product ): ?string { $attributes = $product->get_attributes(); if ( empty( $attributes ) ) { return null; } $parts = []; foreach ( $attributes as $attribute ) { if ( ! $attribute instanceof \WC_Product_Attribute ) { continue; } // Taxonomy attributes store term IDs; resolve to names or the agent relays meaningless numbers. if ( $attribute->is_taxonomy() ) { $values = wc_get_product_terms( $product->get_id(), $attribute->get_name(), [ 'fields' => 'names' ] ); $label = wc_attribute_label( $attribute->get_name() ); } else { $values = $attribute->get_options(); $label = $attribute->get_name(); } if ( ! empty( $values ) ) { $parts[] = $label . ': ' . implode( ' | ', $values ); } } return ! empty( $parts ) ? implode( '; ', $parts ) : null; } }