| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314 |
- <?php
-
- namespace App\Http\Controllers;
-
- use App\Commerce\BundleStock;
- use App\Enums\ProductStatus;
- use App\Http\Requests\Products\SaveProductRequest;
- use App\Models\BundleItem;
- use App\Models\Product;
- use App\Models\ProductImage;
- use App\Models\ProductVariant;
- use App\Models\Store;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Validation\ValidationException;
- use Inertia\Inertia;
- use Inertia\Response;
-
- /**
- * The merchant's product list for one store.
- * Every lookup goes through the user's own stores, so other people's products give "not found".
- */
- class ProductController extends Controller
- {
- public function index(Request $request, string $slug): Response
- {
- $store = $this->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<array{option1: string, option2: string|null, price: int, compare_at_price: int|null, stock: int}> $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<array{product_id: int, variant_id: int|null, quantity: int}> $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<array{key: string, label: string, price: string, stock: int}>
- */
- 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<int, UploadedFile> $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<string, mixed>
- */
- 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();
- }
- }
|