AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProductController.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commerce\BundleStock;
  4. use App\Enums\ProductStatus;
  5. use App\Http\Requests\Products\SaveProductRequest;
  6. use App\Models\BundleItem;
  7. use App\Models\Collection;
  8. use App\Models\Product;
  9. use App\Models\ProductImage;
  10. use App\Models\ProductVariant;
  11. use App\Models\Store;
  12. use Illuminate\Http\RedirectResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Http\UploadedFile;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Validation\ValidationException;
  17. use Inertia\Inertia;
  18. use Inertia\Response;
  19. /**
  20. * The merchant's product list for one store.
  21. * Every lookup goes through the user's own stores, so other people's products give "not found".
  22. */
  23. class ProductController extends Controller
  24. {
  25. public function index(Request $request, string $slug): Response
  26. {
  27. $store = $this->ownedStore($request, $slug);
  28. return Inertia::render('stores/products/index', [
  29. 'store' => $this->presentStore($store),
  30. 'products' => $store->products()
  31. ->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant'])
  32. ->latest('id')
  33. ->get()
  34. ->map(fn (Product $product) => $this->present($product)),
  35. 'collections' => $store->collections()->withCount('products')->get()
  36. ->map(fn (Collection $collection) => [
  37. 'id' => $collection->id,
  38. 'name' => $collection->name,
  39. 'slug' => $collection->slug,
  40. 'products_count' => (int) $collection->getAttribute('products_count'),
  41. ]),
  42. ]);
  43. }
  44. public function create(Request $request, string $slug): Response
  45. {
  46. $store = $this->ownedStore($request, $slug);
  47. return Inertia::render('stores/products/create', [
  48. 'store' => $this->presentStore($store),
  49. 'statuses' => ProductStatus::options(),
  50. 'maxImages' => SaveProductRequest::MAX_IMAGES,
  51. 'bundleChoices' => $this->bundleChoices($store, null),
  52. ]);
  53. }
  54. public function store(SaveProductRequest $request, string $slug): RedirectResponse
  55. {
  56. $store = $this->ownedStore($request, $slug);
  57. $product = DB::transaction(function () use ($store, $request): Product {
  58. $product = $store->products()->make($request->productData());
  59. $product->options = $request->hasOptions() ? $request->optionsData() : null;
  60. $product->is_bundle = $request->isBundle();
  61. $product->save();
  62. $this->syncVariants($product, $request->variantsData());
  63. $this->syncBundleItems($product, $request->bundleData());
  64. BundleStock::refresh($store->id);
  65. return $product;
  66. });
  67. $this->addImages($product, $request->file('images', []));
  68. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product added.')]);
  69. return to_route('stores.products.index', $store->slug);
  70. }
  71. public function edit(Request $request, string $slug, int $product): Response
  72. {
  73. $store = $this->ownedStore($request, $slug);
  74. $product = $this->ownedProduct($store, $product);
  75. return Inertia::render('stores/products/edit', [
  76. 'store' => $this->presentStore($store),
  77. 'product' => $this->present($product),
  78. 'statuses' => ProductStatus::options(),
  79. 'maxImages' => SaveProductRequest::MAX_IMAGES,
  80. 'bundleChoices' => $this->bundleChoices($store, $product),
  81. ]);
  82. }
  83. public function update(SaveProductRequest $request, string $slug, int $product): RedirectResponse
  84. {
  85. $store = $this->ownedStore($request, $slug);
  86. $product = $this->ownedProduct($store, $product);
  87. $files = $request->file('images', []);
  88. if ($product->images()->count() + count($files) > SaveProductRequest::MAX_IMAGES) {
  89. throw ValidationException::withMessages([
  90. 'images' => 'A product can have at most '.SaveProductRequest::MAX_IMAGES.' photos. Remove one first.',
  91. ]);
  92. }
  93. DB::transaction(function () use ($store, $product, $request): void {
  94. $product->fill($request->productData());
  95. $product->options = $request->hasOptions() ? $request->optionsData() : null;
  96. $product->is_bundle = $request->isBundle();
  97. $product->save();
  98. $this->syncVariants($product, $request->variantsData());
  99. $this->syncBundleItems($product, $request->bundleData());
  100. BundleStock::refresh($store->id);
  101. });
  102. $this->addImages($product, $files);
  103. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product saved.')]);
  104. return to_route('stores.products.index', $store->slug);
  105. }
  106. public function destroy(Request $request, string $slug, int $product): RedirectResponse
  107. {
  108. $store = $this->ownedStore($request, $slug);
  109. $product = $this->ownedProduct($store, $product);
  110. $use = $product->usedInBundles()->with('bundle')->first();
  111. // Deleting it would quietly empty part of a bundle, so the merchant takes it out first.
  112. if ($use !== null) {
  113. Inertia::flash('toast', ['type' => 'error', 'message' => __('This product is inside the bundle ":bundle". Take it out of the bundle first.', ['bundle' => $use->bundle->name])]);
  114. return back();
  115. }
  116. $product->delete();
  117. BundleStock::refresh($store->id);
  118. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product deleted.')]);
  119. return to_route('stores.products.index', $store->slug);
  120. }
  121. public function destroyImage(Request $request, string $slug, int $product, int $image): RedirectResponse
  122. {
  123. $store = $this->ownedStore($request, $slug);
  124. $product = $this->ownedProduct($store, $product);
  125. $product->images()->whereKey($image)->firstOrFail()->delete();
  126. return back();
  127. }
  128. /**
  129. * Make the product's variants match the form. A variant whose option values did not change keeps
  130. * its id, so carts holding it stay valid; combinations that are gone are removed.
  131. *
  132. * @param list<array{option1: string, option2: string|null, price: int, compare_at_price: int|null, stock: int}> $rows
  133. */
  134. private function syncVariants(Product $product, array $rows): void
  135. {
  136. $key = fn (?string $first, ?string $second) => mb_strtolower((string) $first).'|'.mb_strtolower((string) $second);
  137. $existing = $product->variants()->get()->keyBy(fn (ProductVariant $variant) => $key($variant->option1, $variant->option2));
  138. $kept = [];
  139. foreach ($rows as $position => $row) {
  140. $variant = $existing->get($key($row['option1'], $row['option2'])) ?? new ProductVariant;
  141. $variant->store_id = $product->store_id;
  142. $variant->product_id = $product->id;
  143. $variant->option1 = $row['option1'];
  144. $variant->option2 = $row['option2'];
  145. $variant->price = $row['price'];
  146. $variant->compare_at_price = $row['compare_at_price'];
  147. $variant->stock = $row['stock'];
  148. $variant->position = $position;
  149. $variant->save();
  150. $kept[] = $variant->id;
  151. }
  152. $product->variants()->whereNotIn('id', $kept)->delete();
  153. $product->unsetRelation('variants');
  154. }
  155. /**
  156. * Make the bundle's items match the form. Not a bundle: no items.
  157. *
  158. * @param list<array{product_id: int, variant_id: int|null, quantity: int}> $items
  159. */
  160. private function syncBundleItems(Product $product, array $items): void
  161. {
  162. BundleItem::replaceFor($product, $items);
  163. }
  164. /**
  165. * What a bundle can hold: every product of the store that is not a bundle, and for a product with
  166. * options, each of its variants. "key" is how the form names it, like a cart line: "12" or "12-34".
  167. *
  168. * @return list<array{key: string, label: string, price: string, stock: int}>
  169. */
  170. private function bundleChoices(Store $store, ?Product $except): array
  171. {
  172. $choices = [];
  173. $products = $store->products()
  174. ->with('variants')
  175. ->where('is_bundle', false)
  176. ->when($except !== null, fn ($query) => $query->whereKeyNot($except->id))
  177. ->orderBy('name')
  178. ->get();
  179. foreach ($products as $product) {
  180. if (! $product->hasVariants()) {
  181. $choices[] = ['key' => (string) $product->id, 'label' => $product->name, 'price' => self::ringgit($product->price), 'stock' => $product->stock];
  182. continue;
  183. }
  184. foreach ($product->variants as $variant) {
  185. $choices[] = [
  186. 'key' => $product->id.'-'.$variant->id,
  187. 'label' => $product->name.' ('.$variant->name().')',
  188. 'price' => self::ringgit($variant->price),
  189. 'stock' => $variant->stock,
  190. ];
  191. }
  192. }
  193. return $choices;
  194. }
  195. private static function ringgit(int $sen): string
  196. {
  197. return number_format($sen / 100, 2, '.', '');
  198. }
  199. /**
  200. * @param array<int, UploadedFile> $files
  201. */
  202. private function addImages(Product $product, array $files): void
  203. {
  204. $position = (int) $product->images()->max('position');
  205. foreach ($files as $file) {
  206. $product->images()->create([
  207. 'store_id' => $product->store_id,
  208. 'path' => $file->store("products/{$product->store_id}", 'public'),
  209. 'position' => ++$position,
  210. ]);
  211. }
  212. }
  213. /**
  214. * The product fields the dashboard is allowed to see. Prices are in ringgit, as text, such as "12.90".
  215. *
  216. * @return array<string, mixed>
  217. */
  218. private function present(Product $product): array
  219. {
  220. return [
  221. 'id' => $product->id,
  222. 'name' => $product->name,
  223. 'slug' => $product->slug,
  224. 'description' => $product->description,
  225. 'details' => $product->details ?? [],
  226. 'price' => number_format($product->price / 100, 2, '.', ''),
  227. 'compare_at_price' => $product->compare_at_price !== null
  228. ? number_format($product->compare_at_price / 100, 2, '.', '')
  229. : null,
  230. 'stock' => $product->stock,
  231. // Options with their choices as one comma-separated line, the way the form edits them.
  232. 'options' => collect($product->options ?? [])
  233. ->map(fn (array $option) => ['name' => $option['name'], 'values' => implode(', ', $option['values'])])
  234. ->all(),
  235. 'variants' => $product->variants
  236. ->map(fn (ProductVariant $variant) => [
  237. 'option1' => $variant->option1,
  238. 'option2' => $variant->option2,
  239. 'price' => number_format($variant->price / 100, 2, '.', ''),
  240. 'compare_at_price' => $variant->compare_at_price !== null
  241. ? number_format($variant->compare_at_price / 100, 2, '.', '')
  242. : null,
  243. 'stock' => $variant->stock,
  244. ])
  245. ->all(),
  246. 'is_bundle' => $product->isBundle(),
  247. 'bundle_items' => $product->bundleItems
  248. ->map(fn (BundleItem $item) => [
  249. 'item' => $item->variant_id !== null ? $item->product_id.'-'.$item->variant_id : (string) $item->product_id,
  250. 'label' => $item->label(),
  251. 'quantity' => $item->quantity,
  252. ])
  253. ->all(),
  254. 'status' => $product->status->value,
  255. 'status_label' => $product->status->label(),
  256. 'images' => $product->images
  257. ->map(fn (ProductImage $image) => ['id' => $image->id, 'url' => $image->url()])
  258. ->all(),
  259. ];
  260. }
  261. /**
  262. * @return array{name: string, slug: string}
  263. */
  264. private function presentStore(Store $store): array
  265. {
  266. return ['name' => $store->name, 'slug' => $store->slug];
  267. }
  268. private function ownedStore(Request $request, string $slug): Store
  269. {
  270. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  271. }
  272. private function ownedProduct(Store $store, int $id): Product
  273. {
  274. return $store->products()->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant'])->whereKey($id)->firstOrFail();
  275. }
  276. }