Files
3dealer/app/Http/Controllers/ProductController.php
T
elviraandClaude Opus 5.5 f0a1b928dd Reviews: submit without a redirect, answered with Turbo Streams
The review form now submits through Turbo (data-turbo="true"; Drive
stays off) and storeReview answers with Turbo Streams instead of a
redirect with flashed data:
- success: the new review is prepended to the list (same Blade partial
  as the existing ones), the empty message is removed, the stars/count
  under the title and the tab label are updated (count and average from
  the DB, which is what the index builds them from), the form is removed
  and the thank-you goes into a live region and gets focus
- validation error: 422 + a stream that replaces the form with inline
  errors (aria-invalid/aria-describedby) and the entered values, focus on
  the first invalid field

Nothing on the product page reads the session any more: no
session('reviewSubmitted'), old() or $errors, and
mergeJustSubmittedReview and the justSubmittedReview flash are gone.
searchableSync() stays.

Without JS it's a plain POST that redirects back to ?tab=reviews,
without inline errors or the thank-you, and the new review shows once
Meilisearch catches up. The ?tab=reviews query parameter is noted in
the controller as a variant to handle once product pages are cached.

New: product/partials/review, product/partials/rating-summary,
product/streams/review-stored|review-invalid, and a small
focus-on-connect Stimulus controller that only appears on streamed
markup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:09:58 +02:00

278 lines
11 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Catalog\CollectionTrail;
use App\Catalog\ProductListing;
use App\Catalog\ProductListingPage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Lunar\Models\Product;
use Lunar\Models\ProductVariant;
use Modules\Core\Catalog\Services\CollectionService;
use Modules\Core\Catalog\Services\ProductService;
use Modules\Core\Review\Models\ProductReview;
class ProductController extends Controller
{
public function __construct(
private readonly ProductService $products,
private readonly ProductListingPage $listingPage,
private readonly CollectionService $collections,
private readonly CollectionTrail $trail,
) {}
/**
* All products — the category page without a collection scope. Filters,
* sort, pagination and the shared listing body all work identically.
*/
public function index(string $locale)
{
$listing = ProductListing::fromRequest(request());
$data = $this->listingPage->build(
$listing,
fn (array $query) => route('products', $query),
);
return view('products.index', $data);
}
public function show(string $locale, int $id)
{
$product = $this->products->getById($id);
abort_if($product === null, Response::HTTP_NOT_FOUND);
[$productOptions, $variantsData] = $this->buildOptionPicker($id);
return view('product.show', [
'breadcrumb' => [...$this->collectionTrail($product), ['label' => $product['name']]],
'product' => $product,
'productOptions' => $productOptions,
'variantsData' => $variantsData,
]);
}
/**
* The product's first directly-assigned collection with its ancestors, or
* the all-products page when it has none. The product document's own
* `collections` entries carry neither ancestors nor a current-locale name,
* so the collection is re-read from the collection index.
*
* @return array<int, array{label: string, href?: string}>
*/
private function collectionTrail(array $product): array
{
$assigned = $product['collections'][0] ?? null;
$collection = $assigned !== null ? $this->collections->getById((int) $assigned['id']) : null;
if ($collection === null) {
return [['label' => __('storefront.nav.products'), 'href' => route('products')]];
}
// Untranslated collections resolve to a null name; the product's own
// index-time name is the fallback, same as CollectionTrail's ancestors.
$collection['name'] ??= $assigned['name'];
return $this->trail->for($collection);
}
/**
* One button/swatch group per product option (a product can have several
* — e.g. a custom-photo product with size + style + person-count, each
* combination resolved client-side to one exact ProductVariant, see
* product-form-controller.js) plus the per-variant data the picker
* resolves a selection against.
*
* Reads live Eloquent rather than the Meilisearch-indexed $product array
* the rest of the page uses (same reasoning as checkStock() below): the
* index has no concept of option/value display order (Lunar's
* `position` column) or a stable value id, both of which the picker
* needs — to render values in the merchant's intended order, and to
* match a combination back to one exact variant without relying on
* translated label strings staying unique.
*
* @return array{0: array, 1: array}
*/
private function buildOptionPicker(int $productId): array
{
$variants = ProductVariant::query()
->where('product_id', $productId)
->with(['values.option', 'prices', 'images'])
->get();
$productOptions = $variants
->flatMap(fn (ProductVariant $variant) => $variant->values)
->unique('id')
->groupBy(fn ($value) => $value->option->handle)
->map(function ($values, $handle) {
$sorted = $values->sortBy([['position', 'asc'], ['id', 'asc']]);
return [
'handle' => $handle,
'label' => $sorted->first()->option->translate('name'),
// The "Color" option type is the only one that writes a
// hex code into meta (see boboko/core's ColorOptionType)
// — its presence is how we tell a color option (swatches)
// from any other option (buttons).
'isColor' => $sorted->contains(fn ($v) => !empty($v->meta['hex'] ?? null)),
'values' => $sorted->map(fn ($v) => [
'id' => $v->id,
'label' => $v->translate('name'),
'hex' => $v->meta['hex'] ?? null,
])->values()->all(),
];
})
->values()
->all();
$variantsData = $variants->map(fn (ProductVariant $variant) => [
'id' => $variant->id,
'price' => $variant->prices->first()?->price?->decimal(),
'image' => $variant->images->first()?->getUrl(),
// Live from the DB (not the index's in_stock), with Lunar's own
// purchasability rule — drives the disabled add-to-cart button.
'inStock' => $variant->canBeFulfilledAtQuantity(1),
// handle => selected value id, for matching a combination of
// selections back to this variant — see selectVariant() in
// product-form-controller.js.
'options' => $variant->values->mapWithKeys(fn ($v) => [$v->option->handle => $v->id])->all(),
])->values()->all();
return [$productOptions, $variantsData];
}
/**
* A storefront-owned, checkout-module-independent stock check — the
* product page's "Add to cart" calls this first and only submits to the
* checkout module's own add-to-cart endpoint once this says `ok`. Reads
* the live Eloquent ProductVariant directly (not the Meilisearch index
* ProductService otherwise reads from, which can lag behind an actual
* sale until the next reindex) via the SAME method Lunar's own
* CartLineStock validator calls, so this can never disagree with what
* the module's own server-side check would decide.
*/
public function checkStock(string $locale, Request $request): JsonResponse
{
$data = $request->validate([
'variant' => ['required', 'integer'],
'quantity' => ['nullable', 'integer', 'min:1'],
]);
$variant = ProductVariant::find($data['variant']);
$quantity = $data['quantity'] ?? 1;
if ($variant === null) {
return response()->json(['ok' => true]);
}
return response()->json([
'ok' => $variant->canBeFulfilledAtQuantity($quantity),
'stock' => $variant->purchasable === 'always' ? null : $variant->getTotalInventory(),
]);
}
/**
* boboko/core's product_reviews table has no moderation/status column, so
* this goes live immediately — no approval queue to land in.
*
* The form submits through Turbo, so the answer is Turbo Streams: the new
* review into the list, the updated count and average, the thank-you in
* place of the form; or, on a validation error, the form again with inline
* errors (422). Nothing goes through the session, so the product page
* itself never reads one (it'll be cached). Without JS this is a plain
* POST that redirects back to the product page, losing the inline errors
* and the thank-you — accepted.
*
* The redirect's ?tab=reviews is a query-string variant of the product
* page: keep that in mind once product pages are cached.
*/
public function storeReview(string $locale, Request $request, Product $product): RedirectResponse|Response
{
$wantsStream = str_contains((string) $request->header('Accept'), 'text/vnd.turbo-stream.html');
$validator = Validator::make($request->all(), [
'rating' => ['required', 'integer', 'between:1,5'],
'content' => ['required', 'string'],
'name' => ['nullable', 'string', 'max:255'],
'email' => ['required', 'email'],
]);
if ($validator->fails()) {
return $wantsStream
? $this->turboStream('product.streams.review-invalid', [
'productId' => $product->id,
'messages' => $validator->errors(),
'values' => $request->only('rating', 'content', 'name', 'email'),
], Response::HTTP_UNPROCESSABLE_ENTITY)
: redirect($this->reviewsUrl($locale, $product));
}
$data = $validator->validated();
// Not $product->reviews()->create(...): that relation only exists via a
// Product::macro() registered in CorePlugin::register(Panel $panel), which
// Filament calls solely when the /boboko admin panel boots — never on a
// plain storefront request, where the macro is simply undefined.
$review = ProductReview::create([
'product_id' => $product->id,
'rating' => $data['rating'],
'body' => $data['content'],
'reviewer_name' => $data['name'] ?? null,
'reviewer_email' => $data['email'],
'reviewed_at' => now(),
'source' => 'storefront',
]);
// ReviewServiceProvider also reindexes on the model's `created` event, but
// queued (SCOUT_QUEUE=true). Syncing here skips our queue, so the next
// product page load has it as soon as Meilisearch (itself async) catches
// up. The stream below doesn't wait for the index: it renders the new
// review and the count/average straight from the DB, which is exactly
// what ProductIndexer builds the index's `reviews` from.
$product->searchableSync();
if (! $wantsStream) {
return redirect($this->reviewsUrl($locale, $product));
}
$reviews = ProductReview::where('product_id', $product->id);
return $this->turboStream('product.streams.review-stored', [
// Same shape as ProductIndexer::mapReview(), for the shared partial.
'review' => [
'id' => $review->id,
'title' => $review->title,
'body' => $review->body,
'rating' => $review->rating,
'reviewed_at' => $review->reviewed_at?->timestamp,
'reviewer_name' => $review->reviewer_name,
'reply' => null,
'replied_at' => null,
'media' => [],
],
'count' => (clone $reviews)->count(),
'averageRating' => round((float) (clone $reviews)->avg('rating'), 1),
]);
}
private function reviewsUrl(string $locale, Product $product): string
{
return route('product.show', [
'locale' => $locale,
'id' => $product->id,
'tab' => 'reviews',
]).'#product-tabs';
}
private function turboStream(string $view, array $data, int $status = Response::HTTP_OK): Response
{
return response()
->view($view, $data, $status)
->header('Content-Type', 'text/vnd.turbo-stream.html');
}
}