Feature: Reviews restructuring and Creating Collection Indexer and Services

This commit is contained in:
2026-08-27 12:11:01 +03:00
parent ba5a9523c8
commit a2c3fd5457
15 changed files with 518 additions and 40 deletions
@@ -0,0 +1,69 @@
<?php
namespace Modules\Core\Catalog\Services;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Lunar\Models\Collection;
use Lunar\Search\CollectionIndexer as BaseCollectionIndexer;
/**
* Extends Lunar's own indexer so Modules\Core\Catalog\Services\CollectionService can
* serve category browsing/nav AND single-collection lookups from Meilisearch alone,
* the same reasoning as Modules\Core\Catalog\Services\ProductIndexer. Lunar's base
* indexer only carries `id`/`name`/`created_at` — nowhere near enough for a storefront
* category page or a nav tree. Adds:
* - parent_id, _lft, _rgt (filterable/sortable) — the nested-set tree position, so
* CollectionService can resolve "children of X" or build a full tree without a
* database read
* - collection_group_id (filterable) — mirrors Collection::scopeInGroup()
* - slugs (filterable) — every locale's Url::slug, so getBySlug() resolves from the
* index directly, no database read
* - thumbnail (display) — the collection's thumbnail image URL
*
* New fields aren't filterable/sortable in Meilisearch until `php artisan
* lunar:meilisearch:setup` re-syncs index settings, and existing documents need
* `lunar:search:index --refresh` to pick up the new shape.
*/
class CollectionIndexer extends BaseCollectionIndexer
{
public function getFilterableFields(): array
{
return [
...parent::getFilterableFields(),
'id',
'parent_id',
'_lft',
'collection_group_id',
'slugs',
];
}
public function getSortableFields(): array
{
return [
...parent::getSortableFields(),
'_lft',
];
}
public function makeAllSearchableUsing(Builder $query): Builder
{
return parent::makeAllSearchableUsing($query)->with(['urls', 'media']);
}
public function toSearchableArray(Model $model): array
{
/** @var Collection $model */
$data = parent::toSearchableArray($model);
$data['parent_id'] = $model->parent_id;
$data['_lft'] = $model->_lft;
$data['_rgt'] = $model->_rgt;
$data['collection_group_id'] = $model->collection_group_id;
$data['slugs'] = $model->urls->pluck('slug')->unique()->values()->all();
$data['thumbnail'] = $model->getThumbnailImage() ?: null;
return $data;
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace Modules\Core\Catalog\Services;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as LengthAwarePaginatorContract;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Lunar\Base\AttributeManifest;
use Lunar\FieldTypes\TranslatedText;
use Lunar\Models\Collection as CollectionModel;
use Modules\Core\Catalog\DTOs\CollectionFilters;
use Modules\Core\Catalog\Enums\CollectionSort;
use Modules\Core\Localization\Services\LanguageCache;
/**
* Category browsing (tree/nav) AND single-collection lookup, all reading directly
* from the Meilisearch index (Modules\Core\Catalog\Services\CollectionIndexer) — same
* shape and reasoning as Modules\Core\Catalog\Services\ProductService. Callers get
* plain arrays of the indexed document, not Eloquent models.
*/
class CollectionService
{
public function __construct(
private readonly LanguageCache $languages,
private readonly AttributeManifest $attributes,
) {}
/**
* Returns a real LengthAwarePaginator (not Scout's own paginateRaw() result — see
* ProductService's "Meilisearch driver quirk" note) so a controller/view gets
* normal pagination behaviour without ever touching the raw Meilisearch response.
*/
public function list(?CollectionFilters $filters = null, int $perPage = 24, int $page = 1, ?CollectionSort $sort = null): LengthAwarePaginator
{
$options = ['filter' => $this->buildFilter($filters)];
if ($sort !== null) {
$options['sort'] = [$sort->toMeilisearchSort()];
}
$paginator = CollectionModel::search('')
->options($options)
->paginateRaw(perPage: $perPage, page: $page);
$data = collect($this->hitsFrom($paginator))
->map(fn (array $collection) => $this->withLocalizedFields($collection))
->all();
return new LengthAwarePaginator(
items: $data,
total: $paginator->total(),
perPage: $paginator->perPage(),
currentPage: $paginator->currentPage(),
options: ['path' => LengthAwarePaginator::resolveCurrentPath()],
);
}
/**
* Look up a single collection by its URL slug (any locale). Returns the full
* indexed collection document, or null if no collection has that slug.
*/
public function getBySlug(string $slug): ?array
{
return $this->findOneWhere('slugs = "'.addcslashes($slug, '"\\').'"');
}
/**
* Look up a single collection by its primary key. Returns the full indexed
* collection document, or null if no collection has that id.
*/
public function getById(int $id): ?array
{
return $this->findOneWhere("id = \"{$id}\"");
}
private function findOneWhere(string $filter): ?array
{
$paginator = CollectionModel::search('')
->options(['filter' => $filter])
->paginateRaw(perPage: 1, page: 1);
$collection = $this->hitsFrom($paginator)[0] ?? null;
return $collection !== null ? $this->withLocalizedFields($collection) : null;
}
/**
* Resolves every translated Collection attribute's current-locale value — same
* logic as ProductService::withLocalizedFields(), see there for the full
* reasoning (AttributeManifest-driven, store-default-locale fallback, raw
* per-locale keys stripped after resolving).
*/
private function withLocalizedFields(array $collection): array
{
$locale = App::getLocale();
$fallbackLocale = $this->languages->defaultLocale();
$availableLocales = $this->languages->availableLocales();
foreach ($this->translatedAttributeHandles() as $handle) {
$collection[$handle] = $collection[$handle.'_'.$locale] ?? $collection[$handle.'_'.$fallbackLocale] ?? null;
foreach ($availableLocales as $availableLocale) {
unset($collection[$handle.'_'.$availableLocale]);
}
}
return $collection;
}
/**
* @return array<int, string>
*/
private function translatedAttributeHandles(): array
{
return $this->attributes->getSearchableAttributes((new CollectionModel)->getMorphClass())
->filter(fn ($attribute) => $attribute->type === TranslatedText::class)
->pluck('handle')
->all();
}
/**
* For the Meilisearch driver, Scout's paginateRaw() puts the whole raw response
* in items(), not a plain list of hits — see ProductService's identical note.
*/
private function hitsFrom(LengthAwarePaginatorContract $paginator): array
{
$rawResponse = $paginator->items();
return collect($rawResponse['hits'] ?? [])->values()->all();
}
private function buildFilter(?CollectionFilters $filters): ?string
{
if ($filters === null) {
return null;
}
$clauses = Collection::make([
$filters->parentId !== null ? "parent_id = \"{$filters->parentId}\""
: ($filters->rootOnly ? 'parent_id IS NULL' : null),
$filters->groupId !== null ? "collection_group_id = \"{$filters->groupId}\"" : null,
])->filter();
return $clauses->isEmpty() ? null : $clauses->join(' AND ');
}
}
+15 -2
View File
@@ -16,7 +16,14 @@ use Spatie\MediaLibrary\MediaCollections\Models\Media;
* Extends Lunar's own indexer so Modules\Core\Catalog\Services\ProductService can
* serve both listing/filtering AND single-product lookups from Meilisearch alone —
* one data source, no separate database read path for a product detail page. Adds:
* - collections: [{id, name}, ...] — filterable via `collections.id`
* - collections: [{id, name}, ...] — directly assigned collections only, for
* display (breadcrumbs, "also in"). Not filterable — see collection_ids below.
* - collection_ids (filterable): flat array of every directly-assigned collection's
* id UNIONED with all of its ancestors' ids. Products are typically attached only
* to leaf collections in a Shopify-imported tree, so a plain `collections.id`
* filter would never match a parent/root category page — ProductService::list()
* filters `collectionId` against this field instead, so "products in category X"
* also picks up every product attached only to one of X's subcategories.
* - slugs (every locale's Url::slug for the product, filterable) — lets
* ProductService::getBySlug() resolve a product from the index directly, with
* no database read at all
@@ -49,7 +56,7 @@ class ProductIndexer extends BaseProductIndexer
...parent::getFilterableFields(),
'id',
'brand',
'collections.id',
'collection_ids',
'price',
'slugs',
'channel_ids',
@@ -68,6 +75,7 @@ class ProductIndexer extends BaseProductIndexer
{
return parent::makeAllSearchableUsing($query)->with([
'collections',
'collections.ancestors',
'media',
'tags',
'urls',
@@ -89,6 +97,11 @@ class ProductIndexer extends BaseProductIndexer
'id' => $collection->id,
'name' => $collection->translateAttribute('name'),
])->all();
$data['collection_ids'] = $model->collections
->flatMap(fn ($collection) => [$collection->id, ...$collection->ancestors->pluck('id')])
->unique()
->values()
->all();
$data['slugs'] = $model->urls->pluck('slug')->unique()->values()->all();
$data['tags'] = $model->tags->pluck('value')->all();
$data['media'] = $model->media->map(fn (Media $media) => $this->mapMedia($media))->all();
+1 -1
View File
@@ -157,7 +157,7 @@ class ProductService
}
$clauses = Collection::make([
$filters->collectionId !== null ? "collections.id = \"{$filters->collectionId}\"" : null,
$filters->collectionId !== null ? "collection_ids = \"{$filters->collectionId}\"" : null,
$filters->brand !== null ? 'brand = "'.addcslashes($filters->brand, '"\\').'"' : null,
$filters->minPrice !== null ? "price >= {$filters->minPrice}" : null,
$filters->maxPrice !== null ? "price <= {$filters->maxPrice}" : null,