ownedStore($request, $slug); return Inertia::render('stores/products/index', [ 'store' => $this->presentStore($store), 'products' => $store->products() ->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant']) ->latest('id') ->get() ->map(fn (Product $product) => $this->present($product)), ]); } public function create(Request $request, string $slug): Response { $store = $this->ownedStore($request, $slug); return Inertia::render('stores/products/create', [ 'store' => $this->presentStore($store), 'statuses' => ProductStatus::options(), 'maxImages' => SaveProductRequest::MAX_IMAGES, 'bundleChoices' => $this->bundleChoices($store, null), ]); } public function store(SaveProductRequest $request, string $slug): RedirectResponse { $store = $this->ownedStore($request, $slug); $product = DB::transaction(function () use ($store, $request): Product { $product = $store->products()->make($request->productData()); $product->options = $request->hasOptions() ? $request->optionsData() : null; $product->is_bundle = $request->isBundle(); $product->save(); $this->syncVariants($product, $request->variantsData()); $this->syncBundleItems($product, $request->bundleData()); BundleStock::refresh($store->id); return $product; }); $this->addImages($product, $request->file('images', [])); Inertia::flash('toast', ['type' => 'success', 'message' => __('Product added.')]); return to_route('stores.products.index', $store->slug); } public function edit(Request $request, string $slug, int $product): Response { $store = $this->ownedStore($request, $slug); $product = $this->ownedProduct($store, $product); return Inertia::render('stores/products/edit', [ 'store' => $this->presentStore($store), 'product' => $this->present($product), 'statuses' => ProductStatus::options(), 'maxImages' => SaveProductRequest::MAX_IMAGES, 'bundleChoices' => $this->bundleChoices($store, $product), ]); } public function update(SaveProductRequest $request, string $slug, int $product): RedirectResponse { $store = $this->ownedStore($request, $slug); $product = $this->ownedProduct($store, $product); $files = $request->file('images', []); if ($product->images()->count() + count($files) > SaveProductRequest::MAX_IMAGES) { throw ValidationException::withMessages([ 'images' => 'A product can have at most '.SaveProductRequest::MAX_IMAGES.' photos. Remove one first.', ]); } DB::transaction(function () use ($store, $product, $request): void { $product->fill($request->productData()); $product->options = $request->hasOptions() ? $request->optionsData() : null; $product->is_bundle = $request->isBundle(); $product->save(); $this->syncVariants($product, $request->variantsData()); $this->syncBundleItems($product, $request->bundleData()); BundleStock::refresh($store->id); }); $this->addImages($product, $files); Inertia::flash('toast', ['type' => 'success', 'message' => __('Product saved.')]); return to_route('stores.products.index', $store->slug); } public function destroy(Request $request, string $slug, int $product): RedirectResponse { $store = $this->ownedStore($request, $slug); $product = $this->ownedProduct($store, $product); $use = $product->usedInBundles()->with('bundle')->first(); // Deleting it would quietly empty part of a bundle, so the merchant takes it out first. if ($use !== null) { Inertia::flash('toast', ['type' => 'error', 'message' => __('This product is inside the bundle ":bundle". Take it out of the bundle first.', ['bundle' => $use->bundle->name])]); return back(); } $product->delete(); BundleStock::refresh($store->id); Inertia::flash('toast', ['type' => 'success', 'message' => __('Product deleted.')]); return to_route('stores.products.index', $store->slug); } public function destroyImage(Request $request, string $slug, int $product, int $image): RedirectResponse { $store = $this->ownedStore($request, $slug); $product = $this->ownedProduct($store, $product); $product->images()->whereKey($image)->firstOrFail()->delete(); return back(); } /** * Make the product's variants match the form. A variant whose option values did not change keeps * its id, so carts holding it stay valid; combinations that are gone are removed. * * @param list $rows */ private function syncVariants(Product $product, array $rows): void { $key = fn (?string $first, ?string $second) => mb_strtolower((string) $first).'|'.mb_strtolower((string) $second); $existing = $product->variants()->get()->keyBy(fn (ProductVariant $variant) => $key($variant->option1, $variant->option2)); $kept = []; foreach ($rows as $position => $row) { $variant = $existing->get($key($row['option1'], $row['option2'])) ?? new ProductVariant; $variant->store_id = $product->store_id; $variant->product_id = $product->id; $variant->option1 = $row['option1']; $variant->option2 = $row['option2']; $variant->price = $row['price']; $variant->compare_at_price = $row['compare_at_price']; $variant->stock = $row['stock']; $variant->position = $position; $variant->save(); $kept[] = $variant->id; } $product->variants()->whereNotIn('id', $kept)->delete(); $product->unsetRelation('variants'); } /** * Make the bundle's items match the form. Not a bundle: no items. * * @param list $items */ private function syncBundleItems(Product $product, array $items): void { BundleItem::replaceFor($product, $items); } /** * What a bundle can hold: every product of the store that is not a bundle, and for a product with * options, each of its variants. "key" is how the form names it, like a cart line: "12" or "12-34". * * @return list */ private function bundleChoices(Store $store, ?Product $except): array { $choices = []; $products = $store->products() ->with('variants') ->where('is_bundle', false) ->when($except !== null, fn ($query) => $query->whereKeyNot($except->id)) ->orderBy('name') ->get(); foreach ($products as $product) { if (! $product->hasVariants()) { $choices[] = ['key' => (string) $product->id, 'label' => $product->name, 'price' => self::ringgit($product->price), 'stock' => $product->stock]; continue; } foreach ($product->variants as $variant) { $choices[] = [ 'key' => $product->id.'-'.$variant->id, 'label' => $product->name.' ('.$variant->name().')', 'price' => self::ringgit($variant->price), 'stock' => $variant->stock, ]; } } return $choices; } private static function ringgit(int $sen): string { return number_format($sen / 100, 2, '.', ''); } /** * @param array $files */ private function addImages(Product $product, array $files): void { $position = (int) $product->images()->max('position'); foreach ($files as $file) { $product->images()->create([ 'store_id' => $product->store_id, 'path' => $file->store("products/{$product->store_id}", 'public'), 'position' => ++$position, ]); } } /** * The product fields the dashboard is allowed to see. Prices are in ringgit, as text, such as "12.90". * * @return array */ private function present(Product $product): array { return [ 'id' => $product->id, 'name' => $product->name, 'slug' => $product->slug, 'description' => $product->description, 'price' => number_format($product->price / 100, 2, '.', ''), 'compare_at_price' => $product->compare_at_price !== null ? number_format($product->compare_at_price / 100, 2, '.', '') : null, 'stock' => $product->stock, // Options with their choices as one comma-separated line, the way the form edits them. 'options' => collect($product->options ?? []) ->map(fn (array $option) => ['name' => $option['name'], 'values' => implode(', ', $option['values'])]) ->all(), 'variants' => $product->variants ->map(fn (ProductVariant $variant) => [ 'option1' => $variant->option1, 'option2' => $variant->option2, 'price' => number_format($variant->price / 100, 2, '.', ''), 'compare_at_price' => $variant->compare_at_price !== null ? number_format($variant->compare_at_price / 100, 2, '.', '') : null, 'stock' => $variant->stock, ]) ->all(), 'is_bundle' => $product->isBundle(), 'bundle_items' => $product->bundleItems ->map(fn (BundleItem $item) => [ 'item' => $item->variant_id !== null ? $item->product_id.'-'.$item->variant_id : (string) $item->product_id, 'label' => $item->label(), 'quantity' => $item->quantity, ]) ->all(), 'status' => $product->status->value, 'status_label' => $product->status->label(), 'images' => $product->images ->map(fn (ProductImage $image) => ['id' => $image->id, 'url' => $image->url()]) ->all(), ]; } /** * @return array{name: string, slug: string} */ private function presentStore(Store $store): array { return ['name' => $store->name, 'slug' => $store->slug]; } private function ownedStore(Request $request, string $slug): Store { return $request->user()->stores()->where('slug', $slug)->firstOrFail(); } private function ownedProduct(Store $store, int $id): Product { return $store->products()->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant'])->whereKey($id)->firstOrFail(); } }