# Search

Product search goes through `SyncShop\Modules\Catalog\Contracts\ProductSearch`. Two drivers ship: PostgreSQL, the only
engine a small shop needs and the fallback for every shop, and Typesense. A Meilisearch driver can come behind the same
contract.

```php
$result = resolve(ProductSearch::class)->search(new SearchQuery('cafea macinata', categoryId: $id, brandIds: [3], page: 1));
$result->productIds; // best match first
$result->total;
$result->exact;      // the first hit matched a SKU or barcode exactly
```

The storefront sees products on sale only (`activeOnly: true`, the default). Prices, stock and visibility for a buyer
are applied to the hit list afterwards, so the index doesn't grow with every price list.

## How the PostgreSQL driver matches

1. **Exact codes first.** A query that is a product's SKU, barcode or manufacturer part number, whatever its case,
   puts that product first.
2. **Full text.** The `romanian` stemmer over unaccented text: diacritics fold, comma-below and cedilla forms alike
   (ș/ş, ț/ţ), so `macinata` finds *măcinată* and `ceasca` finds *ceașca*. Names weigh most, then the brand and codes,
   then the short description, then the description.
3. **Typos.** When full text finds nothing, `pg_trgm` word similarity compares the query with the closest run of words
   in the name, so `zacusa` still finds *Zacuscă*, and so does `cafeaua`, which the stemmer reduces differently from
   *cafea*.

Filters: a category includes everything below it (the product's category paths are `ltree`), and brands.

## Keeping the index in step

- **Outbox.** Saving or deleting a product or a variant, renaming a brand, moving a category and changing a product's
  categories each write a `search_outbox` row in the same transaction as the change. A queued job sends the rows once
  the change commits. When the engine fails, the row stays with the error and a growing delay, so no update is lost.
  `search:process-outbox` runs every minute as a safety net.
- **Reconciliation.** `search:reconcile` runs at 03:30 and compares every product with its index entry by checksum.
  Drifted entries go back through the outbox, and the run is marked failed so the scheduler shows that the index had
  fallen behind.
- **Rebuild.** `php artisan search:rebuild` rebuilds the whole index inside one transaction, so searches keep using
  the old index until the new one is complete.

## Typesense

Typesense is set up on **Settings → Search** (`Catalog\Settings\SearchSettings`, group `search`, API key encrypted),
not in `.env`. `SEARCH_DRIVER` and `TYPESENSE_NODES` / `TYPESENSE_API_KEY` / `TYPESENSE_COLLECTION` /
`TYPESENSE_TIMEOUT` only seed the settings when their migration first runs, so an automated install (the demo) can
start on Typesense; after that the admin screen is the source.

- **Choosing the engine.** `SearchEngines::current()` backs the `ProductSearch` binding. It returns PostgreSQL unless
  Typesense is chosen *and* its index is built for the connection now set up: `built_for` holds the
  `TypesenseConnection::fingerprint()` (nodes and alias, not the key) of the last complete build. Saving a new
  cluster or alias queues `RebuildSearch`; `RebuildSearchIndex` fills the new collection, sets `built_for` only if the
  settings did not change meanwhile, and sends products whose entry drifted during the build through the outbox.
  Switching to PostgreSQL clears `built_for`, so going back rebuilds from scratch. Before the settings exist (fresh
  install), PostgreSQL answers.
- **Connection test.** `TestSearchConnection` checks `/health` on each node on its own (a node down while others
  answer is a warning), then the key, creating a collection, indexing, searching and an alias, and always removes its
  `<alias>_check_<random>` collection. The result is a `Platform\Data\CheckReport`, rendered by `<x-check-report>`
  like the storage test. Node addresses are usually on a private network, so they are not restricted to public
  addresses; instead the server's own answers are never shown (`SearchErrors` maps failures to fixed messages),
  the client never follows redirects, the test route is throttled (10 a minute), and the saved API key is reused only
  when the typed nodes are the saved ones, so it cannot be sent to a new address.
- **Failover.** `FailoverProductSearch` wraps Typesense and PostgreSQL. Every change is indexed in PostgreSQL first, so
  the fallback is never stale. A query that Typesense fails is answered by PostgreSQL; after three failures within a
  minute the circuit breaker (in the shared cache) sends every query to PostgreSQL for 30 seconds, then tries
  Typesense again. While it is open, outbox rows wait and retry instead of timing out one by one. Timeouts are short
  (2 s by default, set on the screen) so a slow engine never holds up a page.
- **Zero-downtime rebuild.** Searches go through an alias. `search:rebuild` (or the screen's button) fills a new collection
  (`<alias>_<timestamp>_<random>`), swaps the alias to it when complete, then deletes the old collections. A rebuild
  that fails deletes its half-built collection and leaves the alias alone.
- **Matching.** The same order as PostgreSQL: an exact SKU, barcode or part number first (a `codes` filter), then
  Typesense's ranking with typo tolerance and prefixes over the name, its folded form (`ș`/`ş` → `s`), the brand, the
  codes and the descriptions. Category filters match the category and everything below it, because each document
  carries its categories' paths and the paths above them.
- **Reconciliation.** `search:reconcile` compares both indexes with the products by checksum (`ProductDocument`
  builds the document and the checksum for both engines).

Tests play the Typesense server with a Guzzle handler (`Tests\Fixtures\FakeTypesense`, passed to `SearchEngines` as its
HTTP client), so they run without one. To try it against a real server locally: `brew install
typesense/tap/typesense-server`, start it with an API key, and fill in Settings → Search with `http://127.0.0.1:8108`.

## Semantic search

- `Contracts\AssistedSearch` (`Search\AiAssistedSearch`):
  - `understand(text)` returns a `Data\SearchIntent`: text, min/max price in bani, brand ids, vector, `understood`. It
    never throws.
  - Understanding runs through `AiFeature::SearchIntent` (a structured answer with keywords, min_price, max_price and
    brand, validated; the brand matched by `Taxonomy::brandNamed()`). Only for `readsLikeASentence()` searches, after
    `screen()` removes e-mails and long digit runs.
  - The vector runs through `AiFeature::SearchEmbeddings` (`Assistant::embed()`, primary route only), only when the
    current engine is Typesense.
  - Only the screened text is sent or cached; the search runs on the original unless the model understood it.
  - Both are cached a day per screened search and model; a partial failure is not cached.
  - `AiFeature::isPublic()` features need a daily budget to be switched on. Calls made for a shopper's request pass `forShopper: true`: they skip the budget lock (never waiting on another call) and count against a shop-wide cap of `GatedAssistant::SHOPPER_CALLS_PER_MINUTE` per feature. Batch work (`search:embed`) keeps the locked path.
- `Data\SearchQuery` takes `minPrice`, `maxPrice` and `vector`. `ProductDocument` carries `minPrice` (the lowest
  active variant price) in `product_search.min_price` and Typesense's `min_price`, plus `embeddingText` /
  `embeddingChecksum()`.
- `Search\ProductVectors` handles the `product_embeddings` table (product, model, dimensions, checksum, vector jsonb),
  for the model `Assistant::embeddingModel()` names. Storing one model's vector drops the others.
- `Search\EmbedProducts` (`search:embed`, every 15 min) embeds active products whose `embeddingChecksum()` differs,
  64 per call, then pushes them to the outbox. It does nothing unless the feature is available and Typesense is current.
- Typesense:
  - The schema gets `embedding` (`float[]`, `num_dim` from the stored vectors) when known. `ensureVectorField()` adds
    or replaces it on the live collection (PATCH) when a document brings a vector of another length.
  - A query with a vector of the right length adds `vector_query: embedding:([...], k: 200, alpha: 0.3)` and drops
    `sort_by`, so Typesense fuses the text and vector rankings.
- Storefront: `SearchController` asks `understand()` unless `exact=1` or the visitor's `search-ai:<ip>` limit (10 a minute) is spent, shows the understood chips with a link to the
  exact search, and repeats the search as typed when the understood one finds nothing.

Tests: `tests/Feature/Catalog/SemanticSearchTest.php`.

## Related products

- `product_relations` (product, kind, related product, position, score) holds, per product, the similar products
  (`RelationKind::Similar`, up to 8) and those bought together (`RelationKind::Together`, up to 6), replaced every
  night by `Related\RelateProducts` (`catalog:relate`, 03:50).
- Similar: when the current engine is a `Search\FindsSimilar` (Typesense, through `FailoverProductSearch` while it is
  healthy) and the product has a vector for the current model, `similar()` asks Typesense for its nearest neighbours by
  its own stored vector (`vector_query: embedding:([], id: <id>, k: n+1)`, active and public only, itself excluded): no
  AI call. Otherwise, or when the engine fails or finds nothing, the rules: products sharing most categories
  (`category_product`), the same brand first, then the closest `min_price`.
- Bought together: `Orders\Contracts\CoPurchases::pairs()` counts, for each ordered pair of products in the same
  order in the last 365 days, the distinct buyers (lower-cased e-mail), leaving out gift lines and cancelled or
  returned orders; only pairs with at least two buyers come back.
- Reading: `Catalog\Contracts\RelatedProducts` (`of()`, `forBasket()`) returns only products that are active and
  public (`product_search`). `Storefront\Support\Suggestions` turns them into cards: bought together in stock only,
  similar in stock first, four each on the product page (and its Markdown version), four for the cart. The MCP
  server's `get_product` lists them as names and links.

- Picks: `product_relation_picks` (product, kind `together` / `similar` / `hidden`, related product, position), saved
  by `Related\RelationPicks` from the SKUs typed on the product's **Produse asociate** tab
  (`ProductRelationsController`, `catalog.manage`). `DatabaseRelatedProducts` reads them live: picks first in their
  order, then the computed relations without the picks and without the pairs the product hides; `forBasket()` the
  same, picks of the basket's products first.
- Best sellers: `Related\CountBestSellers` (`catalog:bestsellers`, 03:55) replaces `product_sales` (product, units,
  distinct buyers) from `SalesFigures::products()` over the last 90 days (gifts, cancelled and returned orders left
  out). `ProductSort::BestSelling` (`vandute`) orders listings by those units, then the newest;
  `RelatedProducts::bestSelling()` gives the home page's best sellers (two buyers or more).
- Recently viewed: `Storefront\Support\RecentlyViewed` keeps up to 12 product ids, newest first, in the session
  (`recently_viewed`); the product page adds to it (not its Markdown version) and shows the four before it, the home
  page the last four.

Tests: `tests/Feature/Catalog/RelatedProductsTest.php`, `tests/Feature/Storefront/RecentAndBestSellersTest.php`.

