AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ProductController.php 12KB

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