Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63caaf55c7 | ||
|
|
e4342da44a | ||
|
|
e95ea4a43c |
+11
-2
@@ -4,11 +4,20 @@ 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.6.1] - 2026-08-27
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Product\Contracts\ProductOptionTypeInterface` describes how a category of `Lunar\Models\ProductOption` (e.g. "Color", "Size") behaves — what structured data its values carry in their free-form `meta` jsonb column, and how an admin edits it via Filament — without introducing a new model. Registered via `Modules\Core\Product\Services\ProductOptionTypeManager::get()->register([...])` (a singleton registry, same shape as `Modules\Core\Notification\NotificationRegistry`) from a service provider's `boot()`. An admin then picks one per `ProductOption` from an "Option Type" dropdown on the option's own edit form (added by `Modules\Core\Product\Filament\Extensions\ProductOptionResourceExtension`), stored in `ProductOption::meta['option_type']` — deliberately not tied to the option's `handle`, since a shop's own handle naming shouldn't have to match a type's key. `Modules\Core\Product\Filament\Extensions\ValuesRelationManagerExtension` hooks Lunar's own `ValuesRelationManager` (both extensions via `LunarPanel::extensions()`, registered in `CorePlugin`) to append the resolved type's meta form fields to the stock "Values" tab — no fork of Lunar's classes needed. Ships a reference implementation, `Modules\Core\Product\OptionTypes\ColorOptionType`, registered automatically by the new `Modules\Core\Providers\ProductServiceProvider`. Documented in `docs/product-options.md`.
|
||||
- `Modules\Core\Product\Services\ProductIndexer::mapVariant()` now includes each option's `handle` (alongside its translated name) in a variant's indexed `options[]` — previously only the translated `option`/`value` names and `meta` were indexed, with no stable, locale-independent identifier for which option a value belongs to.
|
||||
- `Modules\Core\Product\Observers\ProductOptionReindexObserver`, wired in the new `Modules\Core\Providers\ProductServiceProvider`, keeps Meilisearch in sync when a `ProductOption` or `ProductOptionValue` is saved or deleted — e.g. picking an Option Type or editing a color's hex. `ProductIndexer::mapVariant()` embeds each option value's `meta` directly into a product's indexed document, but saving the option/value never fires the *product's* own save events, so without this a changed hex would only reach the index on that product's next unrelated reindex. The observer resolves every `Lunar\Models\Product` whose variants use the changed option (or option value) via the `product_option_value_product_variant` pivot, and calls `->searchable()` on each.
|
||||
|
||||
### Changed
|
||||
- **Breaking:** `Modules\Core\Product\Services\ProductIndexer`'s indexed `collections` field is now an array of `{id, name}` objects instead of two parallel arrays (`collections` as bare ID strings, `collection_names` as translated names joined only by array index). `collection_names` is removed. Filtering by collection now targets the nested field `collections.id` (Meilisearch supports filtering on nested object fields), not bare `collections` — `Modules\Core\Product\Services\ProductService::buildFilter()` updated accordingly; `ProductFilters(collectionId: ...)`'s public API is unchanged. Run `php artisan lunar:meilisearch:setup` then `lunar:search:index --refresh` after upgrading (see docs/product-listing.md "Gotchas").
|
||||
- **Breaking:** `ProductIndexer`'s indexed `review_count`/`average_rating` top-level keys are folded into the existing `reviews` key: `reviews` is now `{items, count, average_rating}` instead of a bare array with `review_count`/`average_rating` as separate sibling keys. `reviews` (the array of review items) moved to `reviews.items`.
|
||||
|
||||
## [0.6.0] - 2026-08-27
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Product\Contracts\ProductOptionTypeInterface` describes how a category of `Lunar\Models\ProductOption` (e.g. "Color", "Size") behaves — what structured data its values carry in their free-form `meta` jsonb column, and how an admin edits it via Filament — without introducing a new model. Enabled per-shop as a plain list in `config('core.product_option_types')`; an admin then picks one per `ProductOption` from a "Option Type" dropdown on the option's own edit form (added by `Modules\Core\Product\Filament\Extensions\ProductOptionResourceExtension`), stored in `ProductOption::meta['option_type']` — deliberately not tied to the option's `handle`, since a shop's own handle naming shouldn't have to match a type's key. `Modules\Core\Product\Services\ProductOptionTypeManager` resolves the selected key to its type (`all()`/`resolve()`). `Modules\Core\Product\Filament\Extensions\ValuesRelationManagerExtension` hooks Lunar's own `ValuesRelationManager` (both extensions via `LunarPanel::extensions()`, registered in `CorePlugin`) to append the resolved type's meta form fields to the stock "Values" tab — no fork of Lunar's classes needed. Ships a reference implementation, `Modules\Core\Product\OptionTypes\ColorOptionType` (not auto-registered). Documented in `docs/product-options.md`.
|
||||
- `Modules\Core\Product\Observers\ProductOptionReindexObserver`, wired in the new `Modules\Core\Providers\ProductServiceProvider`, keeps Meilisearch in sync when a `ProductOption` or `ProductOptionValue` is saved or deleted — e.g. picking an Option Type or editing a color's hex. `ProductIndexer::mapVariant()` embeds each option value's `meta` directly into a product's indexed document, but saving the option/value never fires the *product's* own save events, so without this a changed hex would only reach the index on that product's next unrelated reindex. The observer resolves every `Lunar\Models\Product` whose variants use the changed option (or option value) via the `product_option_value_product_variant` pivot, and calls `->searchable()` on each.
|
||||
- `Modules\Core\Localization\Models\LanguageLine` extends `spatie/laravel-translation-loader`'s `LanguageLine` to fall back to the store's actual default language (`LanguageCache::defaultLocale()`, backed by Lunar's `languages.default` flag) instead of the package's stock behavior of falling back to the static `config('app.fallback_locale')` — the two were previously disconnected, so changing the default language via the Filament **Languages** resource had no effect on which locale an untranslated storefront label silently fell back to. Swapped in automatically via `config('translation-loader.model')` in `LocalizationServiceProvider::register()`; no consuming app changes needed. Documented in `docs/localization.md` ("Fallback locale follows the store's default language").
|
||||
|
||||
### Changed
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
"name": "boboko/core",
|
||||
"description": "Core module — authentication and shared panel behaviour",
|
||||
"type": "library",
|
||||
"version": "0.6.0",
|
||||
"version": "0.6.1",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Core\\": "src/"
|
||||
@@ -36,7 +36,7 @@
|
||||
"Modules\\Core\\Providers\\AuthServiceProvider",
|
||||
"Modules\\Core\\Providers\\CustomerServiceProvider",
|
||||
"Modules\\Core\\Providers\\LocalizationServiceProvider",
|
||||
"Modules\\Core\\Providers\\ProductServiceProvider",
|
||||
"Modules\\Core\\Providers\\CatalogServiceProvider",
|
||||
"Modules\\Core\\Providers\\ReviewServiceProvider"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -16,23 +16,4 @@ return [
|
||||
|
||||
'auto_create_customer_for_user' => true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Product Option Types
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Enabled `Modules\Core\Product\Contracts\ProductOptionTypeInterface`
|
||||
| implementations, describing what structured data a ProductOption's
|
||||
| values carry in their `meta` jsonb column, and how an admin edits it.
|
||||
| An admin picks one per ProductOption from a dropdown built from this
|
||||
| list (stored in ProductOption::meta, not tied to the option's handle) —
|
||||
| a ProductOption with none selected has no described meta behavior,
|
||||
| plain name/position only.
|
||||
|
|
||||
| \App\ProductOptions\ColorOptionType::class,
|
||||
|
|
||||
*/
|
||||
|
||||
'product_option_types' => [],
|
||||
|
||||
];
|
||||
|
||||
@@ -72,15 +72,14 @@ needs, listing and detail alike:
|
||||
| Field | Source | Notes |
|
||||
|---|---|---|
|
||||
| `id` | — | Newly marked **filterable** — needed for `getById()`'s `id = "..."` filter; Meilisearch doesn't filter on the primary key by default. |
|
||||
| `collections` | `$product->collections->pluck('id')` | Filterable. Array of collection IDs (as strings) — filtering matches by ID, not slug. |
|
||||
| `collection_names` | `$product->collections` | Display only, not filterable — translated collection names. |
|
||||
| `collections` | `$product->collections` | Array of `{id, name}` — `name` is the translated collection name. Filterable on the nested field `collections.id`, not `collections` itself. |
|
||||
| `slugs` | `$product->urls->pluck('slug')` | Filterable. Every locale's `Url::slug` for the product, so `getBySlug()` resolves purely from the index — no database read. |
|
||||
| `price` | Cheapest variant's base price | Filterable. Float in major units (e.g. `19.99`, not `1999`). Base price only — no customer group, default currency (`Currency::getDefault()`) only. `null` if the product has no priced variant yet, so it's excluded from range filters rather than treated as free. |
|
||||
| `brand` | Already indexed by Lunar's base indexer | Newly marked **filterable** — it existed in the document already, just wasn't usable in a `filter` clause. |
|
||||
| `tags` | `$product->tags->pluck('value')` | Display only. |
|
||||
| `media` | `$product->media` | Full gallery (id/url/thumb per image), not just the single thumbnail Lunar's base indexer sends. |
|
||||
| `variants` | `$product->variants` | Per variant: `id`, `sku`, `stock`, `purchasable`, `options` (option/value names, in the current locale), `prices` (per currency/customer group), `media` (variant-specific images). |
|
||||
| `reviews`, `review_count`, `average_rating` | `Modules\Core\Review\Models\ProductReview` | See "Reviews" below. |
|
||||
| `reviews` | `Modules\Core\Review\Models\ProductReview` | `{items, count, average_rating}` — see "Reviews" below. |
|
||||
|
||||
`name`/`description` (and any other `TranslatedText` attribute) are indexed per-locale — see
|
||||
"Locale resolution" below for how `ProductService` resolves them down to one value per request.
|
||||
@@ -121,11 +120,12 @@ description sourced from `ProductService`'s results must treat it as trusted HTM
|
||||
|
||||
## Reviews
|
||||
|
||||
`Modules\Core\Review\Models\ProductReview` (`product_reviews` table) is indexed per-product as
|
||||
`reviews` (array), plus `review_count` and `average_rating` (rounded to 1 decimal, `null` if the
|
||||
product has no reviews). Only public-safe fields are included — **`reviewer_email` is deliberately
|
||||
excluded**, it's PII with no storefront use. `reply`/`replied_at` (the staff response) are
|
||||
included, since they're meant to be shown alongside the review.
|
||||
`Modules\Core\Review\Models\ProductReview` (`product_reviews` table) is indexed per-product under
|
||||
a single `reviews` key: `{items, count, average_rating}` — `items` is the array of reviews,
|
||||
`average_rating` is rounded to 1 decimal (`null` if the product has no reviews). Only public-safe
|
||||
fields are included on each item — **`reviewer_email` is deliberately excluded**, it's PII with no
|
||||
storefront use. `reply`/`replied_at` (the staff response) are included, since they're meant to be
|
||||
shown alongside the review.
|
||||
|
||||
A review is created/edited independently of its product (a customer submission, a staff reply)
|
||||
— its own save doesn't touch the `Product` row, so the product's own model events never fire.
|
||||
|
||||
+25
-17
@@ -15,21 +15,23 @@ admin edits that data — without introducing a new model. `ProductOption`/
|
||||
|
||||
## Registering a type
|
||||
|
||||
A shop enables a type class in `config/core.php`:
|
||||
A shop registers a type class from its own service provider's `boot()`, the same
|
||||
shape as `Modules\Core\Notification\NotificationRegistry`:
|
||||
|
||||
```php
|
||||
// config/core.php
|
||||
'product_option_types' => [
|
||||
use Modules\Core\Product\Services\ProductOptionTypeManager;
|
||||
|
||||
ProductOptionTypeManager::get()->register([
|
||||
\App\ProductOptions\ColorOptionType::class,
|
||||
],
|
||||
]);
|
||||
```
|
||||
|
||||
This is a plain list, **not** keyed by `ProductOption::handle` — a shop's own handle
|
||||
naming (transliterated Greek, legacy import slugs, whatever an admin happened to type
|
||||
when creating the option) shouldn't have to match a type's key. Instead, an admin
|
||||
picks a type per-option from a dropdown on the `ProductOption` edit form itself (see
|
||||
below); the choice is stored in `ProductOption::meta['option_type']`, not inferred
|
||||
from anything else.
|
||||
Not a published config array — the mapping isn't per-`ProductOption`, so there's
|
||||
nothing for a shop to *key* by. Instead, an admin picks a type per-option from a
|
||||
dropdown on the `ProductOption` edit form itself (see below); the choice is stored
|
||||
in `ProductOption::meta['option_type']`, deliberately **not** tied to the option's
|
||||
`handle` (a shop's own handle naming — transliterated Greek, legacy import slugs —
|
||||
shouldn't have to match a type's key).
|
||||
|
||||
A `ProductOption` with no type selected behaves exactly as stock Lunar does — plain
|
||||
name/position, no extra meta form.
|
||||
@@ -68,18 +70,24 @@ plain jsonb column). `getKey()` is the identifier used in the admin's "Option Ty
|
||||
dropdown and in `ProductOption::meta['option_type']` — it has no relationship to the
|
||||
`ProductOption::handle`.
|
||||
|
||||
A reference implementation ships at `Modules\Core\Product\OptionTypes\ColorOptionType`
|
||||
— not auto-registered, since registration is always an explicit shop decision.
|
||||
A reference implementation ships at `Modules\Core\Product\OptionTypes\ColorOptionType`,
|
||||
registered automatically by `Modules\Core\Providers\ProductServiceProvider` — no shop
|
||||
setup needed for it to appear in the "Option Type" dropdown, though an admin still
|
||||
has to pick it per-`ProductOption` for it to take effect.
|
||||
|
||||
---
|
||||
|
||||
## How it's wired into the admin UI
|
||||
|
||||
`Modules\Core\Product\Services\ProductOptionTypeManager`:
|
||||
- `all(): Collection<string, ProductOptionTypeInterface>` — every enabled type,
|
||||
keyed by `getKey()`.
|
||||
- `resolve(?string $key): ?ProductOptionTypeInterface` — looks up one by key (or
|
||||
`null` if no key / not found).
|
||||
`Modules\Core\Product\Services\ProductOptionTypeManager` is a singleton registry:
|
||||
- `get(): static` — the shared instance.
|
||||
- `register(array $types): void` — registers one or more type classes, keyed
|
||||
internally by `getKey()`.
|
||||
- `unregister(string $key): void`
|
||||
- `resolve(?string $key): ?ProductOptionTypeInterface` — looks up a registered type
|
||||
by key (or `null` if no key / not found).
|
||||
- `all(): array<string, class-string>` — every registered type's class, keyed by
|
||||
`getKey()`.
|
||||
|
||||
Two extensions hook into Lunar's admin via its extension system
|
||||
(`LunarPanel::extensions([...])`, registered in `CorePlugin`) — no forking of Lunar's
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Contracts;
|
||||
|
||||
use Filament\Forms\Components\Component;
|
||||
|
||||
/**
|
||||
* A Product Option Type describes how a category of Lunar `ProductOption` (e.g.
|
||||
* "Color", "Size", "Material") behaves — namely, what structured data its values
|
||||
* carry in their free-form `meta` jsonb column, and how an admin edits that data.
|
||||
*
|
||||
* `ProductOption`/`ProductOptionValue` themselves stay exactly as Lunar defines
|
||||
* them — this is not a new model. `ProductOptionTypeManager` maps a
|
||||
* `ProductOption::handle` to the type describing it (via `config('core.product_option_types')`,
|
||||
* typed explicitly by the admin), so adding a new kind of option is a single new
|
||||
* class, not scattered per-option special-casing across the admin UI or storefront.
|
||||
*/
|
||||
interface ProductOptionTypeInterface
|
||||
{
|
||||
/**
|
||||
* Matches the ProductOption::handle this type describes (e.g. 'color', 'size').
|
||||
*/
|
||||
public static function getKey(): string;
|
||||
|
||||
/**
|
||||
* Filament form components for editing a ProductOptionValue's `meta` under this
|
||||
* option type — e.g. Color returns a color picker for `meta.hex`, Size returns a
|
||||
* numeric input for `meta.sort_value`. Field names should be dot-notation under
|
||||
* `meta` (e.g. `meta.hex`), matching where ValuesRelationManagerExtension saves them.
|
||||
*
|
||||
* @return array<Component>
|
||||
*/
|
||||
public function getMetaForm(): array;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\DTOs;
|
||||
|
||||
/**
|
||||
* Filter input for ProductService::list(). All fields are optional — omitted
|
||||
* filters are simply not added to the Meilisearch query. Values are matched
|
||||
* against Modules\Core\Product\Services\ProductIndexer's document fields, so
|
||||
* filtering only works on stores where that indexer is registered and the index
|
||||
* has been re-synced (see docs/product-listing.md).
|
||||
*/
|
||||
class ProductFilters
|
||||
{
|
||||
public function __construct(
|
||||
public readonly ?int $collectionId = null,
|
||||
public readonly ?string $brand = null,
|
||||
public readonly ?float $minPrice = null,
|
||||
public readonly ?float $maxPrice = null,
|
||||
) {}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Enums;
|
||||
|
||||
/**
|
||||
* Sort options for ProductService::list(), each mapped to a Meilisearch `sort`
|
||||
* clause against a field indexed as sortable by Modules\Core\Product\Services\
|
||||
* ProductIndexer (see its getSortableFields()). Adding a case here requires the
|
||||
* matching field to also be sortable in the index, re-synced via
|
||||
* `php artisan lunar:meilisearch:setup`.
|
||||
*/
|
||||
enum ProductSort: string
|
||||
{
|
||||
case PriceAsc = 'price_asc';
|
||||
case PriceDesc = 'price_desc';
|
||||
case Newest = 'newest';
|
||||
|
||||
public function toMeilisearchSort(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PriceAsc => 'price:asc',
|
||||
self::PriceDesc => 'price:desc',
|
||||
self::Newest => 'created_at:desc',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Filament\Extensions;
|
||||
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Form;
|
||||
use Illuminate\Support\Str;
|
||||
use Lunar\Admin\Support\Extending\ResourceExtension;
|
||||
use Modules\Core\Product\Services\ProductOptionTypeManager;
|
||||
|
||||
/**
|
||||
* Adds an "Option Type" dropdown to Lunar's own ProductOptionResource form, letting
|
||||
* an admin pick which registered `ProductOptionTypeInterface` (if any) describes this
|
||||
* option's values — e.g. "Color" — independent of the option's own `handle`. The
|
||||
* selection is saved to `ProductOption::meta['option_type']`.
|
||||
*/
|
||||
class ProductOptionResourceExtension extends ResourceExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
{
|
||||
$options = app(ProductOptionTypeManager::class)->all()
|
||||
->keys()
|
||||
->mapWithKeys(fn (string $key) => [$key => Str::headline($key)])
|
||||
->all();
|
||||
|
||||
if ($options === []) {
|
||||
return $form;
|
||||
}
|
||||
|
||||
return $form->schema([
|
||||
...$form->getComponents(),
|
||||
Select::make('meta.option_type')
|
||||
->label('Option Type')
|
||||
->options($options)
|
||||
->helperText('Controls which meta fields appear when editing this option\'s values.')
|
||||
->native(false),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Filament\Extensions;
|
||||
|
||||
use Filament\Forms\Form;
|
||||
use Lunar\Admin\Support\Extending\RelationManagerExtension;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Modules\Core\Product\Services\ProductOptionTypeManager;
|
||||
|
||||
/**
|
||||
* Appends the owning `ProductOption`'s registered `ProductOptionTypeInterface` meta
|
||||
* form (if any) to Lunar's own ValuesRelationManager form, so e.g. a "color" option
|
||||
* gets a hex-color picker for each value alongside the stock name field — without
|
||||
* forking Lunar's relation manager.
|
||||
*/
|
||||
class ValuesRelationManagerExtension extends RelationManagerExtension
|
||||
{
|
||||
public function extendForm(Form $form): Form
|
||||
{
|
||||
/** @var ProductOption $option */
|
||||
$option = $this->caller->getOwnerRecord();
|
||||
|
||||
$type = app(ProductOptionTypeManager::class)->resolve($option->meta['option_type'] ?? null);
|
||||
|
||||
if ($type === null) {
|
||||
return $form;
|
||||
}
|
||||
|
||||
return $form->schema([
|
||||
...$form->getComponents(),
|
||||
...$type->getMetaForm(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Observers;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Lunar\Models\Product;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Lunar\Models\ProductOptionValue;
|
||||
use Lunar\Models\ProductVariant;
|
||||
|
||||
/**
|
||||
* Keeps every product using a ProductOption/ProductOptionValue in sync with
|
||||
* Meilisearch. ProductIndexer::mapVariant() embeds each option value's `meta`
|
||||
* (e.g. a color's hex) directly into the product's indexed document — but saving
|
||||
* the option or one of its values never fires the *product's* own save/update
|
||||
* events, so without this, a changed option_type or a changed hex would only
|
||||
* reach the index on that product's next unrelated reindex.
|
||||
*/
|
||||
class ProductOptionReindexObserver
|
||||
{
|
||||
public function optionSaved(ProductOption $option): void
|
||||
{
|
||||
$this->reindexProductsForOption($option->id);
|
||||
}
|
||||
|
||||
public function optionDeleted(ProductOption $option): void
|
||||
{
|
||||
$this->reindexProductsForOption($option->id);
|
||||
}
|
||||
|
||||
public function valueSaved(ProductOptionValue $value): void
|
||||
{
|
||||
$this->reindexProductsForValues([$value->id]);
|
||||
}
|
||||
|
||||
public function valueDeleted(ProductOptionValue $value): void
|
||||
{
|
||||
$this->reindexProductsForValues([$value->id]);
|
||||
}
|
||||
|
||||
private function reindexProductsForOption(int $optionId): void
|
||||
{
|
||||
$valueIds = ProductOptionValue::where('product_option_id', $optionId)->pluck('id');
|
||||
|
||||
$this->reindexProductsForValues($valueIds->all());
|
||||
}
|
||||
|
||||
private function reindexProductsForValues(array $valueIds): void
|
||||
{
|
||||
if ($valueIds === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$prefix = config('lunar.database.table_prefix');
|
||||
|
||||
$variantIds = DB::table("{$prefix}product_option_value_product_variant")
|
||||
->whereIn('value_id', $valueIds)
|
||||
->pluck('variant_id');
|
||||
|
||||
if ($variantIds->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$productIds = ProductVariant::whereIn('id', $variantIds)->pluck('product_id')->unique();
|
||||
|
||||
Product::whereIn('id', $productIds)->get()->each->searchable();
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\OptionTypes;
|
||||
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Modules\Core\Product\Contracts\ProductOptionTypeInterface;
|
||||
|
||||
/**
|
||||
* Reference implementation: describes a 'color' ProductOption's values as
|
||||
* carrying a hex code in `meta.hex`, editable via a Filament color picker.
|
||||
* Not auto-registered — a shop opts in via config('core.product_option_types').
|
||||
*/
|
||||
class ColorOptionType implements ProductOptionTypeInterface
|
||||
{
|
||||
public static function getKey(): string
|
||||
{
|
||||
return 'color';
|
||||
}
|
||||
|
||||
public function getMetaForm(): array
|
||||
{
|
||||
return [
|
||||
ColorPicker::make('meta.hex')
|
||||
->label('Color')
|
||||
->required(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Services;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Lunar\Models\Currency;
|
||||
use Lunar\Models\Price;
|
||||
use Lunar\Models\Product;
|
||||
use Lunar\Models\ProductVariant;
|
||||
use Lunar\Search\ProductIndexer as BaseProductIndexer;
|
||||
use Modules\Core\Review\Models\ProductReview;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
|
||||
/**
|
||||
* Extends Lunar's own indexer so Modules\Core\Product\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 (ids, filterable) and collection_names (display)
|
||||
* - 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
|
||||
* - price (cheapest variant, filterable) and full per-variant pricing
|
||||
* - variants: sku, stock, purchasable, option values, prices, media
|
||||
* - the full media gallery (not just the single thumbnail Lunar's base indexer sends)
|
||||
* - tags
|
||||
* - reviews: public-safe fields only (see mapReview() — reviewer_email is deliberately
|
||||
* excluded, it's PII with no storefront use), including staff replies, plus an
|
||||
* average rating
|
||||
* - channel_ids (filterable) — Lunar's base indexer only indexes "status" as
|
||||
* filterable, not channel assignment, so search results can't otherwise be
|
||||
* scoped to products actually assigned+enabled on the current sales channel
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* New fields aren't filterable 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 — see docs/product-listing.md. If SCOUT_QUEUE is enabled, the
|
||||
* queue worker also needs restarting after deploying changes to this class (see
|
||||
* docs/lunar.md "Gotchas" — a running worker keeps stale indexer code in memory).
|
||||
*/
|
||||
class ProductIndexer extends BaseProductIndexer
|
||||
{
|
||||
public function getFilterableFields(): array
|
||||
{
|
||||
return [
|
||||
...parent::getFilterableFields(),
|
||||
'id',
|
||||
'brand',
|
||||
'collections',
|
||||
'price',
|
||||
'slugs',
|
||||
'channel_ids',
|
||||
];
|
||||
}
|
||||
|
||||
public function getSortableFields(): array
|
||||
{
|
||||
return [
|
||||
...parent::getSortableFields(),
|
||||
'price',
|
||||
];
|
||||
}
|
||||
|
||||
public function makeAllSearchableUsing(Builder $query): Builder
|
||||
{
|
||||
return parent::makeAllSearchableUsing($query)->with([
|
||||
'collections',
|
||||
'media',
|
||||
'tags',
|
||||
'urls',
|
||||
'variants.images',
|
||||
'variants.prices',
|
||||
'variants.values.option',
|
||||
]);
|
||||
}
|
||||
|
||||
public function toSearchableArray(Model $model): array
|
||||
{
|
||||
/** @var Product $model */
|
||||
$data = parent::toSearchableArray($model);
|
||||
|
||||
$currency = Currency::getDefault();
|
||||
$reviews = ProductReview::where('product_id', $model->id)->with('media')->get();
|
||||
|
||||
$data['collections'] = $model->collections->pluck('id')->map(fn ($id) => (string) $id)->all();
|
||||
$data['collection_names'] = $model->collections->map(fn ($collection) => $collection->translateAttribute('name'))->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();
|
||||
$data['variants'] = $model->variants->map(fn (ProductVariant $variant) => $this->mapVariant($variant, $currency))->all();
|
||||
$data['price'] = $this->cheapestPrice($model, $currency);
|
||||
$data['reviews'] = $reviews->map(fn (ProductReview $review) => $this->mapReview($review))->all();
|
||||
$data['review_count'] = $reviews->count();
|
||||
$data['average_rating'] = $reviews->isEmpty() ? null : round($reviews->avg('rating'), 1);
|
||||
$data['channel_ids'] = $model->channels()
|
||||
->wherePivot('enabled', true)
|
||||
->pluck('lunar_channels.id')
|
||||
->toArray();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function mapVariant(ProductVariant $variant, Currency $currency): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'sku' => $variant->sku,
|
||||
'stock' => $variant->stock,
|
||||
'purchasable' => $variant->purchasable,
|
||||
'options' => $variant->values->map(fn ($value) => [
|
||||
'option' => $this->translatedName($value->option->name),
|
||||
'value' => $this->translatedName($value->name),
|
||||
'meta' => $value->meta,
|
||||
])->all(),
|
||||
'prices' => $variant->prices->map(fn (Price $price) => [
|
||||
'currency_id' => $price->currency_id,
|
||||
'customer_group_id' => $price->customer_group_id,
|
||||
'price' => $price->price->decimal(),
|
||||
'compare_price' => $price->compare_price?->decimal(),
|
||||
'min_quantity' => $price->min_quantity,
|
||||
])->all(),
|
||||
'media' => $variant->images->map(fn (Media $media) => $this->mapMedia($media))->all(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Public-safe fields only — reviewer_email is PII with no storefront use and is
|
||||
* deliberately excluded, unlike every other column on the review. reply/replied_at
|
||||
* (the staff response) are included since they're meant to be shown alongside the
|
||||
* review on the storefront.
|
||||
*/
|
||||
private function mapReview(ProductReview $review): array
|
||||
{
|
||||
return [
|
||||
'id' => $review->id,
|
||||
'title' => $review->title,
|
||||
'body' => $review->body,
|
||||
'rating' => $review->rating,
|
||||
'reviewed_at' => $review->reviewed_at?->timestamp,
|
||||
'reviewer_name' => $review->reviewer_name,
|
||||
'reply' => $review->reply,
|
||||
'replied_at' => $review->replied_at?->timestamp,
|
||||
'location' => $review->location,
|
||||
'media' => $review->media->map(fn (Media $media) => $this->mapMedia($media))->all(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* ProductOption/ProductOptionValue's `name` is a plain locale-keyed array cast
|
||||
* (AsArrayObject) directly on the column — unlike Product/Collection/Brand, it is
|
||||
* not stored in attribute_data. Lunar's translateAttribute() only reads
|
||||
* attribute_data, so it silently returns null for these two models; this reads
|
||||
* the array directly instead. Falls back to the first available locale if the
|
||||
* current one is missing. Not a general replacement for translateAttribute() —
|
||||
* every other translated field in this indexer (product/collection name and
|
||||
* description) genuinely is attribute_data-backed and translateAttribute() is
|
||||
* correct for those.
|
||||
*/
|
||||
private function translatedName(mixed $name): ?string
|
||||
{
|
||||
$names = is_array($name) ? $name : (array) $name;
|
||||
|
||||
return $names[app()->getLocale()] ?? reset($names) ?: null;
|
||||
}
|
||||
|
||||
private function mapMedia(Media $media): array
|
||||
{
|
||||
return [
|
||||
'id' => $media->id,
|
||||
'url' => $media->getUrl(),
|
||||
'thumb' => $media->getUrl('small'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The cheapest variant's base price (no customer group) in the default currency,
|
||||
* as a float in major units — e.g. 19.99, not 1999. Null if the product has no
|
||||
* variant with a price in that currency yet, so it's excluded from price filters
|
||||
* rather than sorting to the bottom as if it were free.
|
||||
*/
|
||||
private function cheapestPrice(Product $model, Currency $currency): ?float
|
||||
{
|
||||
$price = $model->variants
|
||||
->flatMap(fn ($variant) => $variant->prices)
|
||||
->filter(fn ($price) => $price->currency_id === $currency->id && $price->customer_group_id === null)
|
||||
->min(fn ($price) => $price->price->value);
|
||||
|
||||
return $price !== null ? $price / (10 ** $currency->decimal_places) : null;
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Services;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Modules\Core\Product\Contracts\ProductOptionTypeInterface;
|
||||
|
||||
/**
|
||||
* Resolves an admin-selected option type key to the `ProductOptionTypeInterface`
|
||||
* describing it. The selection (which key a given `Lunar\Models\ProductOption` uses)
|
||||
* is stored per-option in `ProductOption::meta['option_type']` — deliberately not
|
||||
* tied to the option's `handle`, since a shop's own handle naming (e.g. transliterated
|
||||
* Greek, legacy imports) shouldn't have to match a type's key.
|
||||
*
|
||||
* The available keys come from `config('core.product_option_types')` — a plain list,
|
||||
* not a config array, because the mapping from option to type is an admin's per-option
|
||||
* choice made in the UI (see ValuesRelationManagerExtension/ProductOptionResourceExtension),
|
||||
* not something config alone can express.
|
||||
*/
|
||||
class ProductOptionTypeManager
|
||||
{
|
||||
/**
|
||||
* @return Collection<string, ProductOptionTypeInterface> keyed by getKey()
|
||||
*/
|
||||
public function all(): Collection
|
||||
{
|
||||
return collect(config('core.product_option_types', []))
|
||||
->map(fn (string $class) => app($class))
|
||||
->keyBy(fn (ProductOptionTypeInterface $type) => $type::getKey());
|
||||
}
|
||||
|
||||
public function resolve(?string $key): ?ProductOptionTypeInterface
|
||||
{
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->all()->get($key);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\Services;
|
||||
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Lunar\Facades\AttributeManifest;
|
||||
use Lunar\Models\Language;
|
||||
use Lunar\Models\Product;
|
||||
|
||||
/**
|
||||
* Lunar's Meilisearch indexer flattens translated attributes into locale-suffixed
|
||||
* fields on a single document (name_en, name_el, description_en, description_el —
|
||||
* see Lunar\Search\ScoutIndexer::mapSearchableAttributes()), not separate indexes
|
||||
* or a filterable locale field. Locale-aware search means choosing which fields
|
||||
* to search on, not filtering results by locale.
|
||||
*/
|
||||
class ProductSearchService
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Product>
|
||||
*/
|
||||
public function search(string $query, ?string $locale = null): Collection
|
||||
{
|
||||
$locale ??= App::getLocale();
|
||||
$defaultLocale = Language::getDefault()->code;
|
||||
|
||||
return Product::search($query)
|
||||
->options([
|
||||
'attributesToSearchOn' => $this->searchableFields($locale, $defaultLocale),
|
||||
])
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Target the resolved locale's fields plus the default locale's fields, so a
|
||||
* product that's only ever been translated into the default language still
|
||||
* surfaces when searched in another locale, instead of becoming invisible
|
||||
* until every product is fully translated.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function searchableFields(string $locale, string $defaultLocale): array
|
||||
{
|
||||
$handles = AttributeManifest::getSearchableAttributes(Product::morphName())
|
||||
->pluck('handle');
|
||||
|
||||
$locales = array_unique([$locale, $defaultLocale]);
|
||||
|
||||
return $handles
|
||||
->crossJoin($locales)
|
||||
->map(fn (array $pair) => "{$pair[0]}_{$pair[1]}")
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Product\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\Product;
|
||||
use Modules\Core\Localization\Services\LanguageCache;
|
||||
use Modules\Core\Product\DTOs\ProductFilters;
|
||||
use Modules\Core\Product\Enums\ProductSort;
|
||||
|
||||
/**
|
||||
* Storefront product listing/filtering AND single-product lookup, all reading directly
|
||||
* from the Meilisearch index (Modules\Core\Product\Services\ProductIndexer) - one data
|
||||
* source, no ->get() model hydration anywhere in this service. Callers get plain arrays
|
||||
* of the indexed document, not Eloquent models.
|
||||
*
|
||||
* Full-text query search lives separately in Modules\Core\Product\Services\
|
||||
* ProductSearchService; this service is for browsing/filtering without a search term.
|
||||
*/
|
||||
class ProductService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LanguageCache $languages,
|
||||
private readonly AttributeManifest $attributes,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Returns a real LengthAwarePaginator (not Scout's own paginateRaw() result -
|
||||
* see "Meilisearch driver quirk" below) so a controller/view gets normal
|
||||
* pagination behaviour ($products->links(), JSON serialization, etc.)
|
||||
* without ever touching the raw Meilisearch response directly.
|
||||
*/
|
||||
public function list(?ProductFilters $filters = null, int $perPage = 24, int $page = 1, ?ProductSort $sort = null): LengthAwarePaginator
|
||||
{
|
||||
$options = ['filter' => $this->buildFilter($filters)];
|
||||
|
||||
if ($sort !== null) {
|
||||
$options['sort'] = [$sort->toMeilisearchSort()];
|
||||
}
|
||||
|
||||
$paginator = Product::search('')
|
||||
->options($options)
|
||||
->paginateRaw(perPage: $perPage, page: $page);
|
||||
|
||||
$data = collect($this->hitsFrom($paginator))
|
||||
->map(fn (array $product) => $this->withLocalizedFields($product))
|
||||
->all();
|
||||
|
||||
return new LengthAwarePaginator(
|
||||
items: $data,
|
||||
total: $paginator->total(),
|
||||
perPage: $paginator->perPage(),
|
||||
currentPage: $paginator->currentPage(),
|
||||
options: ['path' => LengthAwarePaginator::resolveCurrentPath()],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a single product by its URL slug (any locale - slugs are indexed across
|
||||
* all languages, see Modules\Core\Product\Services\ProductIndexer). Returns the full
|
||||
* indexed product document, or null if no product has that slug.
|
||||
*/
|
||||
public function getBySlug(string $slug): ?array
|
||||
{
|
||||
return $this->findOneWhere('slugs = "'.addcslashes($slug, '"\\').'"');
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a single product by its primary key. Returns the full indexed product
|
||||
* document, or null if no product has that id.
|
||||
*/
|
||||
public function getById(int $id): ?array
|
||||
{
|
||||
return $this->findOneWhere("id = \"{$id}\"");
|
||||
}
|
||||
|
||||
private function findOneWhere(string $filter): ?array
|
||||
{
|
||||
$paginator = Product::search('')
|
||||
->options(['filter' => $filter])
|
||||
->paginateRaw(perPage: 1, page: 1);
|
||||
|
||||
$product = $this->hitsFrom($paginator)[0] ?? null;
|
||||
|
||||
return $product !== null ? $this->withLocalizedFields($product) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves every translated Product attribute's current-locale value from the
|
||||
* indexer's per-locale `{handle}_{locale}` fields (e.g. `name_el`, `name_en`,
|
||||
* `seo_title_el`, ...) into a plain `{handle}` key, falling back to the store's
|
||||
* default language (LanguageCache::defaultLocale()) when the current locale
|
||||
* has no translation - e.g. a product with no English copy yet still shows its
|
||||
* Greek name on /en/ rather than rendering blank.
|
||||
*
|
||||
* Which handles are translated is read from AttributeManifest - the same
|
||||
* source Lunar's own ScoutIndexer reads when exploding a TranslatedText
|
||||
* attribute into `{handle}_{locale}` keys at index time - rather than a fixed
|
||||
* list, so a store's own custom translated attributes (e.g. `seo_title`) are
|
||||
* picked up automatically with no change here. The raw per-locale keys are
|
||||
* then stripped, since once resolved, callers only ever need the one that
|
||||
* matched the current locale.
|
||||
*
|
||||
* Deliberately not config('app.locale') - App::setLocale() overwrites that
|
||||
* config value on every request, so by request time it's just whatever the
|
||||
* current locale already is, not a stable fallback.
|
||||
*/
|
||||
private function withLocalizedFields(array $product): array
|
||||
{
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = $this->languages->defaultLocale();
|
||||
$availableLocales = $this->languages->availableLocales();
|
||||
|
||||
foreach ($this->translatedAttributeHandles() as $handle) {
|
||||
$product[$handle] = $product[$handle.'_'.$locale] ?? $product[$handle.'_'.$fallbackLocale] ?? null;
|
||||
|
||||
foreach ($availableLocales as $availableLocale) {
|
||||
unset($product[$handle.'_'.$availableLocale]);
|
||||
}
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function translatedAttributeHandles(): array
|
||||
{
|
||||
return $this->attributes->getSearchableAttributes((new Product)->getMorphClass())
|
||||
->filter(fn ($attribute) => $attribute->type === TranslatedText::class)
|
||||
->pluck('handle')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* For the Meilisearch driver, Scout's paginateRaw() puts the whole raw response
|
||||
* (hits, query, processingTimeMs, ...) in items(), not a plain list of hits - the
|
||||
* actual documents are under the 'hits' key.
|
||||
*/
|
||||
private function hitsFrom(LengthAwarePaginatorContract $paginator): array
|
||||
{
|
||||
$rawResponse = $paginator->items();
|
||||
|
||||
return collect($rawResponse['hits'] ?? [])->values()->all();
|
||||
}
|
||||
|
||||
private function buildFilter(?ProductFilters $filters): ?string
|
||||
{
|
||||
if ($filters === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$clauses = Collection::make([
|
||||
$filters->collectionId !== null ? "collections = \"{$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,
|
||||
])->filter();
|
||||
|
||||
return $clauses->isEmpty() ? null : $clauses->join(' AND ');
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Lunar\Models\ProductOption;
|
||||
use Lunar\Models\ProductOptionValue;
|
||||
use Modules\Core\Product\Observers\ProductOptionReindexObserver;
|
||||
|
||||
class ProductServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function boot(): void
|
||||
{
|
||||
$observer = new ProductOptionReindexObserver;
|
||||
|
||||
ProductOption::saved(fn (ProductOption $option) => $observer->optionSaved($option));
|
||||
ProductOption::deleted(fn (ProductOption $option) => $observer->optionDeleted($option));
|
||||
|
||||
ProductOptionValue::saved(fn (ProductOptionValue $value) => $observer->valueSaved($value));
|
||||
ProductOptionValue::deleted(fn (ProductOptionValue $value) => $observer->valueDeleted($value));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user