Feat: Updating Product Service with new Methods, DTOs for ListingResult And Slider Bounds
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\DTOs;
|
||||
|
||||
/**
|
||||
* A price range slider's bounds and whether it's currently narrowed —
|
||||
* built by ProductService::priceSliderBounds(), which owns the floor/ceil
|
||||
* rounding and "is this actually a meaningful filter" comparison, so a
|
||||
* controller (CategoryController, SearchController, ...) doesn't have to
|
||||
* reimplement that rule itself.
|
||||
*/
|
||||
class PriceSliderBounds
|
||||
{
|
||||
public function __construct(
|
||||
public readonly ?int $floor,
|
||||
public readonly ?int $ceil,
|
||||
public readonly bool $filtered,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog\DTOs;
|
||||
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* Everything a listing page needs from one ProductService::list() call —
|
||||
* the product page itself plus the price slider's bounds, so a controller
|
||||
* makes one service call instead of orchestrating list() and
|
||||
* priceSliderBounds() separately. list() still issues two Meilisearch
|
||||
* requests internally (the product search and the price facet stats — see
|
||||
* priceSliderBounds()'s own docblock for why they can't be merged into one
|
||||
* without changing the slider's UX), but that's this DTO's job to hide,
|
||||
* not the controller's to know about.
|
||||
*/
|
||||
class ProductListingResult
|
||||
{
|
||||
public function __construct(
|
||||
public readonly LengthAwarePaginator $products,
|
||||
public readonly PriceSliderBounds $priceBounds,
|
||||
) {}
|
||||
}
|
||||
@@ -9,7 +9,9 @@ use Lunar\Base\AttributeManifest;
|
||||
use Lunar\FieldTypes\TranslatedText;
|
||||
use Lunar\Models\Product;
|
||||
use Modules\Core\Localization\Services\LanguageCache;
|
||||
use Modules\Core\Catalog\DTOs\PriceSliderBounds;
|
||||
use Modules\Core\Catalog\DTOs\ProductFilters;
|
||||
use Modules\Core\Catalog\DTOs\ProductListingResult;
|
||||
use Modules\Core\Catalog\Enums\ProductSort;
|
||||
use Modules\Core\Catalog\Support\ProductFilterBuilder;
|
||||
|
||||
@@ -31,12 +33,27 @@ class ProductService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* One call for everything a listing page needs: the product page AND
|
||||
* the price slider's bounds — a controller used to have to call this
|
||||
* plus priceSliderBounds() separately and glue the results together
|
||||
* itself; that orchestration now happens in here instead. Still issues
|
||||
* two Meilisearch requests under the hood (the product search, and a
|
||||
* separate price-facet-stats query — see priceSliderBounds()'s
|
||||
* docblock for why they can't be merged into one without changing the
|
||||
* slider's own UX), but the caller only ever makes one call.
|
||||
*
|
||||
* $filters->minPrice/$filters->maxPrice double as both the applied
|
||||
* product filter AND the "is the slider actually narrowed" comparison
|
||||
* in priceSliderBounds() — the same values, used two ways, so nothing
|
||||
* new needs to be threaded through separately.
|
||||
*
|
||||
* The paginator itself is 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
|
||||
public function list(?ProductFilters $filters = null, int $perPage = 24, int $page = 1, ?ProductSort $sort = null): ProductListingResult
|
||||
{
|
||||
$options = ['filter' => $this->filterBuilder->build($filters)];
|
||||
|
||||
@@ -52,13 +69,17 @@ class ProductService
|
||||
->map(fn (array $product) => $this->withLocalizedFields($product))
|
||||
->all();
|
||||
|
||||
return new LengthAwarePaginator(
|
||||
$products = new LengthAwarePaginator(
|
||||
items: $data,
|
||||
total: $paginator->total(),
|
||||
perPage: $paginator->perPage(),
|
||||
currentPage: $paginator->currentPage(),
|
||||
options: ['path' => LengthAwarePaginator::resolveCurrentPath()],
|
||||
);
|
||||
|
||||
$priceBounds = $this->priceSliderBounds($filters, $filters?->minPrice, $filters?->maxPrice);
|
||||
|
||||
return new ProductListingResult($products, $priceBounds);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,6 +130,33 @@ class ProductService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* priceRange() rounded to whole euros (floor/ceil, so the slider's ends
|
||||
* are never tighter than what's actually in range) plus whether
|
||||
* $selectedMinPrice/$selectedMaxPrice actually narrow it — the same
|
||||
* "floor/ceil + is this a real filter" rule CategoryController and
|
||||
* SearchController each used to duplicate inline. $selectedMinPrice/
|
||||
* $selectedMaxPrice are the currently-applied filter values (e.g.
|
||||
* CategoryListing::$minPrice), not part of $filters itself, since
|
||||
* $filters here must already exclude price the way priceRange() expects.
|
||||
*/
|
||||
public function priceSliderBounds(
|
||||
?ProductFilters $filters,
|
||||
?float $selectedMinPrice,
|
||||
?float $selectedMaxPrice,
|
||||
string $query = '',
|
||||
): PriceSliderBounds {
|
||||
$priceRange = $this->priceRange($filters, $query);
|
||||
|
||||
$floor = $priceRange['min'] !== null ? (int) floor($priceRange['min']) : null;
|
||||
$ceil = $priceRange['max'] !== null ? (int) ceil($priceRange['max']) : null;
|
||||
|
||||
$filtered = ($selectedMinPrice !== null && $selectedMinPrice > ($floor ?? PHP_INT_MIN))
|
||||
|| ($selectedMaxPrice !== null && $selectedMaxPrice < ($ceil ?? PHP_INT_MAX));
|
||||
|
||||
return new PriceSliderBounds($floor, $ceil, $filtered);
|
||||
}
|
||||
|
||||
private function rawFacets(string $field, ?string $filter, string $query = ''): array
|
||||
{
|
||||
return Product::search($query)
|
||||
@@ -139,15 +187,87 @@ class ProductService
|
||||
return $this->findOneWhere("id = \"{$id}\"");
|
||||
}
|
||||
|
||||
/**
|
||||
* The id/price/image of every variant on a product document (from
|
||||
* getById()/getBySlug()'s own 'variants' array) — the base price and
|
||||
* thumbnail a variant picker/swatch list needs, without a caller
|
||||
* reaching into $product['variants'][n]['prices'][0]/['media'][0]
|
||||
* itself. Domain shaping (which price/image represents a variant),
|
||||
* not presentation — a card's href/layout stays a storefront concern
|
||||
* (e.g. App\Catalog\ProductCard in 3dealer), but "the variant's price
|
||||
* is its first price row" is a rule about the data, true regardless of
|
||||
* which app renders it.
|
||||
*
|
||||
* @param array $product A document from getById()/getBySlug().
|
||||
* @return array<int, array{id: int, price: ?float, image: ?string}>
|
||||
*/
|
||||
public function variantSummaries(array $product): array
|
||||
{
|
||||
return collect($product['variants'] ?? [])
|
||||
->map(fn (array $variant) => [
|
||||
'id' => $variant['id'],
|
||||
'price' => $variant['prices'][0]['price'] ?? null,
|
||||
'image' => $variant['media'][0]['url'] ?? null,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* $limit random products, still scoped to the index's own default
|
||||
* visibility (channel/status), unlike Eloquent's Product::inRandomOrder()
|
||||
* which has no notion of that filtering at all — a random pick can never
|
||||
* surface a hidden/unpublished product this way. Meilisearch itself has
|
||||
* no ORDER BY RANDOM() equivalent, so this pulls every matching id only
|
||||
* (attributesToRetrieve: ['id'], the lightest possible request — no
|
||||
* name/media/variants/etc. for documents that will mostly be discarded),
|
||||
* shuffles in PHP, then fetches the full localized documents for just
|
||||
* the $limit ids actually picked.
|
||||
*
|
||||
* @return array<int, array>
|
||||
*/
|
||||
public function random(int $limit): array
|
||||
{
|
||||
$raw = Product::search('')
|
||||
->options(['attributesToRetrieve' => ['id']])
|
||||
->raw();
|
||||
|
||||
$ids = collect($raw['hits'] ?? [])->pluck('id')->shuffle()->take($limit)->values();
|
||||
|
||||
if ($ids->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Meilisearch's `id IN [...]` doesn't preserve the given order — it's
|
||||
// an unordered set filter, not a list to iterate — so the shuffle
|
||||
// above would otherwise be silently undone by whatever order the
|
||||
// re-fetch comes back in. Re-sort the fetched documents back into
|
||||
// $ids's already-shuffled order instead of trusting the response's.
|
||||
$products = collect($this->findAllWhere('id IN ['.$ids->implode(', ').']'))
|
||||
->keyBy('id');
|
||||
|
||||
return $ids->map(fn ($id) => $products->get($id))->filter()->values()->all();
|
||||
}
|
||||
|
||||
private function findOneWhere(string $filter): ?array
|
||||
{
|
||||
$products = $this->findAllWhere($filter, limit: 1);
|
||||
|
||||
return $products[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array>
|
||||
*/
|
||||
private function findAllWhere(string $filter, int $limit = 1000): array
|
||||
{
|
||||
$paginator = Product::search('')
|
||||
->options(['filter' => $filter])
|
||||
->paginateRaw(perPage: 1, page: 1);
|
||||
->paginateRaw(perPage: $limit, page: 1);
|
||||
|
||||
$product = $this->hitsFrom($paginator)[0] ?? null;
|
||||
|
||||
return $product !== null ? $this->withLocalizedFields($product) : null;
|
||||
return collect($this->hitsFrom($paginator))
|
||||
->map(fn (array $product) => $this->withLocalizedFields($product))
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user