Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
026ab5bc2d | ||
|
|
483c0ce00f | ||
|
|
ce405d20e6 | ||
|
|
0f07751559 | ||
|
|
53d8a5aefe | ||
|
|
380e860386 |
@@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [0.11.1] - 2026-09-01
|
||||
|
||||
### Fixed
|
||||
- `Modules\Core\Catalog\Services\RecommendationService::recommend()` built its result with the base `Illuminate\Support\Collection` (`collect()`) instead of `Illuminate\Database\Eloquent\Collection`, even though every element is a `Product` model. `ProductIndexer::toSearchableArray()` calling `->load(['media', 'variants.prices'])` on that result threw `BadMethodCallException: Method Illuminate\Support\Collection::load does not exist` — silently failing every `MakeSearchable` queue job for a saved product (visible only as `FAIL` in the queue log, with the real exception in `storage/logs/laravel.log`). Fixed by having `RecommendationService` accumulate into a real `Eloquent\Collection` from the start.
|
||||
|
||||
## [0.11.0] - 2026-09-01
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Catalog\Services\RecommendationService` — computes "related products" for a given product as a configurable, ordered chain of strategies (`config('catalog.recommendation_rules')`), not one hardcoded rule. Tops up from each successive rule until the limit (default 4) is reached or every rule is exhausted — e.g. 3 products from a same-category rule plus 1 from a random fallback — deduplicated across rules so the same product is never returned twice. Ships with `Modules\Core\Catalog\Recommendations\SameCategoryRule` (other products sharing the source product's first collection) and `RandomRule` (the universal fallback, placed last in the default chain). A new rule is just a class implementing `Modules\Core\Catalog\Contracts\RecommendationRule`. Documented in `docs/product-recommendations.md`.
|
||||
- `Modules\Core\Catalog\Services\ProductIndexer` embeds the result directly into each product's own Meilisearch document as `recommendations: [{id, name, price, image}, ...]` (`recommendations.id` filterable) — a product detail page renders its "related products" section with zero extra queries, same reasoning as the existing `collections` field. Deliberately embeds an `id` for the view to build a locale-correct URL from, not a resolved `href` — `product.show` is locale-prefixed, so a URL baked in at index time would only be correct for whichever locale happened to be active during that index run.
|
||||
- `Modules\Core\Catalog\Events\ProductSaved`/`ProductDeleted`, dispatched from `Product::saved()`/`Product::deleted()` in `CatalogServiceProvider` (the latter fires for both a soft delete and a force delete, matching Scout's own `unsearchable()` trigger point) — feed `Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct`, which reverse-searches Meilisearch for every product currently recommending the changed/deleted one (`recommendations.id = "..."` — there's no Postgres relation for this, a recommendation only exists inside the index) and re-indexes them via Scout's own `->searchable()`. Product creation is deliberately not hooked into this: a new product not yet appearing as a recommendation elsewhere is an accepted staleness window, the same tradeoff already documented for `in_stock`/`price` — see `docs/product-recommendations.md`.
|
||||
- `CatalogServiceProvider` schedules `lunar:search:index "Lunar\Models\Product" --refresh` daily at 03:00 — a safety net on top of the event-driven reindexing above, covering a newly-created product not yet appearing as a recommendation and any other drift already accepted between reindexes. `--refresh` also re-syncs filterable/sortable index settings, not just documents.
|
||||
|
||||
## [0.10.1] - 2026-09-01
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Localization\Services\StorefrontLabels::all()` gains three keys found missing from `3dealer`'s actual `storefront.*` translation usage: `shop.price_min`, `shop.price_max`, `shop.reset` (the price-filter sidebar's min/max labels and its reset link). Picked up by `InstallLunarCommand`'s existing per-key upsert — re-running `lunar:install` on an already-installed store adds only these three rows, leaving everything already seeded or admin-edited untouched.
|
||||
|
||||
## [0.10.0] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "boboko/core",
|
||||
"description": "Core module — authentication and shared panel behaviour",
|
||||
"type": "library",
|
||||
"version": "0.10.0",
|
||||
"version": "0.11.1",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Core\\": "src/"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use Modules\Core\Catalog\Recommendations\RandomRule;
|
||||
use Modules\Core\Catalog\Recommendations\SameCategoryRule;
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Product recommendation rules
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Tried in order by Modules\Core\Catalog\Services\RecommendationService —
|
||||
| the first rule that returns at least one product wins. The order here IS
|
||||
| the fallback chain: SameCategoryRule first, then RandomRule as a
|
||||
| last-resort so a product page is never left with zero recommendations
|
||||
| (as long as the store has more than one product). A consuming app can
|
||||
| reorder, add, or remove rules freely — nothing about the chain shape is
|
||||
| hardcoded in the service itself.
|
||||
|
|
||||
*/
|
||||
'recommendation_rules' => [
|
||||
SameCategoryRule::class,
|
||||
RandomRule::class,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,155 @@
|
||||
# Product Recommendations
|
||||
|
||||
`Modules\Core\Catalog\Services\RecommendationService` computes "related products" for a given
|
||||
product — a same-category pick today, with a random fallback, but built as a configurable chain of
|
||||
strategies rather than one hardcoded rule. `Modules\Core\Catalog\Services\ProductIndexer` embeds
|
||||
the result directly into each product's own Meilisearch document, so a product detail page renders
|
||||
its recommendations with zero extra queries — same reasoning as `collections` (see
|
||||
`docs/product-listing.md`).
|
||||
|
||||
---
|
||||
|
||||
## The rule chain
|
||||
|
||||
```php
|
||||
use Modules\Core\Catalog\Services\RecommendationService;
|
||||
|
||||
$recommendations = app(RecommendationService::class)->recommend($product, limit: 4);
|
||||
// Illuminate\Support\Collection<int, Lunar\Models\Product>
|
||||
```
|
||||
|
||||
`recommend()` walks `config('catalog.recommendation_rules')` in order, **topping up** from each
|
||||
successive rule until `$limit` distinct products are collected or every rule is exhausted — it does
|
||||
not stop at the first rule that returns *something*. If a product's category only has 3 other
|
||||
products, `SameCategoryRule` contributes those 3 and `RandomRule` fills the last slot. A rule is
|
||||
handed the ids already collected (`$exclude`, always including the source product's own id) so it
|
||||
never wastes its own `$limit` budget re-suggesting something already picked, and the same product
|
||||
is never returned twice even if two rules would both suggest it.
|
||||
|
||||
Default chain (`config/catalog.php`):
|
||||
|
||||
```php
|
||||
'recommendation_rules' => [
|
||||
SameCategoryRule::class, // other products sharing $product's first collection
|
||||
RandomRule::class, // universal fallback — always returns something as
|
||||
// long as the store has more than one product
|
||||
],
|
||||
```
|
||||
|
||||
A consuming app publishes and edits this config to reorder, add, or remove rules — nothing about
|
||||
the chain shape is hardcoded in `RecommendationService` itself. A new rule (same tag, best sellers,
|
||||
"frequently bought together", ...) is a class implementing `Modules\Core\Catalog\Contracts\
|
||||
RecommendationRule`, added to the array:
|
||||
|
||||
```php
|
||||
interface RecommendationRule
|
||||
{
|
||||
/**
|
||||
* @param array<int> $exclude ids to never return — the source product's own
|
||||
* id, plus every id an earlier rule in the chain already picked
|
||||
* @return Collection<int, Product> at most $limit products
|
||||
*/
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection;
|
||||
}
|
||||
```
|
||||
|
||||
Rules query Eloquent directly (`$product->collections->first()->products()`, `Product::query()`),
|
||||
not `Modules\Core\Catalog\Services\ProductService` — see "Why not `ProductService`" below.
|
||||
|
||||
---
|
||||
|
||||
## Why not `ProductService`
|
||||
|
||||
Every other read path in `Modules\Core\Catalog` goes through `ProductService`, which reads
|
||||
Meilisearch and resolves translated fields to whatever locale the *current request* is in (see
|
||||
`docs/product-listing.md`, "Locale resolution"). Recommendation rules deliberately don't use it:
|
||||
they run inside `ProductIndexer::toSearchableArray()`, at **index time** — there is no request, no
|
||||
meaningful "current locale" to resolve against, and Meilisearch itself may be mid-write for the very
|
||||
product being indexed. Rules return raw `Lunar\Models\Product` models instead; `ProductIndexer`
|
||||
resolves what it embeds (`name` via `translateAttribute()`, `price` via the indexer's own
|
||||
`cheapestPrice()`, `image` via its own `mapMedia()`) the same way it already does for the embedded
|
||||
`collections` field — including that field's same accepted index-time-locale tradeoff (a
|
||||
recommendation's embedded `name` reflects whatever locale was active when *that* product was last
|
||||
indexed, not the viewer's current locale).
|
||||
|
||||
---
|
||||
|
||||
## What's embedded, and why not just an id
|
||||
|
||||
`ProductIndexer` embeds full card data per recommendation, not just an id:
|
||||
|
||||
```php
|
||||
$data['recommendations'] = [
|
||||
['id' => 42, 'name' => 'Espresso Cup', 'price' => 12.5, 'image' => 'https://.../thumb.jpg'],
|
||||
// ...
|
||||
];
|
||||
```
|
||||
|
||||
This shape is deliberately exactly what `x-ui.product-card`/`x-product-grid` (3dealer's storefront
|
||||
components) need — `name`, `price`, `image`, and an `id` the view resolves to a URL itself via
|
||||
`route('product.show', ['id' => $rec['id']])`. A resolved `href` is **not** embedded: `product.show`
|
||||
is locale-prefixed (`{locale}/products/{id}`), so a URL baked in at index time would be correct only
|
||||
for whichever locale happened to be active during that index run — wrong for every other locale.
|
||||
Building the URL is left to the view, which knows the current request's locale.
|
||||
|
||||
`recommendations.id` is marked **filterable** — not for the storefront, but for the reverse-lookup
|
||||
reindexing below.
|
||||
|
||||
---
|
||||
|
||||
## Keeping it fresh: `ProductSaved` / `ProductDeleted`
|
||||
|
||||
A recommendation is computed once, at index time, and embedded — it does not update itself when the
|
||||
recommended product later changes name, price, or image, or is deleted. Unlike `Modules\Core\Catalog\
|
||||
Observers\ProductOptionReindexObserver`'s equivalent problem (which product option value is used by),
|
||||
there is no Postgres relation for "which products currently recommend product X" — a recommendation
|
||||
only exists inside Meilisearch. The fix is a reverse Meilisearch filter query, not a database join,
|
||||
wired through a real event → listener pair (`Modules\Core\Providers\CatalogServiceProvider`):
|
||||
|
||||
- `Product::saved()` dispatches `Modules\Core\Catalog\Events\ProductSaved`.
|
||||
- `Product::deleted()` dispatches `Modules\Core\Catalog\Events\ProductDeleted` — fires for both a
|
||||
soft delete and a force delete (`Lunar\Models\Product` uses `SoftDeletes`), the same model event
|
||||
Laravel Scout's own `ModelObserver` hooks to make a deleted product `unsearchable()`.
|
||||
- `Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct` handles both: it searches the
|
||||
product index for `recommendations.id = "{id}"`, finds every referencing product, and calls
|
||||
`->searchable()` on each — which recomputes their `recommendations` field fresh, picking up the
|
||||
changed name/price/image, or (for a delete) dropping the now-gone product and topping back up to
|
||||
the configured limit via the rule chain, same as any other reindex.
|
||||
|
||||
`->searchable()` dispatches Scout's own reindex job, queued if `SCOUT_QUEUE` is configured — this
|
||||
listener does no synchronous Meilisearch writing itself.
|
||||
|
||||
**Product creation is deliberately not hooked into this.** A brand-new product has no
|
||||
`recommendations` of its own until Scout's existing create-triggered indexing runs (already correct
|
||||
— nothing to add). What's *not* immediate is other products picking the new one up as a fresh
|
||||
recommendation candidate — that happens on their own next natural reindex (a save, or the nightly
|
||||
full reindex below), the same accepted staleness window `docs/product-listing.md` already documents
|
||||
for `in_stock`/`price`. A full proactive "who could now recommend this new product" pass was
|
||||
considered and rejected as unnecessary cost for a cosmetic delay.
|
||||
|
||||
---
|
||||
|
||||
## Nightly full reindex
|
||||
|
||||
`Modules\Core\Providers\CatalogServiceProvider` schedules `lunar:search:index "Lunar\Models\Product"
|
||||
--refresh` daily at 03:00 — a safety net on top of the event-driven reindexing above, not a
|
||||
replacement for it. Catches what event-driven reindexing deliberately doesn't cover: a newly-created
|
||||
product not yet appearing as a recommendation elsewhere, and any other drift already accepted
|
||||
between reindexes (see `docs/product-listing.md`, "Stock goes stale between orders"). `--refresh`
|
||||
also re-syncs filterable/sortable index *settings*, not just documents, so a deploy that changed
|
||||
`ProductIndexer`'s field list self-heals overnight even if `lunar:meilisearch:setup` wasn't run
|
||||
manually right after that deploy.
|
||||
|
||||
---
|
||||
|
||||
## Re-syncing after this change
|
||||
|
||||
Same as any other `ProductIndexer` field change (see `docs/product-listing.md`):
|
||||
|
||||
```bash
|
||||
php artisan lunar:meilisearch:setup
|
||||
php artisan lunar:search:index "Lunar\Models\Product" --refresh
|
||||
```
|
||||
|
||||
Restart the queue worker if `SCOUT_QUEUE=true` — see `docs/product-listing.md`'s "Re-syncing after
|
||||
this change" for why a running worker won't otherwise pick up the new indexer code.
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Contracts;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
|
||||
/**
|
||||
* One strategy for producing recommended products for a given product —
|
||||
* e.g. same category, same tag, best sellers, random. Modules\Core\Catalog\
|
||||
* Services\RecommendationService runs rules registered in
|
||||
* config('catalog.recommendation_rules') in order, topping up from each
|
||||
* successive rule until $limit distinct products are collected or every
|
||||
* rule is exhausted (e.g. 3 from SameCategoryRule + 1 from RandomRule) —
|
||||
* nothing here decides that accumulation itself; a store composes its own
|
||||
* chain by ordering rules in config (e.g. [SameCategoryRule::class,
|
||||
* RandomRule::class]).
|
||||
*
|
||||
* Returns raw Product models, not ProductService::list()'s locale-resolved
|
||||
* array output — this runs at index time (ProductIndexer::toSearchableArray()),
|
||||
* where "the current locale" isn't a meaningful concept the way it is for a
|
||||
* storefront request. ProductIndexer resolves translated fields itself via
|
||||
* translateAttribute(), same as it already does for the embedded `collections`
|
||||
* field — same known index-time-locale tradeoff, not a new one.
|
||||
*/
|
||||
interface RecommendationRule
|
||||
{
|
||||
/**
|
||||
* $exclude carries $product's own id plus every id already picked by an
|
||||
* earlier rule this call — RecommendationService never shows the same
|
||||
* product twice even when two rules would both suggest it, and a rule
|
||||
* shouldn't spend its $limit budget re-returning something already
|
||||
* collected.
|
||||
*
|
||||
* @param array<int> $exclude
|
||||
* @return Collection<int, Product> at most $limit products
|
||||
*/
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Events;
|
||||
|
||||
/**
|
||||
* Dispatched whenever a Product is deleted (see CatalogServiceProvider,
|
||||
* which wires this to the model's own deleted() hook — fires for both a
|
||||
* soft delete and a force delete, same as Laravel Scout's own
|
||||
* ModelObserver::deleted() that triggers unsearchable() for the product
|
||||
* itself). Same purpose as Modules\Core\Catalog\Events\ProductSaved: lets
|
||||
* Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct find
|
||||
* and re-index every OTHER product that currently embeds this one in its
|
||||
* `recommendations` field, so a deleted product doesn't linger as a dead
|
||||
* reference elsewhere. Carries only the id, not the Product model — by the
|
||||
* time this fires the model may already be gone (force delete), and the
|
||||
* reverse lookup only ever needs the id to filter on.
|
||||
*/
|
||||
class ProductDeleted
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $productId,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Events;
|
||||
|
||||
use Lunar\Models\Product;
|
||||
|
||||
/**
|
||||
* Dispatched whenever a Product is saved (see CatalogServiceProvider,
|
||||
* which wires this to the model's own saved() hook) — exists specifically
|
||||
* so Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct can
|
||||
* find and re-index every OTHER product that currently embeds this one in
|
||||
* its own `recommendations` field (see ProductIndexer). Those products
|
||||
* have no direct database relationship to this one — a recommendation is
|
||||
* computed and stored only inside Meilisearch (Modules\Core\Catalog\
|
||||
* Services\RecommendationService) — so nothing about their own save
|
||||
* lifecycle would otherwise pick up this product's changed name/price/
|
||||
* image.
|
||||
*/
|
||||
class ProductSaved
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Product $product,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Listeners;
|
||||
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Events\ProductDeleted;
|
||||
use Modules\Core\Catalog\Events\ProductSaved;
|
||||
|
||||
/**
|
||||
* Keeps every product's embedded `recommendations` field (see
|
||||
* ProductIndexer) in sync when a product they recommend changes or is
|
||||
* removed. Unlike Modules\Core\Catalog\Observers\ProductOptionReindexObserver's
|
||||
* equivalent ("who references this option value"), there is no Postgres
|
||||
* table to query here — a recommendation only exists inside Meilisearch,
|
||||
* computed by RecommendationService at index time — so the reverse lookup
|
||||
* is a Meilisearch filter query against `recommendations.id`, not a
|
||||
* database join.
|
||||
*
|
||||
* Handles both ProductSaved (name/price/image changed — referencing
|
||||
* products' embedded copy is stale) and ProductDeleted (the recommended
|
||||
* product no longer exists at all — referencing products need to drop it
|
||||
* and, since RecommendationService tops up to its limit, naturally pick up
|
||||
* a replacement on reindex). Same reverse lookup either way, just a
|
||||
* different source for the id being searched for.
|
||||
*
|
||||
* Re-indexing via ->searchable() dispatches Scout's own (queued, if
|
||||
* SCOUT_QUEUE is configured) reindex job per matched product — this
|
||||
* listener itself does no synchronous Meilisearch writing.
|
||||
*/
|
||||
class ReindexProductsRecommendingProduct
|
||||
{
|
||||
public function handleSaved(ProductSaved $event): void
|
||||
{
|
||||
$this->reindexReferencingProducts($event->product->id);
|
||||
}
|
||||
|
||||
public function handleDeleted(ProductDeleted $event): void
|
||||
{
|
||||
$this->reindexReferencingProducts($event->productId);
|
||||
}
|
||||
|
||||
private function reindexReferencingProducts(int $productId): void
|
||||
{
|
||||
$hits = Product::search('')
|
||||
->options([
|
||||
'filter' => "recommendations.id = \"{$productId}\"",
|
||||
'attributesToRetrieve' => ['id'],
|
||||
// Meilisearch's own hitsPerPage default (20) would silently
|
||||
// drop referencing products past that count — this is a
|
||||
// reverse lookup, not a paginated storefront result, so it
|
||||
// needs every match, up to Meilisearch's hard limit.
|
||||
'hitsPerPage' => 1000,
|
||||
])
|
||||
->raw()['hits'] ?? [];
|
||||
|
||||
$ids = collect($hits)->pluck('id')->unique()->values();
|
||||
|
||||
if ($ids->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Product::whereIn('id', $ids)->get()->each->searchable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Recommendations;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* The universal fallback — always returns something as long as the store
|
||||
* has more than one product, since it has no eligibility condition of its
|
||||
* own to come up empty on. Meant to be placed last in
|
||||
* config('catalog.recommendation_rules'), not first: every store using
|
||||
* the default chain gets a real fallback, but one that only kicks in once
|
||||
* more specific rules (same category, same tag, ...) have had a chance.
|
||||
*/
|
||||
class RandomRule implements RecommendationRule
|
||||
{
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection
|
||||
{
|
||||
return Product::query()
|
||||
->whereKeyNot($exclude)
|
||||
->inRandomOrder()
|
||||
->limit($limit)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Recommendations;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* Recommends other products sharing at least one of $product's directly-
|
||||
* assigned collections — takes $product's first collection (a product
|
||||
* usually has one primary category; if it has several, the first is as
|
||||
* good a choice as any without a "primary collection" concept to prefer).
|
||||
* Returns nothing if $product has no collection at all, letting the next
|
||||
* rule in the chain (see RecommendationRule's docblock) take over.
|
||||
*
|
||||
* Queries Eloquent directly rather than going through Modules\Core\Catalog\
|
||||
* Services\ProductService — this runs at index time (see
|
||||
* RecommendationRule's docblock), where Meilisearch may be mid-reindex for
|
||||
* this very product and ProductService::list()'s locale-resolution has no
|
||||
* meaningful "current locale" to resolve against anyway.
|
||||
*/
|
||||
class SameCategoryRule implements RecommendationRule
|
||||
{
|
||||
public function recommend(Product $product, int $limit, array $exclude): Collection
|
||||
{
|
||||
$collection = $product->collections->first();
|
||||
|
||||
if ($collection === null) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return $collection->products()
|
||||
->whereKeyNot($exclude)
|
||||
->inRandomOrder()
|
||||
->limit($limit)
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,21 @@ use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
* Reflects stock as of the last reindex only — nothing currently reindexes a
|
||||
* product when an order decrements its stock (see docs/product-listing.md).
|
||||
*
|
||||
* - recommendations (recommendations.id filterable): [{id, name, price, image}, ...]
|
||||
* up to 4 other products to show alongside this one (a "related products"
|
||||
* section), sourced from Modules\Core\Catalog\Services\RecommendationService's
|
||||
* configured rule chain (config('catalog.recommendation_rules')). Embedded
|
||||
* card data, not just ids, same reasoning as `collections`: renders
|
||||
* directly with zero extra Meilisearch calls. `name` is resolved via
|
||||
* translateAttribute() at index time (not through ProductService's
|
||||
* per-request locale resolution, since indexing has no "current locale"
|
||||
* the way a storefront request does) — same known index-time-locale
|
||||
* tradeoff `collections` already has. `recommendations.id` is filterable
|
||||
* specifically so Modules\Core\Catalog\Listeners\
|
||||
* ReindexProductsRecommendingProduct can find every product currently
|
||||
* recommending a given one, when that one changes — there's no Postgres
|
||||
* relation for this, a recommendation only exists inside the index.
|
||||
*
|
||||
* A review is created/edited independently of its product (Modules\Core\Providers\
|
||||
* ReviewServiceProvider re-indexes the product on review create/update/delete), so
|
||||
* this data doesn't go stale between full reindexes.
|
||||
@@ -67,6 +82,7 @@ class ProductIndexer extends BaseProductIndexer
|
||||
'slugs',
|
||||
'channel_ids',
|
||||
'in_stock',
|
||||
'recommendations.id',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -126,6 +142,16 @@ class ProductIndexer extends BaseProductIndexer
|
||||
$data['in_stock'] = $model->variants->contains(
|
||||
fn (ProductVariant $variant) => $variant->canBeFulfilledAtQuantity(1)
|
||||
);
|
||||
$data['recommendations'] = app(RecommendationService::class)
|
||||
->recommend($model)
|
||||
->load(['media', 'variants.prices'])
|
||||
->map(fn (Product $recommendation) => [
|
||||
'id' => $recommendation->id,
|
||||
'name' => $recommendation->translateAttribute('name'),
|
||||
'price' => $this->cheapestPrice($recommendation, $currency),
|
||||
'image' => $recommendation->media->first() ? $this->mapMedia($recommendation->media->first())['thumb'] : null,
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\Services;
|
||||
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Catalog\Contracts\RecommendationRule;
|
||||
|
||||
/**
|
||||
* Runs each rule in config('catalog.recommendation_rules'), in order,
|
||||
* topping up from each successive rule until $limit distinct products are
|
||||
* collected or every rule is exhausted — e.g. 3 from SameCategoryRule
|
||||
* (the product's category only has 3 other products) + 1 from RandomRule.
|
||||
* No rule is special-cased as "the fallback" here; a store gets fallback
|
||||
* behaviour purely by how it orders its own config (e.g. SameCategoryRule
|
||||
* before RandomRule). Never returns the same product twice even if two
|
||||
* rules would both suggest it (see RecommendationRule's $exclude), and
|
||||
* never returns fewer than $limit unless the store genuinely doesn't have
|
||||
* that many other products at all.
|
||||
*/
|
||||
class RecommendationService
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Product>
|
||||
*/
|
||||
public function recommend(Product $product, int $limit = 4): Collection
|
||||
{
|
||||
$recommendations = new Collection();
|
||||
|
||||
foreach (config('catalog.recommendation_rules', []) as $ruleClass) {
|
||||
if ($recommendations->count() >= $limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
$exclude = [$product->id, ...$recommendations->pluck('id')];
|
||||
$remaining = $limit - $recommendations->count();
|
||||
|
||||
/** @var RecommendationRule $rule */
|
||||
$rule = app($ruleClass);
|
||||
$recommendations = $recommendations->merge(
|
||||
$rule->recommend($product, $remaining, $exclude)
|
||||
);
|
||||
}
|
||||
|
||||
return $recommendations->take($limit)->values();
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,9 @@ class StorefrontLabels
|
||||
'shop.search_label' => ['en' => 'Search products', 'el' => 'Αναζήτηση προϊόντων'],
|
||||
'shop.search_placeholder' => ['en' => 'Search products…', 'el' => 'Αναζήτησε προϊόντα…'],
|
||||
'shop.filter_price' => ['en' => 'Filter by price', 'el' => 'Φίλτρο τιμής'],
|
||||
'shop.price_min' => ['en' => 'Min price', 'el' => 'Ελάχιστη τιμή'],
|
||||
'shop.price_max' => ['en' => 'Max price', 'el' => 'Μέγιστη τιμή'],
|
||||
'shop.reset' => ['en' => 'Reset', 'el' => 'Επαναφορά'],
|
||||
'shop.apply' => ['en' => 'Apply', 'el' => 'Εφαρμογή'],
|
||||
'shop.availability' => ['en' => 'Availability', 'el' => 'Διαθεσιμότητα'],
|
||||
'shop.in_stock_only' => ['en' => 'In-stock products only', 'el' => 'Μόνο διαθέσιμα προϊόντα'],
|
||||
|
||||
@@ -2,17 +2,32 @@
|
||||
|
||||
namespace Modules\Core\Providers;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Lunar\Models\Product;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Lunar\Models\ProductOptionValue;
|
||||
use Modules\Core\Catalog\Events\ProductDeleted;
|
||||
use Modules\Core\Catalog\Events\ProductSaved;
|
||||
use Modules\Core\Catalog\Listeners\ReindexProductsRecommendingProduct;
|
||||
use Modules\Core\Catalog\Observers\ProductOptionReindexObserver;
|
||||
use Modules\Core\Catalog\OptionTypes\ColorOptionType;
|
||||
use Modules\Core\Catalog\Services\ProductOptionTypeManager;
|
||||
|
||||
class CatalogServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(__DIR__ . '/../../config/catalog.php', 'catalog');
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$this->publishes([
|
||||
__DIR__ . '/../../config/catalog.php' => config_path('catalog.php'),
|
||||
], 'core-config');
|
||||
|
||||
ProductOptionTypeManager::get()->register([
|
||||
ColorOptionType::class,
|
||||
]);
|
||||
@@ -24,5 +39,28 @@ class CatalogServiceProvider extends ServiceProvider
|
||||
|
||||
ProductOptionValue::saved(fn (ProductOptionValue $value) => $observer->valueSaved($value));
|
||||
ProductOptionValue::deleted(fn (ProductOptionValue $value) => $observer->valueDeleted($value));
|
||||
|
||||
Product::saved(fn (Product $product) => Event::dispatch(new ProductSaved($product)));
|
||||
Product::deleted(fn (Product $product) => Event::dispatch(new ProductDeleted($product->id)));
|
||||
|
||||
Event::listen(ProductSaved::class, [ReindexProductsRecommendingProduct::class, 'handleSaved']);
|
||||
Event::listen(ProductDeleted::class, [ReindexProductsRecommendingProduct::class, 'handleDeleted']);
|
||||
|
||||
$this->app->booted(function () {
|
||||
// A full nightly reindex, on top of the per-event reindexing
|
||||
// above — catches everything event-driven reindexing
|
||||
// deliberately doesn't cover: a newly-created product not yet
|
||||
// appearing as a recommendation elsewhere, in_stock/price
|
||||
// drifting from an order decrementing stock outside a product
|
||||
// save, and any other staleness ProductIndexer's own docblock
|
||||
// already documents as accepted between reindexes. --refresh
|
||||
// re-syncs filterable/sortable field settings too, not just
|
||||
// documents, so a deploy that changed ProductIndexer's field
|
||||
// list self-heals here even if `lunar:meilisearch:setup`
|
||||
// wasn't run manually after that deploy.
|
||||
$this->app->make(Schedule::class)
|
||||
->command('lunar:search:index', ['Lunar\\Models\\Product', '--refresh'])
|
||||
->dailyAt('03:00');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user