|null */ private ?FilterSet $filterSet = null; /** How many related rows a detail-page panel previews before "View all". */ private const RELATION_PREVIEW = 10; /** * Display a listing of the resource. */ #[Authorize('viewAny', Product::class)] public function index(Request $request): Response { $filters = $this->filters($request); $query = $this->filterSet()->apply($filters); $columns = ProductColumns::make(); $perPage = PageSize::from($request, PageSize::SCREEN); $stats = ProductStats::get(); // paginate() already counts, so its total is reused below. $items = $query ->paginate($perPage) ->withQueryString(); TreeOptions::prime(['table' => 'categories', 'display' => 'name', 'tree' => ['parent' => 'parent_id', 'level' => 'level', 'leaf' => 'category', 'name' => 'name']], $items->getCollection()->pluck('category_id')); $items = $items->through(fn (Product $product): array => $columns->tableRow($product)); $total = $items->total(); return Inertia::render('product/index', [ 'items' => $items, 'total' => $total, 'filters' => [...$filters, 'per_page' => $perPage], // Decided server-side: only the server knows who is asking. See Channels. 'realtimeChannel' => Channels::forViewer('product', $request->user()), 'savedViews' => $this->savedViews($request), // What the page may offer, asked of the policy the routes are // guarded by, so a button is shown exactly when its action is allowed. 'abilities' => $this->abilities(), ...ProductFormOptions::get(), 'stats' => $stats, ]); } /** * Get the views the viewer saved for this list. * * @return array */ private function savedViews(Request $request): array { $user = $request->user(); if (! $user instanceof User) { return []; } return $user->userViews() ->forModule('product') ->orderBy('name') ->get(['id', 'name', 'filters']) ->all(); } /** * Display the specified resource. */ #[Authorize('view', 'product')] public function show(Request $request, Product $product): Response { $product->load([ 'publishedByRef:id,name', 'productVariants' => fn (HasMany $query) => $query ->select(['id', 'product_id', 'name', 'sku', 'size', 'color', 'price', 'stock']) ->latest('id') ->limit(self::RELATION_PREVIEW), 'reviews' => fn (HasMany $query) => $query ->select(['id', 'product_id', 'title', 'rating', 'status', 'customer_id']) ->addSelect(['customer_label' => DB::table('customers')->select('name')->whereColumn('customers.id', 'reviews.customer_id')->limit(1)]) ->latest('id') ->limit(self::RELATION_PREVIEW), 'coupons' => fn (MorphMany $query) => $query ->select(['id', 'applies_to_id', 'applies_to_type', 'code', 'description', 'kind', 'percent_off', 'amount_off', 'starts_on']) ->latest('id') ->limit(self::RELATION_PREVIEW), 'tags' => fn (BelongsToMany $query) => $query ->select(['tags.id', 'tags.name']) ->limit(self::RELATION_PREVIEW), ]); return Inertia::render('product/show', [ 'item' => [ 'id' => $product->id, 'category' => TreeOptions::label(['table' => 'categories', 'display' => 'name', 'tree' => ['parent' => 'parent_id', 'level' => 'level', 'leaf' => 'category', 'name' => 'name']], $product->category_id), 'category_id' => $product->category_id, 'name' => $product->name, 'slug' => $product->slug, 'sku' => $product->sku, 'status' => $product->status->value, 'price' => $product->price, 'compare_at_price' => $product->compare_at_price, 'cost_price' => $product->cost_price, 'photos' => $product->photos, 'video_url' => $product->video_url, 'description' => $product->description, 'size_chart' => $product->size_chart, 'is_featured' => $product->is_featured, 'published_at' => $product->published_at?->toIso8601String(), 'publishedByRef' => $product->publishedByRef?->name, 'published_by' => $product->published_by, 'specs' => $product->specs, 'created_at' => $product->created_at?->toIso8601String(), 'updated_at' => $product->updated_at?->toIso8601String(), 'productVariants' => $product->productVariants->map(fn (ProductVariant $item) => [ 'id' => $item->id, 'name' => $item->name, 'sku' => $item->sku, 'size' => $item->size, 'color' => $item->color, 'price' => $item->price, 'stock' => $item->stock, ])->all(), 'reviews' => $product->reviews->map(fn (Review $item) => [ 'id' => $item->id, 'title' => $item->title, 'rating' => $item->rating, 'status' => $item->status, 'customer' => $item->getAttribute('customer_label'), ])->all(), 'coupons' => $product->coupons->map(fn (Coupon $item) => [ 'id' => $item->id, 'code' => $item->code, 'description' => $item->description, 'kind' => $item->kind, 'percent_off' => $item->percent_off, 'amount_off' => $item->amount_off, 'starts_on' => $item->starts_on, ])->all(), 'tags' => $product->tags->map(fn (Tag $item) => [ 'id' => $item->id, 'name' => $item->name, ])->all(), ], 'timeline' => Timeline::for($product, $this->actor($request)), 'abilities' => $this->recordAbilities($product), ...ProductFormOptions::get(), 'productVariantsFormOptions' => ProductVariantFormOptions::get(), 'reviewsFormOptions' => ReviewFormOptions::get(), ]); } /** The viewer the audit timeline is shown to, or null for a guest. */ private function actor(Request $request): ?User { $user = $request->user(); return $user instanceof User ? $user : null; } /** * Store a newly created resource in storage. */ #[Authorize('create', Product::class)] public function store(StoreProductRequest $request, StoreProduct $action): RedirectResponse { $action->handle($request->validated(), $this->uploadedPhotos($request), $this->uploadedSizeChart($request)); Inertia::flash('toast', ['type' => 'success', 'message' => __('crud.created')]); return back(); } /** * Update the specified resource in storage. */ #[Authorize('update', 'product')] public function update(UpdateProductRequest $request, Product $product, UpdateProduct $action): RedirectResponse { // A save from a stale copy would revert what another editor changed, so // the action compares `_version` under a row lock and refuses it whole. // The form holds every list, but a browser leaves an emptied one out // of a multipart body: here an absent list means none are left. $data = $request->validated() + ['tag_ids' => [], 'photos_existing' => []]; if (! $this->canEditRestricted()) { unset($data['price']); } $action->handle($product, $data, $this->uploadedPhotos($request), $this->uploadedSizeChart($request), expected: RecordVersion::submitted($request)); Inertia::flash('toast', ['type' => 'success', 'message' => __('crud.updated')]); return back(); } /** * Remove the specified resource from storage. */ #[Authorize('delete', 'product')] public function destroy(Product $product, DeleteProduct $action): RedirectResponse { $action->handle($product); Inertia::flash('toast', ['type' => 'success', 'message' => __('crud.deleted')]); return to_route('product.index'); } /** * The normalized filters, echoed back so the toolbar stays in sync with the URL. * * @return array */ private function filters(Request $request): array { return FilteredProducts::fromRequest($request); } /** * Get the filters and sorts the list understands. * * @return FilterSet */ private function filterSet(): FilterSet { return $this->filterSet ??= FilteredProducts::set(); } /** * What the list may offer this viewer, from the policy the routes ask. * * @return array */ private function abilities(): array { return [ 'export' => Gate::allows('export', Product::class), 'create' => Gate::allows('create', Product::class), 'import' => Gate::allows('import', Product::class), 'update' => Gate::allows('updateAny', Product::class), 'updateRestricted' => Gate::allows('updateRestricted', Product::class), 'delete' => Gate::allows('deleteAny', Product::class), 'restore' => Gate::allows('restoreAny', Product::class), 'forceDelete' => Gate::allows('forceDeleteAny', Product::class), ]; } /** * What this record's page may offer: the same policy, asked about the record. * * @return array */ private function recordAbilities(Product $product): array { return [ 'update' => Gate::allows('update', $product), 'updateRestricted' => Gate::allows('updateRestricted', Product::class), 'delete' => Gate::allows('delete', $product), ]; } /** * Whether the current user may change this module's restricted fields. */ private function canEditRestricted(): bool { return Gate::allows('updateRestricted', Product::class); } /** * Get the files uploaded for the field, in the order they were sent. * * @return list */ private function uploadedPhotos(Request $request): array { return array_values(array_filter( (array) $request->file('photos_new', []), static fn (mixed $file): bool => $file instanceof UploadedFile, )); } private function uploadedSizeChart(Request $request): ?UploadedFile { $file = $request->file('size_chart'); return $file instanceof UploadedFile ? $file : null; } }