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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Enums\ProductStatus;
  4. use App\Http\Requests\Products\SaveProductRequest;
  5. use App\Models\Product;
  6. use App\Models\ProductImage;
  7. use App\Models\ProductVariant;
  8. use App\Models\Store;
  9. use Illuminate\Http\RedirectResponse;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Http\UploadedFile;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Validation\ValidationException;
  14. use Inertia\Inertia;
  15. use Inertia\Response;
  16. /**
  17. * The merchant's product list for one store.
  18. * Every lookup goes through the user's own stores, so other people's products give "not found".
  19. */
  20. class ProductController extends Controller
  21. {
  22. public function index(Request $request, string $slug): Response
  23. {
  24. $store = $this->ownedStore($request, $slug);
  25. return Inertia::render('stores/products/index', [
  26. 'store' => $this->presentStore($store),
  27. 'products' => $store->products()
  28. ->with(['images', 'variants'])
  29. ->latest('id')
  30. ->get()
  31. ->map(fn (Product $product) => $this->present($product)),
  32. ]);
  33. }
  34. public function create(Request $request, string $slug): Response
  35. {
  36. return Inertia::render('stores/products/create', [
  37. 'store' => $this->presentStore($this->ownedStore($request, $slug)),
  38. 'statuses' => ProductStatus::options(),
  39. 'maxImages' => SaveProductRequest::MAX_IMAGES,
  40. ]);
  41. }
  42. public function store(SaveProductRequest $request, string $slug): RedirectResponse
  43. {
  44. $store = $this->ownedStore($request, $slug);
  45. $product = DB::transaction(function () use ($store, $request): Product {
  46. $product = $store->products()->make($request->productData());
  47. $product->options = $request->hasOptions() ? $request->optionsData() : null;
  48. $product->save();
  49. $this->syncVariants($product, $request->variantsData());
  50. return $product;
  51. });
  52. $this->addImages($product, $request->file('images', []));
  53. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product added.')]);
  54. return to_route('stores.products.index', $store->slug);
  55. }
  56. public function edit(Request $request, string $slug, int $product): Response
  57. {
  58. $store = $this->ownedStore($request, $slug);
  59. return Inertia::render('stores/products/edit', [
  60. 'store' => $this->presentStore($store),
  61. 'product' => $this->present($this->ownedProduct($store, $product)),
  62. 'statuses' => ProductStatus::options(),
  63. 'maxImages' => SaveProductRequest::MAX_IMAGES,
  64. ]);
  65. }
  66. public function update(SaveProductRequest $request, string $slug, int $product): RedirectResponse
  67. {
  68. $store = $this->ownedStore($request, $slug);
  69. $product = $this->ownedProduct($store, $product);
  70. $files = $request->file('images', []);
  71. if ($product->images()->count() + count($files) > SaveProductRequest::MAX_IMAGES) {
  72. throw ValidationException::withMessages([
  73. 'images' => 'A product can have at most '.SaveProductRequest::MAX_IMAGES.' photos. Remove one first.',
  74. ]);
  75. }
  76. DB::transaction(function () use ($product, $request): void {
  77. $product->fill($request->productData());
  78. $product->options = $request->hasOptions() ? $request->optionsData() : null;
  79. $product->save();
  80. $this->syncVariants($product, $request->variantsData());
  81. });
  82. $this->addImages($product, $files);
  83. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product saved.')]);
  84. return to_route('stores.products.index', $store->slug);
  85. }
  86. public function destroy(Request $request, string $slug, int $product): RedirectResponse
  87. {
  88. $store = $this->ownedStore($request, $slug);
  89. $this->ownedProduct($store, $product)->delete();
  90. Inertia::flash('toast', ['type' => 'success', 'message' => __('Product deleted.')]);
  91. return to_route('stores.products.index', $store->slug);
  92. }
  93. public function destroyImage(Request $request, string $slug, int $product, int $image): RedirectResponse
  94. {
  95. $store = $this->ownedStore($request, $slug);
  96. $product = $this->ownedProduct($store, $product);
  97. $product->images()->whereKey($image)->firstOrFail()->delete();
  98. return back();
  99. }
  100. /**
  101. * Make the product's variants match the form. A variant whose option values did not change keeps
  102. * its id, so carts holding it stay valid; combinations that are gone are removed.
  103. *
  104. * @param list<array{option1: string, option2: string|null, price: int, compare_at_price: int|null, stock: int}> $rows
  105. */
  106. private function syncVariants(Product $product, array $rows): void
  107. {
  108. $key = fn (?string $first, ?string $second) => mb_strtolower((string) $first).'|'.mb_strtolower((string) $second);
  109. $existing = $product->variants()->get()->keyBy(fn (ProductVariant $variant) => $key($variant->option1, $variant->option2));
  110. $kept = [];
  111. foreach ($rows as $position => $row) {
  112. $variant = $existing->get($key($row['option1'], $row['option2'])) ?? new ProductVariant;
  113. $variant->store_id = $product->store_id;
  114. $variant->product_id = $product->id;
  115. $variant->option1 = $row['option1'];
  116. $variant->option2 = $row['option2'];
  117. $variant->price = $row['price'];
  118. $variant->compare_at_price = $row['compare_at_price'];
  119. $variant->stock = $row['stock'];
  120. $variant->position = $position;
  121. $variant->save();
  122. $kept[] = $variant->id;
  123. }
  124. $product->variants()->whereNotIn('id', $kept)->delete();
  125. $product->unsetRelation('variants');
  126. }
  127. /**
  128. * @param array<int, UploadedFile> $files
  129. */
  130. private function addImages(Product $product, array $files): void
  131. {
  132. $position = (int) $product->images()->max('position');
  133. foreach ($files as $file) {
  134. $product->images()->create([
  135. 'store_id' => $product->store_id,
  136. 'path' => $file->store("products/{$product->store_id}", 'public'),
  137. 'position' => ++$position,
  138. ]);
  139. }
  140. }
  141. /**
  142. * The product fields the dashboard is allowed to see. Prices are in ringgit, as text, such as "12.90".
  143. *
  144. * @return array<string, mixed>
  145. */
  146. private function present(Product $product): array
  147. {
  148. return [
  149. 'id' => $product->id,
  150. 'name' => $product->name,
  151. 'slug' => $product->slug,
  152. 'description' => $product->description,
  153. 'price' => number_format($product->price / 100, 2, '.', ''),
  154. 'compare_at_price' => $product->compare_at_price !== null
  155. ? number_format($product->compare_at_price / 100, 2, '.', '')
  156. : null,
  157. 'stock' => $product->stock,
  158. // Options with their choices as one comma-separated line, the way the form edits them.
  159. 'options' => collect($product->options ?? [])
  160. ->map(fn (array $option) => ['name' => $option['name'], 'values' => implode(', ', $option['values'])])
  161. ->all(),
  162. 'variants' => $product->variants
  163. ->map(fn (ProductVariant $variant) => [
  164. 'option1' => $variant->option1,
  165. 'option2' => $variant->option2,
  166. 'price' => number_format($variant->price / 100, 2, '.', ''),
  167. 'compare_at_price' => $variant->compare_at_price !== null
  168. ? number_format($variant->compare_at_price / 100, 2, '.', '')
  169. : null,
  170. 'stock' => $variant->stock,
  171. ])
  172. ->all(),
  173. 'status' => $product->status->value,
  174. 'status_label' => $product->status->label(),
  175. 'images' => $product->images
  176. ->map(fn (ProductImage $image) => ['id' => $image->id, 'url' => $image->url()])
  177. ->all(),
  178. ];
  179. }
  180. /**
  181. * @return array{name: string, slug: string}
  182. */
  183. private function presentStore(Store $store): array
  184. {
  185. return ['name' => $store->name, 'slug' => $store->slug];
  186. }
  187. private function ownedStore(Request $request, string $slug): Store
  188. {
  189. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  190. }
  191. private function ownedProduct(Store $store, int $id): Product
  192. {
  193. return $store->products()->with(['images', 'variants'])->whereKey($id)->firstOrFail();
  194. }
  195. }