Parcourir la source

Add product bundles

- Bundles of other products at one price, stock taken from the items inside
- "What's inside" on the product page
- Paying lowers each item's stock; checkout checks shared stock
- Order page shows what to pack
feature/bundles
fahmisaad il y a 3 jours
Parent
révision
b857c5aead

+ 15
- 3
PROGRESS.md Voir le fichier

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-16
7
-**Current step:** Step 8 — Discounts and product options (discount codes and product variants done; next: bundles)
8
-**Next action:** Merge `feature/discount-codes`, then `feature/product-variants` (built on top of it), into `main`. Then build bundles with linked stock. Step 7 part 2 still waits for an EasyParcel API key
7
+**Current step:** Step 8 — Discounts and product options (discount codes, product variants and bundles done; next: chat commands)
8
+**Next action:** Merge `feature/bundles` into `main`. Then build chat commands for products, discounts and bundles, with a confirm step. Step 7 part 2 still waits for an EasyParcel API key
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -153,6 +153,16 @@ Changing from Claude to another AI model (or back) must be a settings change, no
153 153
 - Editing a product keeps variants whose choices did not change, so carts holding them stay valid. Combinations that disappear are removed.
154 154
 - Limits: 2 options, 20 choices per option, 50 combinations.
155 155
 
156
+### How bundles work (added in Step 8)
157
+
158
+- A bundle is a product with `is_bundle` on. `bundle_items` lists what is inside: a product (and, for a product with options, one variant) and how many.
159
+- A bundle has its own price (and optional "price before discount"), but no stock of its own. Its stock is how many times the items allow, for example 10 sambal ÷ 2 and 3 kerepek ÷ 1 gives 3. `BundleStock::refresh()` saves that number on the bundle whenever stock in the store changes (product saved or deleted, order paid), so lists, cards and the cart read it like any other product.
160
+- A bundle cannot hold itself, another bundle, or a product of another store. A product with options must name one of its variants. Up to 10 items, up to 20 of each.
161
+- Products inside a bundle are protected: they cannot be deleted, become a bundle, gain or lose options, or lose a choice the bundle holds. The merchant takes them out of the bundle first.
162
+- At checkout, a bundle and the same items bought on their own are checked together against the stock.
163
+- Each order line for a bundle keeps `bundle_contents` (what was inside at the time). Paying lowers the stock of those items. The merchant's order page shows "Each has: 1 × Cleanser, 1 × Moisturiser (50ml)" for packing.
164
+- The product form shows "Bought one by one: RM X" and how many bundles can be sold, to help set the price. The storefront product page shows "What's inside" with links to the items.
165
+
156 166
 ### How the featured product section works (fixed in Step 7)
157 167
 
158 168
 - A `featured_product` section may hold `productSlug`: the web-address name of one of the store's active products. Product web-address names never change, even when a product is renamed, so the link stays good.
@@ -279,7 +289,7 @@ Agreed on 2026-11-15. Build in this order. It comes after Step 7 because automat
279 289
 
280 290
 - [x] Discount codes (done 2026-11-16): "Discounts" tab for the merchant (code, percent or fixed amount off, optional minimum spend, first and last day, number of uses, on or off); a "Discount code" box in the cart; the order records the code and the amount taken off; Stripe shows the code and the saving. Tested with a real Stripe test payment: RM 42.00 − 20% (RM 8.40) + RM 8.00 shipping = RM 41.60
281 291
 - [x] Product variants (done 2026-11-16): up to 2 options per product (such as Size and Flavour), with a price, "price before discount" and stock for every combination. Shoppers pick with buttons on the product page; sold-out choices are crossed out. Each choice is its own cart line, order line and stock count. Tested with a real Stripe test payment
282
-- [ ] Bundles with linked stock: a product made of other products, with one bundle price. The product page shows what is included and the saving. Selling a bundle lowers the stock of each item in it, and a bundle is sold out when any item is sold out
292
+- [x] Bundles with linked stock (done 2026-11-16): a product made of other products, with one bundle price. The product page shows what is included and the saving ("price before discount" crossed out). Selling a bundle lowers the stock of each item in it, and a bundle is sold out when any item is sold out. Tested with a real Stripe test payment
283 293
 - [ ] Chat commands for products, discounts and bundles ("create a bundle of the cleanser and moisturiser for RM 85", "make a 10% code RAYA10"). The AI turns the sentence into an action, the app shows a confirmation, and nothing changes until the merchant confirms
284 294
 - [ ] Later: automatic discounts ("buy 2, get 10% off", "free shipping over RM 100")
285 295
 
@@ -381,6 +391,7 @@ Then, from the project folder:
381 391
 | Discount in the cart and checkout      | `Cart::applyCode` and `Cart::discount`, `Checkout::placeOrder`                                                                                |
382 392
 | Product variants                       | `app/Models/ProductVariant.php`, `SaveProductRequest`, `ProductController::syncVariants`, `resources/js/components/stores/variant-editor.tsx` |
383 393
 | Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                                            |
394
+| Bundles                                | `app/Models/BundleItem.php`, `app/Commerce/BundleStock.php`, `resources/js/components/stores/bundle-editor.tsx`                               |
384 395
 | Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                             |
385 396
 | Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                            |
386 397
 | Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                   |
@@ -450,3 +461,4 @@ Add one line per work session: date, what was done, what is next.
450 461
 | 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                          | Merge branches, then Step 7 part 2 or Step 8                    |
451 462
 | 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                      | Merge, then product variants                                    |
452 463
 | 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                           | Merge both branches, then bundles                               |
464
+| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                            | Merge, then chat commands                                       |

+ 13
- 12
README.md Voir le fichier

@@ -10,18 +10,18 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
10 10
 
11 11
 ## Current status
12 12
 
13
-| Step | What                                                    | Status                                                         |
14
-| ---- | ------------------------------------------------------- | -------------------------------------------------------------- |
15
-| 0    | Prepare the local machine                               | Done                                                           |
16
-| 1    | Project foundation: login, create a store, dashboard    | Done                                                           |
17
-| 2    | Store sections, renderer and preview                    | Done                                                           |
18
-| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                           |
19
-| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                           |
20
-| 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting            |
21
-| 6    | Our own subscription billing                            | Done                                                           |
22
-| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Part 1 done (shipping fees, WhatsApp); EasyParcel and FPX next |
23
-| 8    | Discounts and product options: codes, variants, bundles | In progress: codes and variants done; bundles next             |
24
-| 9    | Before launch: hosting, legal pages, backups            | Not started                                                    |
13
+| Step | What                                                    | Status                                                            |
14
+| ---- | ------------------------------------------------------- | ----------------------------------------------------------------- |
15
+| 0    | Prepare the local machine                               | Done                                                              |
16
+| 1    | Project foundation: login, create a store, dashboard    | Done                                                              |
17
+| 2    | Store sections, renderer and preview                    | Done                                                              |
18
+| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                              |
19
+| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                              |
20
+| 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting               |
21
+| 6    | Our own subscription billing                            | Done                                                              |
22
+| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Part 1 done (shipping fees, WhatsApp); EasyParcel and FPX next    |
23
+| 8    | Discounts and product options: codes, variants, bundles | In progress: codes, variants and bundles done; chat commands next |
24
+| 9    | Before launch: hosting, legal pages, backups            | Not started                                                       |
25 25
 
26 26
 ## What works today
27 27
 
@@ -39,6 +39,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
39 39
 - A `fake` AI provider that needs no API key, for development and tests
40 40
 - Products: add, edit, delete, up to 5 photos, price, stock, draft or active
41 41
 - Product options such as Size and Flavour, each choice with its own price and stock
42
+- Bundles: several products sold together at one price, with stock taken from the products inside
42 43
 - A Shop page with all products and a page for each product, in the store's design
43 44
 - The home page shows the merchant's real products, with a "View all" button
44 45
 - Cart: add products, change quantities, remove items, see the subtotal. No account needed

+ 50
- 0
app/Commerce/BundleStock.php Voir le fichier

@@ -0,0 +1,50 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Models\BundleItem;
6
+use App\Models\Product;
7
+
8
+/**
9
+ * A bundle has no stock of its own. It can be sold as many times as the items inside it allow:
10
+ * a bundle of 2 sambal and 1 kerepek, with 10 sambal and 3 kerepek left, has 3 left (10 ÷ 2 = 5, 3 ÷ 1 = 3).
11
+ *
12
+ * The answer is saved on the bundle's own stock column, so lists, cards and the cart read it like any
13
+ * other product. Call refresh() whenever stock in the store changes.
14
+ */
15
+class BundleStock
16
+{
17
+    /**
18
+     * Work out the stock of every bundle in one store again.
19
+     */
20
+    public static function refresh(int $storeId): void
21
+    {
22
+        Product::query()
23
+            ->where('store_id', $storeId)
24
+            ->where('is_bundle', true)
25
+            ->with(['bundleItems.product', 'bundleItems.variant'])
26
+            ->get()
27
+            ->each(function (Product $bundle): void {
28
+                $stock = self::for($bundle);
29
+
30
+                if ($bundle->stock !== $stock) {
31
+                    $bundle->stock = $stock;
32
+                    $bundle->saveQuietly();
33
+                }
34
+            });
35
+    }
36
+
37
+    /**
38
+     * How many of this bundle can be sold now.
39
+     */
40
+    public static function for(Product $bundle): int
41
+    {
42
+        if ($bundle->bundleItems->isEmpty()) {
43
+            return 0;
44
+        }
45
+
46
+        return (int) $bundle->bundleItems
47
+            ->map(fn (BundleItem $item) => intdiv(max(0, $item->stock()), max(1, $item->quantity)))
48
+            ->min();
49
+    }
50
+}

+ 1
- 1
app/Commerce/Cart.php Voir le fichier

@@ -224,7 +224,7 @@ class Cart
224 224
 
225 225
         $products = $this->store->products()
226 226
             ->active()
227
-            ->with(['images', 'variants'])
227
+            ->with(Product::STOREFRONT_RELATIONS)
228 228
             ->whereKey($productIds)
229 229
             ->get()
230 230
             ->keyBy('id');

+ 89
- 16
app/Commerce/Checkout.php Voir le fichier

@@ -6,6 +6,7 @@ use App\Commerce\Payments\PaymentStatus;
6 6
 use App\Commerce\Shipping\ShippingProvider;
7 7
 use App\Enums\OrderStatus;
8 8
 use App\Mail\OrderConfirmation;
9
+use App\Models\BundleItem;
9 10
 use App\Models\DiscountCode;
10 11
 use App\Models\Order;
11 12
 use App\Models\Product;
@@ -52,6 +53,12 @@ class Checkout
52 53
         }
53 54
 
54 55
         $language = $store->language->value;
56
+
57
+        // A bundle and its items bought separately draw on the same stock, so check them together.
58
+        if (! $this->enoughStock($lines)) {
59
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'not_enough_stock')]);
60
+        }
61
+
55 62
         $applied = $cart->discount($subtotal);
56 63
 
57 64
         // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
@@ -101,6 +108,7 @@ class Checkout
101 108
 
102 109
             foreach ($lines as $line) {
103 110
                 $variantName = $line['variant']?->name();
111
+                $product = $line['product'];
104 112
 
105 113
                 $order->items()->create([
106 114
                     'store_id' => $store->id,
@@ -109,6 +117,14 @@ class Checkout
109 117
                     // "Sambal Hijau (500g / Pedas)", so every place that shows the order shows the choice too.
110 118
                     'name' => $line['product']->name.($variantName !== null ? " ({$variantName})" : ''),
111 119
                     'variant_name' => $variantName,
120
+                    'bundle_contents' => $product->isBundle()
121
+                        ? $product->bundleItems->map(fn (BundleItem $item) => [
122
+                            'product_id' => $item->product_id,
123
+                            'variant_id' => $item->variant_id,
124
+                            'quantity' => $item->quantity,
125
+                            'label' => $item->label(),
126
+                        ])->values()->all()
127
+                        : null,
112 128
                     'unit_price' => $line['unit_price'],
113 129
                     'quantity' => $line['quantity'],
114 130
                     'line_total' => $line['line_total'],
@@ -151,25 +167,20 @@ class Checkout
151 167
             $locked->save();
152 168
 
153 169
             foreach ($locked->items as $item) {
154
-                // The product or variant may have been deleted since the order was placed.
155
-                $product = $item->product_id !== null
156
-                    ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
157
-                    : null;
158
-                $variant = $item->variant_id !== null
159
-                    ? ProductVariant::query()->whereKey($item->variant_id)->lockForUpdate()->first()
160
-                    : null;
161
-
162
-                if ($variant !== null) {
163
-                    // Never below zero, even if stock was changed by hand in the meantime.
164
-                    $variant->stock = max(0, $variant->stock - $item->quantity);
165
-                    $variant->save();
166
-                    $product?->syncFromVariants();
167
-                } elseif ($product !== null && $item->variant_id === null) {
168
-                    $product->stock = max(0, $product->stock - $item->quantity);
169
-                    $product->save();
170
+                if ($item->bundle_contents !== null) {
171
+                    // A bundle has no stock of its own: lower the stock of what was inside it.
172
+                    foreach ($item->bundle_contents as $part) {
173
+                        $this->lowerStock($part['product_id'], $part['variant_id'], $part['quantity'] * $item->quantity);
174
+                    }
175
+
176
+                    continue;
170 177
                 }
178
+
179
+                $this->lowerStock($item->product_id, $item->variant_id, $item->quantity);
171 180
             }
172 181
 
182
+            BundleStock::refresh($locked->store_id);
183
+
173 184
             // A code counts as used only once the order is paid.
174 185
             if ($locked->discount_code !== null) {
175 186
                 DiscountCode::query()
@@ -189,4 +200,66 @@ class Checkout
189 200
 
190 201
         return $marked;
191 202
     }
203
+
204
+    /**
205
+     * Take stock off a product or one of its variants. Either may have been deleted since the order was placed.
206
+     * Never below zero, even if stock was changed by hand in the meantime.
207
+     */
208
+    private function lowerStock(?int $productId, ?int $variantId, int $quantity): void
209
+    {
210
+        $product = $productId !== null ? Product::query()->whereKey($productId)->lockForUpdate()->first() : null;
211
+
212
+        if ($variantId !== null) {
213
+            $variant = ProductVariant::query()->whereKey($variantId)->lockForUpdate()->first();
214
+
215
+            if ($variant !== null) {
216
+                $variant->stock = max(0, $variant->stock - $quantity);
217
+                $variant->save();
218
+                $product?->syncFromVariants();
219
+            }
220
+
221
+            return;
222
+        }
223
+
224
+        if ($product !== null) {
225
+            $product->stock = max(0, $product->stock - $quantity);
226
+            $product->save();
227
+        }
228
+    }
229
+
230
+    /**
231
+     * Whether there is stock for every line at once, counting what bundles hold.
232
+     * A bundle of 2 sambal plus 3 sambal bought on their own needs 5 sambal.
233
+     *
234
+     * @param  iterable<array{product: Product, variant: ProductVariant|null, quantity: int}>  $lines
235
+     */
236
+    private function enoughStock(iterable $lines): bool
237
+    {
238
+        $needed = [];
239
+        $left = [];
240
+
241
+        $count = function (Product $product, ?ProductVariant $variant, int $quantity) use (&$needed, &$left): void {
242
+            $key = $variant !== null ? 'v'.$variant->id : 'p'.$product->id;
243
+            $needed[$key] = ($needed[$key] ?? 0) + $quantity;
244
+            $left[$key] = $variant !== null ? $variant->stock : $product->stock;
245
+        };
246
+
247
+        foreach ($lines as $line) {
248
+            if ($line['product']->isBundle()) {
249
+                foreach ($line['product']->bundleItems as $item) {
250
+                    $count($item->product, $item->variant, $item->quantity * $line['quantity']);
251
+                }
252
+            } else {
253
+                $count($line['product'], $line['variant'], $line['quantity']);
254
+            }
255
+        }
256
+
257
+        foreach ($needed as $key => $quantity) {
258
+            if ($quantity > $left[$key]) {
259
+                return false;
260
+            }
261
+        }
262
+
263
+        return true;
264
+    }
192 265
 }

+ 2
- 2
app/Http/Controllers/Concerns/RendersStorefront.php Voir le fichier

@@ -47,7 +47,7 @@ trait RendersStorefront
47 47
             'view' => $view,
48 48
             'products' => $store->products()
49 49
                 ->active()
50
-                ->with(['images', 'variants'])
50
+                ->with(Product::STOREFRONT_RELATIONS)
51 51
                 ->latest('id')
52 52
                 ->limit(60)
53 53
                 ->get()
@@ -56,7 +56,7 @@ trait RendersStorefront
56 56
             // Fetched separately so a featured product always shows, however many products the store has.
57 57
             'featuredProducts' => (object) $store->products()
58 58
                 ->active()
59
-                ->with(['images', 'variants'])
59
+                ->with(Product::STOREFRONT_RELATIONS)
60 60
                 ->whereIn('slug', FeaturedProducts::slugs($storefront->plan))
61 61
                 ->get()
62 62
                 ->mapWithKeys(fn (Product $product) => [$product->slug => $product->toStorefront()])

+ 101
- 6
app/Http/Controllers/ProductController.php Voir le fichier

@@ -2,8 +2,10 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
+use App\Commerce\BundleStock;
5 6
 use App\Enums\ProductStatus;
6 7
 use App\Http\Requests\Products\SaveProductRequest;
8
+use App\Models\BundleItem;
7 9
 use App\Models\Product;
8 10
 use App\Models\ProductImage;
9 11
 use App\Models\ProductVariant;
@@ -29,7 +31,7 @@ class ProductController extends Controller
29 31
         return Inertia::render('stores/products/index', [
30 32
             'store' => $this->presentStore($store),
31 33
             'products' => $store->products()
32
-                ->with(['images', 'variants'])
34
+                ->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant'])
33 35
                 ->latest('id')
34 36
                 ->get()
35 37
                 ->map(fn (Product $product) => $this->present($product)),
@@ -38,10 +40,13 @@ class ProductController extends Controller
38 40
 
39 41
     public function create(Request $request, string $slug): Response
40 42
     {
43
+        $store = $this->ownedStore($request, $slug);
44
+
41 45
         return Inertia::render('stores/products/create', [
42
-            'store' => $this->presentStore($this->ownedStore($request, $slug)),
46
+            'store' => $this->presentStore($store),
43 47
             'statuses' => ProductStatus::options(),
44 48
             'maxImages' => SaveProductRequest::MAX_IMAGES,
49
+            'bundleChoices' => $this->bundleChoices($store, null),
45 50
         ]);
46 51
     }
47 52
 
@@ -52,8 +57,11 @@ class ProductController extends Controller
52 57
         $product = DB::transaction(function () use ($store, $request): Product {
53 58
             $product = $store->products()->make($request->productData());
54 59
             $product->options = $request->hasOptions() ? $request->optionsData() : null;
60
+            $product->is_bundle = $request->isBundle();
55 61
             $product->save();
56 62
             $this->syncVariants($product, $request->variantsData());
63
+            $this->syncBundleItems($product, $request->bundleData());
64
+            BundleStock::refresh($store->id);
57 65
 
58 66
             return $product;
59 67
         });
@@ -68,12 +76,14 @@ class ProductController extends Controller
68 76
     public function edit(Request $request, string $slug, int $product): Response
69 77
     {
70 78
         $store = $this->ownedStore($request, $slug);
79
+        $product = $this->ownedProduct($store, $product);
71 80
 
72 81
         return Inertia::render('stores/products/edit', [
73 82
             'store' => $this->presentStore($store),
74
-            'product' => $this->present($this->ownedProduct($store, $product)),
83
+            'product' => $this->present($product),
75 84
             'statuses' => ProductStatus::options(),
76 85
             'maxImages' => SaveProductRequest::MAX_IMAGES,
86
+            'bundleChoices' => $this->bundleChoices($store, $product),
77 87
         ]);
78 88
     }
79 89
 
@@ -89,11 +99,14 @@ class ProductController extends Controller
89 99
             ]);
90 100
         }
91 101
 
92
-        DB::transaction(function () use ($product, $request): void {
102
+        DB::transaction(function () use ($store, $product, $request): void {
93 103
             $product->fill($request->productData());
94 104
             $product->options = $request->hasOptions() ? $request->optionsData() : null;
105
+            $product->is_bundle = $request->isBundle();
95 106
             $product->save();
96 107
             $this->syncVariants($product, $request->variantsData());
108
+            $this->syncBundleItems($product, $request->bundleData());
109
+            BundleStock::refresh($store->id);
97 110
         });
98 111
 
99 112
         $this->addImages($product, $files);
@@ -106,8 +119,18 @@ class ProductController extends Controller
106 119
     public function destroy(Request $request, string $slug, int $product): RedirectResponse
107 120
     {
108 121
         $store = $this->ownedStore($request, $slug);
122
+        $product = $this->ownedProduct($store, $product);
123
+        $use = $product->usedInBundles()->with('bundle')->first();
124
+
125
+        // Deleting it would quietly empty part of a bundle, so the merchant takes it out first.
126
+        if ($use !== null) {
127
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('This product is inside the bundle ":bundle". Take it out of the bundle first.', ['bundle' => $use->bundle->name])]);
128
+
129
+            return back();
130
+        }
109 131
 
110
-        $this->ownedProduct($store, $product)->delete();
132
+        $product->delete();
133
+        BundleStock::refresh($store->id);
111 134
 
112 135
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Product deleted.')]);
113 136
 
@@ -156,6 +179,70 @@ class ProductController extends Controller
156 179
         $product->unsetRelation('variants');
157 180
     }
158 181
 
182
+    /**
183
+     * Make the bundle's items match the form. Not a bundle: no items.
184
+     *
185
+     * @param  list<array{product_id: int, variant_id: int|null, quantity: int}>  $items
186
+     */
187
+    private function syncBundleItems(Product $product, array $items): void
188
+    {
189
+        $product->bundleItems()->delete();
190
+
191
+        foreach ($items as $position => $item) {
192
+            $row = new BundleItem;
193
+            $row->store_id = $product->store_id;
194
+            $row->bundle_id = $product->id;
195
+            $row->product_id = $item['product_id'];
196
+            $row->variant_id = $item['variant_id'];
197
+            $row->quantity = $item['quantity'];
198
+            $row->position = $position;
199
+            $row->save();
200
+        }
201
+
202
+        $product->unsetRelation('bundleItems');
203
+    }
204
+
205
+    /**
206
+     * What a bundle can hold: every product of the store that is not a bundle, and for a product with
207
+     * options, each of its variants. "key" is how the form names it, like a cart line: "12" or "12-34".
208
+     *
209
+     * @return list<array{key: string, label: string, price: string, stock: int}>
210
+     */
211
+    private function bundleChoices(Store $store, ?Product $except): array
212
+    {
213
+        $choices = [];
214
+        $products = $store->products()
215
+            ->with('variants')
216
+            ->where('is_bundle', false)
217
+            ->when($except !== null, fn ($query) => $query->whereKeyNot($except->id))
218
+            ->orderBy('name')
219
+            ->get();
220
+
221
+        foreach ($products as $product) {
222
+            if (! $product->hasVariants()) {
223
+                $choices[] = ['key' => (string) $product->id, 'label' => $product->name, 'price' => self::ringgit($product->price), 'stock' => $product->stock];
224
+
225
+                continue;
226
+            }
227
+
228
+            foreach ($product->variants as $variant) {
229
+                $choices[] = [
230
+                    'key' => $product->id.'-'.$variant->id,
231
+                    'label' => $product->name.' ('.$variant->name().')',
232
+                    'price' => self::ringgit($variant->price),
233
+                    'stock' => $variant->stock,
234
+                ];
235
+            }
236
+        }
237
+
238
+        return $choices;
239
+    }
240
+
241
+    private static function ringgit(int $sen): string
242
+    {
243
+        return number_format($sen / 100, 2, '.', '');
244
+    }
245
+
159 246
     /**
160 247
      * @param  array<int, UploadedFile>  $files
161 248
      */
@@ -204,6 +291,14 @@ class ProductController extends Controller
204 291
                     'stock' => $variant->stock,
205 292
                 ])
206 293
                 ->all(),
294
+            'is_bundle' => $product->isBundle(),
295
+            'bundle_items' => $product->bundleItems
296
+                ->map(fn (BundleItem $item) => [
297
+                    'item' => $item->variant_id !== null ? $item->product_id.'-'.$item->variant_id : (string) $item->product_id,
298
+                    'label' => $item->label(),
299
+                    'quantity' => $item->quantity,
300
+                ])
301
+                ->all(),
207 302
             'status' => $product->status->value,
208 303
             'status_label' => $product->status->label(),
209 304
             'images' => $product->images
@@ -227,6 +322,6 @@ class ProductController extends Controller
227 322
 
228 323
     private function ownedProduct(Store $store, int $id): Product
229 324
     {
230
-        return $store->products()->with(['images', 'variants'])->whereKey($id)->firstOrFail();
325
+        return $store->products()->with(['images', 'variants', 'bundleItems.product', 'bundleItems.variant'])->whereKey($id)->firstOrFail();
231 326
     }
232 327
 }

+ 2
- 1
app/Http/Controllers/StoreDesignController.php Voir le fichier

@@ -3,6 +3,7 @@
3 3
 namespace App\Http\Controllers;
4 4
 
5 5
 use App\Http\Controllers\Concerns\RendersStorefront;
6
+use App\Models\Product;
6 7
 use App\StorePlan\PlanSchema;
7 8
 use Illuminate\Http\RedirectResponse;
8 9
 use Illuminate\Http\Request;
@@ -61,7 +62,7 @@ class StoreDesignController extends Controller
61 62
 
62 63
         $product = $storefront->store->products()
63 64
             ->active()
64
-            ->with(['images', 'variants'])
65
+            ->with(Product::STOREFRONT_RELATIONS)
65 66
             ->where('slug', (string) $request->route('productSlug'))
66 67
             ->firstOrFail();
67 68
 

+ 180
- 2
app/Http/Requests/Products/SaveProductRequest.php Voir le fichier

@@ -3,6 +3,9 @@
3 3
 namespace App\Http\Requests\Products;
4 4
 
5 5
 use App\Enums\ProductStatus;
6
+use App\Models\BundleItem;
7
+use App\Models\Product;
8
+use App\Models\Store;
6 9
 use Illuminate\Foundation\Http\FormRequest;
7 10
 use Illuminate\Validation\Rule;
8 11
 use Illuminate\Validation\Validator;
@@ -12,6 +15,7 @@ use Illuminate\Validation\Validator;
12 15
  *
13 16
  * A simple product has one price and one stock count. A product with options (up to 2, such as
14 17
  * Size and Flavour) has a price and stock for every combination of their values instead.
18
+ * A bundle has one price, and a list of other products inside it; its stock comes from theirs.
15 19
  */
16 20
 class SaveProductRequest extends FormRequest
17 21
 {
@@ -25,6 +29,11 @@ class SaveProductRequest extends FormRequest
25 29
     /** The most combinations, so the variant table stays usable. */
26 30
     public const int MAX_VARIANTS = 50;
27 31
 
32
+    /** The most different items in one bundle, and the most of each. */
33
+    public const int MAX_BUNDLE_ITEMS = 10;
34
+
35
+    public const int MAX_BUNDLE_QUANTITY = 20;
36
+
28 37
     /**
29 38
      * Prices arrive in ringgit, as typed by the merchant, such as "12.90".
30 39
      *
@@ -33,13 +42,14 @@ class SaveProductRequest extends FormRequest
33 42
     public function rules(): array
34 43
     {
35 44
         $simple = ! $this->hasOptions();
45
+        $bundle = $this->isBundle();
36 46
 
37 47
         return [
38 48
             'name' => ['required', 'string', 'min:2', 'max:120'],
39 49
             'description' => ['nullable', 'string', 'max:5000'],
40 50
             'price' => [Rule::requiredIf($simple), 'nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
41 51
             'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', ...($simple ? ['gt:price'] : [])],
42
-            'stock' => [Rule::requiredIf($simple), 'nullable', 'integer', 'min:0', 'max:1000000'],
52
+            'stock' => [Rule::requiredIf($simple && ! $bundle), 'nullable', 'integer', 'min:0', 'max:1000000'],
43 53
             'status' => ['required', Rule::enum(ProductStatus::class)],
44 54
             'images' => ['nullable', 'array', 'max:'.self::MAX_IMAGES],
45 55
             'images.*' => ['image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
@@ -54,6 +64,14 @@ class SaveProductRequest extends FormRequest
54 64
             'variants.*.price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
55 65
             'variants.*.compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
56 66
             'variants.*.stock' => ['required', 'integer', 'min:0', 'max:1000000'],
67
+
68
+            'is_bundle' => ['nullable', 'boolean'],
69
+            ...($bundle ? [
70
+                'bundle_items' => ['required', 'array', 'min:1', 'max:'.self::MAX_BUNDLE_ITEMS],
71
+                // The product id, or "product-variant" for a product with options, like a cart line.
72
+                'bundle_items.*.item' => ['required', 'string', 'regex:/^\d+(-\d+)?$/'],
73
+                'bundle_items.*.quantity' => ['required', 'integer', 'min:1', 'max:'.self::MAX_BUNDLE_QUANTITY],
74
+            ] : []),
57 75
         ];
58 76
     }
59 77
 
@@ -72,6 +90,11 @@ class SaveProductRequest extends FormRequest
72 90
             'options.*.values.required' => 'List the choices for each option, separated by commas.',
73 91
             'variants.*.price.required' => 'Every combination needs a price.',
74 92
             'variants.*.stock.required' => 'Every combination needs a stock number.',
93
+            'bundle_items.required' => 'Add at least one product to the bundle.',
94
+            'bundle_items.min' => 'Add at least one product to the bundle.',
95
+            'bundle_items.max' => 'A bundle can hold at most '.self::MAX_BUNDLE_ITEMS.' different products.',
96
+            'bundle_items.*.item.required' => 'Choose a product for each row.',
97
+            'bundle_items.*.quantity.max' => 'At most '.self::MAX_BUNDLE_QUANTITY.' of each product in a bundle.',
75 98
         ];
76 99
     }
77 100
 
@@ -80,6 +103,16 @@ class SaveProductRequest extends FormRequest
80 103
      */
81 104
     public function withValidator(Validator $validator): void
82 105
     {
106
+        $validator->after(function (Validator $validator): void {
107
+            if ($validator->errors()->isEmpty()) {
108
+                $this->checkBundle($validator);
109
+            }
110
+
111
+            if ($validator->errors()->isEmpty()) {
112
+                $this->checkUsedInBundles($validator);
113
+            }
114
+        });
115
+
83 116
         $validator->after(function (Validator $validator): void {
84 117
             if ($validator->errors()->isNotEmpty() || ! $this->hasOptions()) {
85 118
                 return;
@@ -130,9 +163,142 @@ class SaveProductRequest extends FormRequest
130 163
         });
131 164
     }
132 165
 
166
+    /**
167
+     * A bundle never has options of its own; its items may.
168
+     */
133 169
     public function hasOptions(): bool
134 170
     {
135
-        return is_array($this->input('options')) && $this->input('options') !== [];
171
+        return ! $this->isBundle() && is_array($this->input('options')) && $this->input('options') !== [];
172
+    }
173
+
174
+    public function isBundle(): bool
175
+    {
176
+        return $this->boolean('is_bundle');
177
+    }
178
+
179
+    /**
180
+     * What goes inside the bundle, in the order given. Empty when this is not a bundle.
181
+     *
182
+     * @return list<array{product_id: int, variant_id: int|null, quantity: int}>
183
+     */
184
+    public function bundleData(): array
185
+    {
186
+        if (! $this->isBundle()) {
187
+            return [];
188
+        }
189
+
190
+        $items = [];
191
+
192
+        foreach (array_values((array) $this->input('bundle_items', [])) as $row) {
193
+            [$productId, $variantId] = array_pad(array_map('intval', explode('-', (string) ($row['item'] ?? ''))), 2, null);
194
+
195
+            $items[] = ['product_id' => (int) $productId, 'variant_id' => $variantId, 'quantity' => (int) ($row['quantity'] ?? 1)];
196
+        }
197
+
198
+        return $items;
199
+    }
200
+
201
+    /**
202
+     * Every item must be another product of this store that is not a bundle itself. A product with
203
+     * options must name one of its variants, so the bundle knows whose stock to use.
204
+     */
205
+    private function checkBundle(Validator $validator): void
206
+    {
207
+        $store = $this->store();
208
+
209
+        if (! $this->isBundle() || $store === null) {
210
+            return;
211
+        }
212
+
213
+        $editing = $this->editedProduct();
214
+        $items = $this->bundleData();
215
+        $products = $store->products()->with('variants')->whereKey(array_column($items, 'product_id'))->get()->keyBy('id');
216
+        $seen = [];
217
+
218
+        foreach ($items as $index => $item) {
219
+            $product = $products->get($item['product_id']);
220
+            $field = "bundle_items.$index.item";
221
+
222
+            if ($product === null) {
223
+                $validator->errors()->add($field, 'Choose a product from this store.');
224
+            } elseif ($editing !== null && $product->id === $editing->id) {
225
+                $validator->errors()->add($field, 'A bundle cannot hold itself.');
226
+            } elseif ($product->isBundle()) {
227
+                $validator->errors()->add($field, 'A bundle cannot hold another bundle.');
228
+            } elseif ($product->hasVariants() && ($item['variant_id'] === null || $product->variants->firstWhere('id', $item['variant_id']) === null)) {
229
+                $validator->errors()->add($field, "Choose which {$product->name} goes in the bundle.");
230
+            } elseif (! $product->hasVariants() && $item['variant_id'] !== null) {
231
+                $validator->errors()->add($field, 'Choose a product from this store.');
232
+            } elseif (isset($seen[$item['product_id'].'-'.$item['variant_id']])) {
233
+                $validator->errors()->add($field, 'This product is already in the bundle. Change its quantity instead.');
234
+            }
235
+
236
+            $seen[$item['product_id'].'-'.$item['variant_id']] = true;
237
+        }
238
+
239
+        if ($editing !== null && $editing->usedInBundles()->exists()) {
240
+            $validator->errors()->add('is_bundle', 'This product is inside another bundle, so it cannot be a bundle itself.');
241
+        }
242
+    }
243
+
244
+    /**
245
+     * A product inside a bundle must keep what the bundle points at: it cannot gain or lose its options,
246
+     * and a choice the bundle holds cannot be removed. Otherwise the bundle would quietly change.
247
+     */
248
+    private function checkUsedInBundles(Validator $validator): void
249
+    {
250
+        $product = $this->editedProduct();
251
+
252
+        if ($product === null || $this->isBundle()) {
253
+            return;
254
+        }
255
+
256
+        $uses = BundleItem::query()->where('product_id', $product->id)->with(['bundle', 'variant'])->get();
257
+
258
+        if ($uses->isEmpty()) {
259
+            return;
260
+        }
261
+
262
+        $bundleName = $uses->first()->bundle->name;
263
+
264
+        if ($product->hasVariants() !== $this->hasOptions()) {
265
+            $validator->errors()->add('options', "This product is inside the bundle \"{$bundleName}\". Take it out of the bundle before adding or removing options.");
266
+
267
+            return;
268
+        }
269
+
270
+        $kept = array_map(
271
+            fn (array $row) => mb_strtolower($row['option1']).'|'.mb_strtolower((string) $row['option2']),
272
+            $this->variantsData(),
273
+        );
274
+
275
+        foreach ($uses as $use) {
276
+            $variant = $use->variant;
277
+
278
+            if ($variant !== null && ! in_array(mb_strtolower($variant->option1).'|'.mb_strtolower((string) $variant->option2), $kept, true)) {
279
+                $validator->errors()->add('options', "\"{$variant->name()}\" is inside the bundle \"{$use->bundle->name}\". Keep that choice, or take it out of the bundle first.");
280
+
281
+                return;
282
+            }
283
+        }
284
+    }
285
+
286
+    /**
287
+     * The store this form belongs to. Only the user's own stores are looked at.
288
+     */
289
+    private function store(): ?Store
290
+    {
291
+        return $this->user()?->stores()->where('slug', (string) $this->route('slug'))->first();
292
+    }
293
+
294
+    /**
295
+     * The product being edited, or null when adding a new one.
296
+     */
297
+    private function editedProduct(): ?Product
298
+    {
299
+        $id = $this->route('product');
300
+
301
+        return $id === null ? null : $this->store()?->products()->with('variants')->whereKey((int) $id)->first();
136 302
     }
137 303
 
138 304
     /**
@@ -200,6 +366,18 @@ class SaveProductRequest extends FormRequest
200 366
     {
201 367
         $data = $this->safe()->only(['name', 'description', 'status']);
202 368
 
369
+        if ($this->isBundle()) {
370
+            $compare = $this->validated('compare_at_price');
371
+
372
+            return [
373
+                ...$data,
374
+                'price' => self::toSen($this->validated('price')),
375
+                'compare_at_price' => $compare === null || $compare === '' ? null : self::toSen($compare),
376
+                // Worked out from the items once they are saved.
377
+                'stock' => 0,
378
+            ];
379
+        }
380
+
203 381
         if ($this->hasOptions()) {
204 382
             $variants = $this->variantsData();
205 383
             $cheapest = collect($variants)->sortBy('price')->first();

+ 82
- 0
app/Models/BundleItem.php Voir le fichier

@@ -0,0 +1,82 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
+
8
+/**
9
+ * One thing inside a bundle: a product (and, for a product with options, one of its variants) and how many.
10
+ *
11
+ * @property int $id
12
+ * @property int $store_id
13
+ * @property int $bundle_id
14
+ * @property int $product_id
15
+ * @property int|null $variant_id
16
+ * @property int $quantity
17
+ * @property int $position
18
+ * @property-read Product $bundle
19
+ * @property-read Product $product
20
+ * @property-read ProductVariant|null $variant
21
+ */
22
+class BundleItem extends Model
23
+{
24
+    /**
25
+     * @return BelongsTo<Product, $this>
26
+     */
27
+    public function bundle(): BelongsTo
28
+    {
29
+        return $this->belongsTo(Product::class, 'bundle_id');
30
+    }
31
+
32
+    /**
33
+     * @return BelongsTo<Product, $this>
34
+     */
35
+    public function product(): BelongsTo
36
+    {
37
+        return $this->belongsTo(Product::class);
38
+    }
39
+
40
+    /**
41
+     * @return BelongsTo<ProductVariant, $this>
42
+     */
43
+    public function variant(): BelongsTo
44
+    {
45
+        return $this->belongsTo(ProductVariant::class, 'variant_id');
46
+    }
47
+
48
+    /**
49
+     * "Sambal Hijau (250g)".
50
+     */
51
+    public function name(): string
52
+    {
53
+        return $this->product->name.($this->variant !== null ? ' ('.$this->variant->name().')' : '');
54
+    }
55
+
56
+    /**
57
+     * "2 × Sambal Hijau (250g)".
58
+     */
59
+    public function label(): string
60
+    {
61
+        return $this->quantity.' × '.$this->name();
62
+    }
63
+
64
+    /**
65
+     * How many of this item are left: the variant's stock, or the product's.
66
+     */
67
+    public function stock(): int
68
+    {
69
+        return $this->variant !== null ? $this->variant->stock : $this->product->stock;
70
+    }
71
+
72
+    /**
73
+     * @return array<string, string>
74
+     */
75
+    protected function casts(): array
76
+    {
77
+        return [
78
+            'quantity' => 'integer',
79
+            'position' => 'integer',
80
+        ];
81
+    }
82
+}

+ 2
- 0
app/Models/Order.php Voir le fichier

@@ -103,6 +103,8 @@ class Order extends Model
103 103
                 'unit_price' => $item->unit_price / 100,
104 104
                 'quantity' => $item->quantity,
105 105
                 'line_total' => $item->line_total / 100,
106
+                // For a bundle, what to pack for each one: ["2 × Sambal Hijau (250g)", ...].
107
+                'contents' => array_map(fn (array $part) => $part['label'], $item->bundle_contents ?? []),
106 108
             ])->all(),
107 109
         ];
108 110
     }

+ 12
- 1
app/Models/OrderItem.php Voir le fichier

@@ -15,12 +15,13 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
15 15
  * @property int|null $product_id
16 16
  * @property int|null $variant_id
17 17
  * @property string|null $variant_name
18
+ * @property list<array{product_id: int, variant_id: int|null, quantity: int, label: string}>|null $bundle_contents For a bundle: what was inside, per bundle bought.
18 19
  * @property string $name
19 20
  * @property int $unit_price
20 21
  * @property int $quantity
21 22
  * @property int $line_total
22 23
  */
23
-#[Fillable(['store_id', 'product_id', 'variant_id', 'name', 'variant_name', 'unit_price', 'quantity', 'line_total'])]
24
+#[Fillable(['store_id', 'product_id', 'variant_id', 'name', 'variant_name', 'bundle_contents', 'unit_price', 'quantity', 'line_total'])]
24 25
 class OrderItem extends Model
25 26
 {
26 27
     /**
@@ -30,4 +31,14 @@ class OrderItem extends Model
30 31
     {
31 32
         return $this->belongsTo(Order::class);
32 33
     }
34
+
35
+    /**
36
+     * @return array<string, string>
37
+     */
38
+    protected function casts(): array
39
+    {
40
+        return [
41
+            'bundle_contents' => 'array',
42
+        ];
43
+    }
33 44
 }

+ 40
- 0
app/Models/Product.php Voir le fichier

@@ -23,6 +23,7 @@ use Illuminate\Support\Str;
23 23
  * @property string $slug
24 24
  * @property string|null $description
25 25
  * @property list<array{name: string, values: list<string>}>|null $options Up to 2 options. Null for a simple product.
26
+ * @property bool $is_bundle True for a bundle: its stock comes from the products inside it.
26 27
  * @property int $price
27 28
  * @property int|null $compare_at_price
28 29
  * @property int $stock
@@ -32,6 +33,7 @@ use Illuminate\Support\Str;
32 33
  * @property-read Store $store
33 34
  * @property-read Collection<int, ProductImage> $images
34 35
  * @property-read Collection<int, ProductVariant> $variants
36
+ * @property-read Collection<int, BundleItem> $bundleItems
35 37
  */
36 38
 #[Fillable(['name', 'description', 'price', 'compare_at_price', 'stock', 'status'])]
37 39
 class Product extends Model
@@ -39,6 +41,9 @@ class Product extends Model
39 41
     /** @use HasFactory<ProductFactory> */
40 42
     use HasFactory;
41 43
 
44
+    /** What the storefront needs loaded to show a product. */
45
+    public const array STOREFRONT_RELATIONS = ['images', 'variants', 'bundleItems.product', 'bundleItems.variant'];
46
+
42 47
     protected static function booted(): void
43 48
     {
44 49
         static::creating(function (Product $product): void {
@@ -91,6 +96,31 @@ class Product extends Model
91 96
         return $this->hasMany(ProductVariant::class)->orderBy('position')->orderBy('id');
92 97
     }
93 98
 
99
+    /**
100
+     * For a bundle: what is inside it.
101
+     *
102
+     * @return HasMany<BundleItem, $this>
103
+     */
104
+    public function bundleItems(): HasMany
105
+    {
106
+        return $this->hasMany(BundleItem::class, 'bundle_id')->orderBy('position')->orderBy('id');
107
+    }
108
+
109
+    /**
110
+     * The bundles this product (or one of its variants) is inside.
111
+     *
112
+     * @return HasMany<BundleItem, $this>
113
+     */
114
+    public function usedInBundles(): HasMany
115
+    {
116
+        return $this->hasMany(BundleItem::class, 'product_id');
117
+    }
118
+
119
+    public function isBundle(): bool
120
+    {
121
+        return $this->is_bundle;
122
+    }
123
+
94 124
     /**
95 125
      * True when the product comes in options, such as sizes. Then price and stock live on each variant.
96 126
      */
@@ -155,6 +185,15 @@ class Product extends Model
155 185
                 : [],
156 186
             // True when variants cost different amounts, so lists show "From RM X".
157 187
             'price_varies' => $this->hasVariants() && $this->variants->pluck('price')->unique()->count() > 1,
188
+            // For a bundle: what is inside, such as [{"name": "Sambal Hijau (250g)", "quantity": 2}].
189
+            'bundle' => $this->isBundle()
190
+                ? $this->bundleItems->map(fn (BundleItem $item) => [
191
+                    'name' => $item->name(),
192
+                    'quantity' => $item->quantity,
193
+                    // A link to the item's own page, when shoppers can see it.
194
+                    'slug' => $item->product->status === ProductStatus::Active ? $item->product->slug : null,
195
+                ])->all()
196
+                : [],
158 197
         ];
159 198
     }
160 199
 
@@ -169,6 +208,7 @@ class Product extends Model
169 208
             'compare_at_price' => 'integer',
170 209
             'stock' => 'integer',
171 210
             'options' => 'array',
211
+            'is_bundle' => 'boolean',
172 212
         ];
173 213
     }
174 214
 }

+ 11
- 0
app/Models/ProductVariant.php Voir le fichier

@@ -4,6 +4,7 @@ namespace App\Models;
4 4
 
5 5
 use Illuminate\Database\Eloquent\Model;
6 6
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
+use Illuminate\Database\Eloquent\Relations\HasMany;
7 8
 
8 9
 /**
9 10
  * One combination of a product's options, such as "500g / Pedas", with its own price and stock.
@@ -30,6 +31,16 @@ class ProductVariant extends Model
30 31
         return $this->belongsTo(Product::class);
31 32
     }
32 33
 
34
+    /**
35
+     * The bundles this variant is inside.
36
+     *
37
+     * @return HasMany<BundleItem, $this>
38
+     */
39
+    public function usedInBundles(): HasMany
40
+    {
41
+        return $this->hasMany(BundleItem::class, 'variant_id');
42
+    }
43
+
33 44
     /**
34 45
      * The option values in order, without empty ones.
35 46
      *

+ 2
- 0
app/Storefront/StorefrontText.php Voir le fichier

@@ -12,6 +12,7 @@ final class StorefrontText
12 12
         'en' => [
13 13
             'cart_empty' => 'Your cart is empty.',
14 14
             'minimum_total' => 'The order total must be at least RM 2.00.',
15
+            'not_enough_stock' => 'Some items in your cart share the same stock, and there is not enough for all of them. Please lower a quantity.',
15 16
             'sold_out' => 'This product is sold out.',
16 17
             'choose_option' => 'Please choose an option first.',
17 18
             'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
@@ -26,6 +27,7 @@ final class StorefrontText
26 27
         'ms' => [
27 28
             'cart_empty' => 'Troli anda kosong.',
28 29
             'minimum_total' => 'Jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
30
+            'not_enough_stock' => 'Beberapa barang dalam troli anda berkongsi stok yang sama, dan stok tidak mencukupi untuk semuanya. Sila kurangkan kuantiti.',
29 31
             'sold_out' => 'Produk ini telah habis dijual.',
30 32
             'choose_option' => 'Sila pilih satu pilihan dahulu.',
31 33
             'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',

+ 50
- 0
database/migrations/2026_11_17_000001_create_bundle_items_table.php Voir le fichier

@@ -0,0 +1,50 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        Schema::table('products', function (Blueprint $table) {
12
+            // A bundle is sold as one product but is made of other products. Its stock comes from theirs.
13
+            $table->boolean('is_bundle')->default(false)->after('options');
14
+        });
15
+
16
+        // What is inside a bundle: "2 × Sambal Hijau (250g)". The app refuses to delete a product or variant
17
+        // a bundle holds, so a bundle never loses an item without the merchant knowing.
18
+        Schema::create('bundle_items', function (Blueprint $table) {
19
+            $table->id();
20
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
21
+            $table->foreignId('bundle_id')->constrained('products')->cascadeOnDelete();
22
+            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
23
+            $table->foreignId('variant_id')->nullable()->constrained('product_variants')->cascadeOnDelete();
24
+            $table->unsignedSmallInteger('quantity')->default(1);
25
+            $table->unsignedSmallInteger('position')->default(0);
26
+            $table->timestamps();
27
+
28
+            $table->index(['bundle_id', 'position']);
29
+            $table->index('product_id');
30
+        });
31
+
32
+        Schema::table('order_items', function (Blueprint $table) {
33
+            // For a bundle: what was inside when it was bought, such as ["2 × Sambal Hijau (250g)"].
34
+            $table->json('bundle_contents')->nullable()->after('variant_name');
35
+        });
36
+    }
37
+
38
+    public function down(): void
39
+    {
40
+        Schema::table('order_items', function (Blueprint $table) {
41
+            $table->dropColumn('bundle_contents');
42
+        });
43
+
44
+        Schema::dropIfExists('bundle_items');
45
+
46
+        Schema::table('products', function (Blueprint $table) {
47
+            $table->dropColumn('is_bundle');
48
+        });
49
+    }
50
+};

+ 218
- 0
resources/js/components/stores/bundle-editor.tsx Voir le fichier

@@ -0,0 +1,218 @@
1
+import { Plus, X } from 'lucide-react';
2
+import { useState } from 'react';
3
+import InputError from '@/components/input-error';
4
+import { Button } from '@/components/ui/button';
5
+import { Checkbox } from '@/components/ui/checkbox';
6
+import { Input } from '@/components/ui/input';
7
+import { Label } from '@/components/ui/label';
8
+import type { BundleChoice, Product } from '@/types';
9
+
10
+type Row = { item: string; quantity: string };
11
+
12
+const MAX_ITEMS = 10;
13
+
14
+const selectClass =
15
+    'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm';
16
+
17
+/**
18
+ * A bundle: other products of the store sold together at one price.
19
+ * Its stock is not typed in; it follows the stock of what is inside.
20
+ * The inputs carry the names the server reads: is_bundle, bundle_items[i][item] and bundle_items[i][quantity].
21
+ */
22
+export default function BundleEditor({
23
+    product,
24
+    choices,
25
+    enabled,
26
+    onEnabledChange,
27
+    errors,
28
+}: {
29
+    product?: Product;
30
+    choices: BundleChoice[];
31
+    enabled: boolean;
32
+    onEnabledChange: (enabled: boolean) => void;
33
+    errors: Record<string, string>;
34
+}) {
35
+    const [rows, setRows] = useState<Row[]>(
36
+        product && product.bundle_items.length > 0
37
+            ? product.bundle_items.map((row) => ({
38
+                  item: row.item,
39
+                  quantity: String(row.quantity),
40
+              }))
41
+            : [{ item: '', quantity: '1' }],
42
+    );
43
+
44
+    const byKey = new Map(choices.map((choice) => [choice.key, choice]));
45
+    const filled = rows
46
+        .map((row) => ({
47
+            choice: byKey.get(row.item),
48
+            quantity: Math.max(1, Number(row.quantity) || 1),
49
+        }))
50
+        .filter((row) => row.choice !== undefined);
51
+
52
+    // What the items cost bought one by one, and how many bundles their stock allows.
53
+    const separately = filled.reduce(
54
+        (sum, row) => sum + Number(row.choice!.price) * row.quantity,
55
+        0,
56
+    );
57
+    const stock =
58
+        filled.length > 0
59
+            ? Math.min(
60
+                  ...filled.map((row) =>
61
+                      Math.floor(row.choice!.stock / row.quantity),
62
+                  ),
63
+              )
64
+            : 0;
65
+
66
+    function setRow(index: number, field: keyof Row, value: string) {
67
+        setRows((current) =>
68
+            current.map((row, i) =>
69
+                i === index ? { ...row, [field]: value } : row,
70
+            ),
71
+        );
72
+    }
73
+
74
+    const rowErrors = (index: number) =>
75
+        errors[`bundle_items.${index}.item`] ??
76
+        errors[`bundle_items.${index}.quantity`];
77
+
78
+    return (
79
+        <div className="space-y-4 rounded-xl border p-4">
80
+            <div className="flex items-start gap-3">
81
+                <Checkbox
82
+                    id="is-bundle"
83
+                    className="mt-0.5"
84
+                    checked={enabled}
85
+                    onCheckedChange={(checked) =>
86
+                        onEnabledChange(checked === true)
87
+                    }
88
+                />
89
+                <div>
90
+                    <Label htmlFor="is-bundle">This is a bundle</Label>
91
+                    <p className="mt-0.5 text-sm text-muted-foreground">
92
+                        Sell some of your products together at one price. The
93
+                        stock follows the products inside.
94
+                    </p>
95
+                </div>
96
+            </div>
97
+
98
+            {enabled && (
99
+                <>
100
+                    <input type="hidden" name="is_bundle" value="1" />
101
+
102
+                    {choices.length === 0 ? (
103
+                        <p className="text-sm text-muted-foreground">
104
+                            Add the products that go inside first. Then come
105
+                            back to make the bundle.
106
+                        </p>
107
+                    ) : (
108
+                        <div className="space-y-3">
109
+                            <p className="text-sm font-medium">
110
+                                What is inside
111
+                            </p>
112
+
113
+                            {rows.map((row, index) => (
114
+                                <div key={index} className="space-y-1">
115
+                                    <div className="flex items-center gap-2">
116
+                                        <select
117
+                                            name={`bundle_items[${index}][item]`}
118
+                                            aria-label={`Product ${index + 1}`}
119
+                                            value={row.item}
120
+                                            onChange={(event) =>
121
+                                                setRow(
122
+                                                    index,
123
+                                                    'item',
124
+                                                    event.target.value,
125
+                                                )
126
+                                            }
127
+                                            className={selectClass}
128
+                                        >
129
+                                            <option value="">
130
+                                                Choose a product
131
+                                            </option>
132
+                                            {choices.map((choice) => (
133
+                                                <option
134
+                                                    key={choice.key}
135
+                                                    value={choice.key}
136
+                                                >
137
+                                                    {choice.label} · RM{' '}
138
+                                                    {choice.price} ·{' '}
139
+                                                    {choice.stock} in stock
140
+                                                </option>
141
+                                            ))}
142
+                                        </select>
143
+                                        <span className="text-sm text-muted-foreground">
144
+                                            ×
145
+                                        </span>
146
+                                        <Input
147
+                                            name={`bundle_items[${index}][quantity]`}
148
+                                            aria-label={`How many of product ${index + 1}`}
149
+                                            type="number"
150
+                                            min={1}
151
+                                            max={20}
152
+                                            step={1}
153
+                                            className="w-20"
154
+                                            value={row.quantity}
155
+                                            onChange={(event) =>
156
+                                                setRow(
157
+                                                    index,
158
+                                                    'quantity',
159
+                                                    event.target.value,
160
+                                                )
161
+                                            }
162
+                                        />
163
+                                        <Button
164
+                                            type="button"
165
+                                            variant="ghost"
166
+                                            size="icon"
167
+                                            aria-label={`Remove product ${index + 1}`}
168
+                                            disabled={rows.length === 1}
169
+                                            onClick={() =>
170
+                                                setRows((current) =>
171
+                                                    current.filter(
172
+                                                        (_, i) => i !== index,
173
+                                                    ),
174
+                                                )
175
+                                            }
176
+                                        >
177
+                                            <X />
178
+                                        </Button>
179
+                                    </div>
180
+                                    <InputError message={rowErrors(index)} />
181
+                                </div>
182
+                            ))}
183
+
184
+                            {rows.length < MAX_ITEMS && (
185
+                                <Button
186
+                                    type="button"
187
+                                    variant="outline"
188
+                                    size="sm"
189
+                                    onClick={() =>
190
+                                        setRows((current) => [
191
+                                            ...current,
192
+                                            { item: '', quantity: '1' },
193
+                                        ])
194
+                                    }
195
+                                >
196
+                                    <Plus />
197
+                                    Add a product
198
+                                </Button>
199
+                            )}
200
+
201
+                            {filled.length > 0 && (
202
+                                <p className="text-sm text-muted-foreground tabular-nums">
203
+                                    Bought one by one: RM{' '}
204
+                                    {separately.toFixed(2)} · Bundles you can
205
+                                    sell now: {stock}
206
+                                </p>
207
+                            )}
208
+                        </div>
209
+                    )}
210
+
211
+                    <InputError
212
+                        message={errors.bundle_items ?? errors.is_bundle}
213
+                    />
214
+                </>
215
+            )}
216
+        </div>
217
+    );
218
+}

+ 43
- 20
resources/js/components/stores/product-form.tsx Voir le fichier

@@ -3,11 +3,17 @@ import { Trash2 } from 'lucide-react';
3 3
 import { useState } from 'react';
4 4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
5 5
 import InputError from '@/components/input-error';
6
+import BundleEditor from '@/components/stores/bundle-editor';
6 7
 import VariantEditor from '@/components/stores/variant-editor';
7 8
 import { Button } from '@/components/ui/button';
8 9
 import { Input } from '@/components/ui/input';
9 10
 import { Label } from '@/components/ui/label';
10
-import type { Product, SelectOption, StoreSummary } from '@/types';
11
+import type {
12
+    BundleChoice,
13
+    Product,
14
+    SelectOption,
15
+    StoreSummary,
16
+} from '@/types';
11 17
 
12 18
 const fieldClass =
13 19
     'w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm';
@@ -18,11 +24,13 @@ export default function ProductForm({
18 24
     product,
19 25
     statuses,
20 26
     maxImages,
27
+    bundleChoices,
21 28
 }: {
22 29
     store: StoreSummary;
23 30
     product?: Product;
24 31
     statuses: SelectOption[];
25 32
     maxImages: number;
33
+    bundleChoices: BundleChoice[];
26 34
 }) {
27 35
     const action = product
28 36
         ? ProductController.update.form({
@@ -34,6 +42,7 @@ export default function ProductForm({
34 42
     const [hasOptions, setHasOptions] = useState(
35 43
         (product?.options.length ?? 0) > 0,
36 44
     );
45
+    const [isBundle, setIsBundle] = useState(product?.is_bundle ?? false);
37 46
 
38 47
     function removeImage(imageId: number) {
39 48
         if (!product) {
@@ -122,19 +131,21 @@ export default function ProductForm({
122 131
                                     />
123 132
                                 </div>
124 133
 
125
-                                <div className="grid gap-2">
126
-                                    <Label htmlFor="stock">Stock</Label>
127
-                                    <Input
128
-                                        id="stock"
129
-                                        name="stock"
130
-                                        type="number"
131
-                                        required
132
-                                        min={0}
133
-                                        step={1}
134
-                                        defaultValue={product?.stock ?? 0}
135
-                                    />
136
-                                    <InputError message={errors.stock} />
137
-                                </div>
134
+                                {!isBundle && (
135
+                                    <div className="grid gap-2">
136
+                                        <Label htmlFor="stock">Stock</Label>
137
+                                        <Input
138
+                                            id="stock"
139
+                                            name="stock"
140
+                                            type="number"
141
+                                            required
142
+                                            min={0}
143
+                                            step={1}
144
+                                            defaultValue={product?.stock ?? 0}
145
+                                        />
146
+                                        <InputError message={errors.stock} />
147
+                                    </div>
148
+                                )}
138 149
                             </>
139 150
                         )}
140 151
 
@@ -168,12 +179,24 @@ export default function ProductForm({
168 179
                         </div>
169 180
                     </div>
170 181
 
171
-                    <VariantEditor
172
-                        product={product}
173
-                        enabled={hasOptions}
174
-                        onEnabledChange={setHasOptions}
175
-                        errors={errors}
176
-                    />
182
+                    {!hasOptions && (
183
+                        <BundleEditor
184
+                            product={product}
185
+                            choices={bundleChoices}
186
+                            enabled={isBundle}
187
+                            onEnabledChange={setIsBundle}
188
+                            errors={errors}
189
+                        />
190
+                    )}
191
+
192
+                    {!isBundle && (
193
+                        <VariantEditor
194
+                            product={product}
195
+                            enabled={hasOptions}
196
+                            onEnabledChange={setHasOptions}
197
+                            errors={errors}
198
+                        />
199
+                    )}
177 200
 
178 201
                     <div className="grid gap-3">
179 202
                         <Label htmlFor="images">Photos</Label>

+ 6
- 0
resources/js/pages/stores/orders/show.tsx Voir le fichier

@@ -84,6 +84,12 @@ export default function ShowOrder({
84 84
                                             × {item.quantity} at{' '}
85 85
                                             {formatRinggit(item.unit_price)}
86 86
                                         </span>
87
+                                        {item.contents.length > 0 && (
88
+                                            <span className="mt-0.5 block text-xs text-muted-foreground">
89
+                                                Each has:{' '}
90
+                                                {item.contents.join(', ')}
91
+                                            </span>
92
+                                        )}
87 93
                                     </span>
88 94
                                     <span className="tabular-nums">
89 95
                                         {formatRinggit(item.line_total)}

+ 4
- 1
resources/js/pages/stores/products/create.tsx Voir le fichier

@@ -2,16 +2,18 @@ import { Head } from '@inertiajs/react';
2 2
 import Heading from '@/components/heading';
3 3
 import ProductForm from '@/components/stores/product-form';
4 4
 import { dashboard } from '@/routes';
5
-import type { SelectOption, StoreSummary } from '@/types';
5
+import type { BundleChoice, SelectOption, StoreSummary } from '@/types';
6 6
 
7 7
 export default function CreateProduct({
8 8
     store,
9 9
     statuses,
10 10
     maxImages,
11
+    bundleChoices,
11 12
 }: {
12 13
     store: StoreSummary;
13 14
     statuses: SelectOption[];
14 15
     maxImages: number;
16
+    bundleChoices: BundleChoice[];
15 17
 }) {
16 18
     return (
17 19
         <>
@@ -27,6 +29,7 @@ export default function CreateProduct({
27 29
                     store={store}
28 30
                     statuses={statuses}
29 31
                     maxImages={maxImages}
32
+                    bundleChoices={bundleChoices}
30 33
                 />
31 34
             </div>
32 35
         </>

+ 9
- 1
resources/js/pages/stores/products/edit.tsx Voir le fichier

@@ -14,18 +14,25 @@ import {
14 14
     DialogTrigger,
15 15
 } from '@/components/ui/dialog';
16 16
 import { dashboard } from '@/routes';
17
-import type { Product, SelectOption, StoreSummary } from '@/types';
17
+import type {
18
+    BundleChoice,
19
+    Product,
20
+    SelectOption,
21
+    StoreSummary,
22
+} from '@/types';
18 23
 
19 24
 export default function EditProduct({
20 25
     store,
21 26
     product,
22 27
     statuses,
23 28
     maxImages,
29
+    bundleChoices,
24 30
 }: {
25 31
     store: StoreSummary;
26 32
     product: Product;
27 33
     statuses: SelectOption[];
28 34
     maxImages: number;
35
+    bundleChoices: BundleChoice[];
29 36
 }) {
30 37
     return (
31 38
         <>
@@ -42,6 +49,7 @@ export default function EditProduct({
42 49
                     product={product}
43 50
                     statuses={statuses}
44 51
                     maxImages={maxImages}
52
+                    bundleChoices={bundleChoices}
45 53
                 />
46 54
 
47 55
                 <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-destructive/30 p-4">

+ 15
- 0
resources/js/pages/stores/products/index.tsx Voir le fichier

@@ -87,6 +87,14 @@ export default function ProductsIndex({
87 87
                                 <div className="min-w-0 flex-1">
88 88
                                     <p className="truncate font-medium">
89 89
                                         {product.name}
90
+                                        {product.is_bundle && (
91
+                                            <Badge
92
+                                                variant="outline"
93
+                                                className="ml-2 align-middle"
94
+                                            >
95
+                                                Bundle
96
+                                            </Badge>
97
+                                        )}
90 98
                                     </p>
91 99
                                     <p className="text-sm text-muted-foreground tabular-nums">
92 100
                                         {product.variants.length > 0
@@ -99,6 +107,13 @@ export default function ProductsIndex({
99 107
                                         {product.variants.length > 0 &&
100 108
                                             ` · ${product.variants.length} choices`}
101 109
                                     </p>
110
+                                    {product.is_bundle && (
111
+                                        <p className="truncate text-xs text-muted-foreground">
112
+                                            {product.bundle_items
113
+                                                .map((item) => item.label)
114
+                                                .join(', ')}
115
+                                        </p>
116
+                                    )}
102 117
                                 </div>
103 118
 
104 119
                                 <Badge

+ 30
- 0
resources/js/storefront/pages/product.tsx Voir le fichier

@@ -160,6 +160,36 @@ export function ProductPage({ product }: { product: StoreProduct }) {
160 160
                             </div>
161 161
                         )}
162 162
 
163
+                        {product.bundle.length > 0 && (
164
+                            <div className="mt-6">
165
+                                <h2 className="text-sm font-medium">
166
+                                    {t.whatsInside}
167
+                                </h2>
168
+                                <ul className="mt-2 divide-y divide-(--sf-border) rounded-(--sf-radius-card) border border-(--sf-border)">
169
+                                    {product.bundle.map((item) => (
170
+                                        <li
171
+                                            key={item.name}
172
+                                            className="flex items-center gap-3 px-4 py-2.5 text-sm"
173
+                                        >
174
+                                            <span className="min-w-8 font-semibold tabular-nums">
175
+                                                {item.quantity} ×
176
+                                            </span>
177
+                                            {item.slug ? (
178
+                                                <SfLink
179
+                                                    href={`/products/${item.slug}`}
180
+                                                    className="underline-offset-4 hover:underline"
181
+                                                >
182
+                                                    {item.name}
183
+                                                </SfLink>
184
+                                            ) : (
185
+                                                <span>{item.name}</span>
186
+                                            )}
187
+                                        </li>
188
+                                    ))}
189
+                                </ul>
190
+                            </div>
191
+                        )}
192
+
163 193
                         {product.description && (
164 194
                             <p className="mt-6 leading-relaxed whitespace-pre-line text-(--sf-muted)">
165 195
                                 {product.description}

+ 2
- 0
resources/js/storefront/text.ts Voir le fichier

@@ -12,6 +12,7 @@ const words = {
12 12
         from: (amount: string) => `From ${amount}`,
13 13
         chooseOption: 'Please choose an option first.',
14 14
         unavailable: 'Not available',
15
+        whatsInside: "What's inside",
15 16
         inStock: 'In stock',
16 17
         addToCart: 'Add to cart',
17 18
         quantity: 'Quantity',
@@ -91,6 +92,7 @@ const words = {
91 92
         from: (amount: string) => `Dari ${amount}`,
92 93
         chooseOption: 'Sila pilih satu pilihan dahulu.',
93 94
         unavailable: 'Tiada',
95
+        whatsInside: 'Kandungan set',
94 96
         inStock: 'Ada stok',
95 97
         addToCart: 'Tambah ke troli',
96 98
         quantity: 'Kuantiti',

+ 2
- 0
resources/js/storefront/types.ts Voir le fichier

@@ -176,6 +176,8 @@ export type StoreProduct = {
176 176
     variants: StoreVariant[];
177 177
     /** True when variants cost different amounts, so lists show "From RM X". */
178 178
     price_varies: boolean;
179
+    /** For a bundle: what is inside. "slug" links to the item's page when shoppers can see it. */
180
+    bundle: { name: string; quantity: number; slug: string | null }[];
179 181
 };
180 182
 
181 183
 /** One combination of a product's options, such as "500g / Pedas". Prices in ringgit. */

+ 13
- 0
resources/js/types/store.ts Voir le fichier

@@ -65,6 +65,9 @@ export type Product = {
65 65
     /** Options with their choices as one comma-separated line, such as "250g, 500g". */
66 66
     options: { name: string; values: string }[];
67 67
     variants: ProductVariantRow[];
68
+    is_bundle: boolean;
69
+    /** For a bundle: what is inside. "item" is "12", or "12-34" for a product with options. */
70
+    bundle_items: { item: string; label: string; quantity: number }[];
68 71
     status: 'draft' | 'active';
69 72
     status_label: string;
70 73
     images: { id: number; url: string }[];
@@ -79,6 +82,14 @@ export type ProductVariantRow = {
79 82
     stock: number;
80 83
 };
81 84
 
85
+/** Something a bundle can hold: a product, or one variant of a product with options. */
86
+export type BundleChoice = {
87
+    key: string;
88
+    label: string;
89
+    price: string;
90
+    stock: number;
91
+};
92
+
82 93
 export type StoreSummary = {
83 94
     name: string;
84 95
     slug: string;
@@ -118,6 +129,8 @@ export type Order = {
118 129
         unit_price: number;
119 130
         quantity: number;
120 131
         line_total: number;
132
+        /** For a bundle: what to pack for each one. */
133
+        contents: string[];
121 134
     }[];
122 135
 };
123 136
 

+ 252
- 0
tests/Feature/Stores/BundleTest.php Voir le fichier

@@ -0,0 +1,252 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Models\Order;
7
+use App\Models\Product;
8
+use App\Models\ProductVariant;
9
+use App\Models\Store;
10
+use App\Models\User;
11
+use App\StorePlan\SamplePlan;
12
+use Illuminate\Foundation\Testing\RefreshDatabase;
13
+use Illuminate\Support\Facades\Mail;
14
+use Inertia\Testing\AssertableInertia as Assert;
15
+use Tests\Support\FakeGateway;
16
+use Tests\TestCase;
17
+
18
+class BundleTest extends TestCase
19
+{
20
+    use RefreshDatabase;
21
+
22
+    private User $user;
23
+
24
+    private Store $store;
25
+
26
+    private Product $sambal;
27
+
28
+    private ProductVariant $small;
29
+
30
+    private ProductVariant $big;
31
+
32
+    private Product $kerepek;
33
+
34
+    protected function setUp(): void
35
+    {
36
+        parent::setUp();
37
+
38
+        Mail::fake();
39
+
40
+        $this->user = User::factory()->create();
41
+        $this->store = Store::factory()->for($this->user)->create();
42
+        $this->store->plan = SamplePlan::for($this->store);
43
+        $this->store->save();
44
+        $this->actingAs($this->user);
45
+
46
+        // A sambal in two sizes, and a simple kerepek.
47
+        $this->post(route('stores.products.store', $this->store->slug), [
48
+            'name' => 'Sambal', 'status' => 'active',
49
+            'options' => [['name' => 'Size', 'values' => '250g, 500g']],
50
+            'variants' => [
51
+                ['option1' => '250g', 'price' => '12.90', 'stock' => 10],
52
+                ['option1' => '500g', 'price' => '22.90', 'stock' => 4],
53
+            ],
54
+        ])->assertSessionHasNoErrors();
55
+
56
+        $this->sambal = $this->store->products()->where('name', 'Sambal')->firstOrFail();
57
+        $this->small = $this->sambal->variants()->where('option1', '250g')->firstOrFail();
58
+        $this->big = $this->sambal->variants()->where('option1', '500g')->firstOrFail();
59
+        $this->kerepek = $this->store->products()->create(['name' => 'Kerepek', 'price' => 800, 'stock' => 3, 'status' => 'active']);
60
+    }
61
+
62
+    /**
63
+     * Two small sambal and one kerepek for RM 30.
64
+     *
65
+     * @return array<string, mixed>
66
+     */
67
+    private function form(array $overrides = []): array
68
+    {
69
+        return [
70
+            'name' => 'Combo Pedas',
71
+            'status' => 'active',
72
+            'price' => '30.00',
73
+            'is_bundle' => '1',
74
+            'bundle_items' => [
75
+                ['item' => $this->sambal->id.'-'.$this->small->id, 'quantity' => 2],
76
+                ['item' => (string) $this->kerepek->id, 'quantity' => 1],
77
+            ],
78
+            ...$overrides,
79
+        ];
80
+    }
81
+
82
+    private function createBundle(array $overrides = []): Product
83
+    {
84
+        $this->post(route('stores.products.store', $this->store->slug), $this->form($overrides))
85
+            ->assertSessionHasNoErrors();
86
+
87
+        return $this->store->products()->where('is_bundle', true)->latest('id')->firstOrFail();
88
+    }
89
+
90
+    private function addToCart(Product $product, ?int $variantId, int $quantity = 1)
91
+    {
92
+        return $this->post(route('stores.preview.cart.add', $this->store->slug), [
93
+            'product_id' => $product->id,
94
+            'variant_id' => $variantId,
95
+            'quantity' => $quantity,
96
+        ]);
97
+    }
98
+
99
+    private function checkout()
100
+    {
101
+        return $this->post(route('stores.preview.checkout.store', $this->store->slug), [
102
+            'name' => 'Aminah', 'email' => 'a@example.com', 'phone' => '0123456789',
103
+            'line1' => '12 Jalan Mawar', 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor',
104
+        ]);
105
+    }
106
+
107
+    public function test_a_bundle_gets_its_stock_from_what_is_inside()
108
+    {
109
+        $bundle = $this->createBundle();
110
+
111
+        $this->assertSame(3000, $bundle->price);
112
+        $this->assertCount(2, $bundle->bundleItems);
113
+        // 10 small sambal ÷ 2 = 5, 3 kerepek ÷ 1 = 3: three bundles can be sold.
114
+        $this->assertSame(3, $bundle->stock);
115
+
116
+        // Changing an item's stock changes the bundle's.
117
+        $this->post(route('stores.products.update', [$this->store->slug, $this->kerepek->id]), [
118
+            'name' => 'Kerepek', 'status' => 'active', 'price' => '8.00', 'stock' => 20,
119
+        ])->assertSessionHasNoErrors();
120
+
121
+        $this->assertSame(5, $bundle->fresh()->stock);
122
+
123
+        $this->get(route('stores.products.edit', [$this->store->slug, $bundle->id]))
124
+            ->assertInertia(fn (Assert $page) => $page
125
+                ->where('product.is_bundle', true)
126
+                ->where('product.bundle_items.0.item', $this->sambal->id.'-'.$this->small->id)
127
+                ->where('product.bundle_items.0.label', '2 × Sambal (250g)')
128
+                // The bundle cannot hold itself or another bundle: only the 2 sizes and the kerepek.
129
+                ->has('bundleChoices', 3));
130
+    }
131
+
132
+    public function test_bundle_items_must_be_other_products_of_the_store()
133
+    {
134
+        $other = Product::factory()->create(['name' => 'Elsewhere']);
135
+        $bundle = $this->createBundle();
136
+        $url = route('stores.products.store', $this->store->slug);
137
+
138
+        $this->post($url, $this->form(['bundle_items' => []]))->assertSessionHasErrors('bundle_items');
139
+        $this->post($url, $this->form(['bundle_items' => [['item' => (string) $other->id, 'quantity' => 1]]]))
140
+            ->assertSessionHasErrors('bundle_items.0.item');
141
+        // The sambal has sizes, so the bundle must say which one.
142
+        $this->post($url, $this->form(['bundle_items' => [['item' => (string) $this->sambal->id, 'quantity' => 1]]]))
143
+            ->assertSessionHasErrors('bundle_items.0.item');
144
+        $this->post($url, $this->form(['bundle_items' => [['item' => (string) $bundle->id, 'quantity' => 1]]]))
145
+            ->assertSessionHasErrors('bundle_items.0.item');
146
+        $this->post($url, $this->form(['bundle_items' => [
147
+            ['item' => (string) $this->kerepek->id, 'quantity' => 1],
148
+            ['item' => (string) $this->kerepek->id, 'quantity' => 2],
149
+        ]]))->assertSessionHasErrors('bundle_items.1.item');
150
+
151
+        $this->post(route('stores.products.update', [$this->store->slug, $bundle->id]), $this->form([
152
+            'bundle_items' => [['item' => (string) $bundle->id, 'quantity' => 1]],
153
+        ]))->assertSessionHasErrors('bundle_items.0.item');
154
+
155
+        $this->assertSame(1, $this->store->products()->where('is_bundle', true)->count());
156
+    }
157
+
158
+    public function test_products_inside_a_bundle_are_protected()
159
+    {
160
+        $bundle = $this->createBundle();
161
+
162
+        // Deleting the kerepek would quietly empty part of the bundle.
163
+        $this->delete(route('stores.products.destroy', [$this->store->slug, $this->kerepek->id]));
164
+        $this->assertNotNull($this->kerepek->fresh());
165
+
166
+        // The 250g size is inside the bundle, so it cannot be removed.
167
+        $this->post(route('stores.products.update', [$this->store->slug, $this->sambal->id]), [
168
+            'name' => 'Sambal', 'status' => 'active',
169
+            'options' => [['name' => 'Size', 'values' => '500g']],
170
+            'variants' => [['option1' => '500g', 'price' => '22.90', 'stock' => 4]],
171
+        ])->assertSessionHasErrors('options');
172
+
173
+        // Nor can the sambal lose its sizes, or become a bundle itself.
174
+        $this->post(route('stores.products.update', [$this->store->slug, $this->sambal->id]), [
175
+            'name' => 'Sambal', 'status' => 'active', 'price' => '12.90', 'stock' => 10,
176
+        ])->assertSessionHasErrors('options');
177
+
178
+        $this->post(route('stores.products.update', [$this->store->slug, $this->kerepek->id]), [
179
+            'name' => 'Kerepek', 'status' => 'active', 'price' => '8.00',
180
+            'is_bundle' => '1', 'bundle_items' => [['item' => $this->sambal->id.'-'.$this->big->id, 'quantity' => 1]],
181
+        ])->assertSessionHasErrors('is_bundle');
182
+
183
+        $this->assertCount(2, $this->sambal->variants()->get());
184
+
185
+        // Once the bundle is gone, the kerepek can be deleted.
186
+        $this->delete(route('stores.products.destroy', [$this->store->slug, $bundle->id]));
187
+        $this->delete(route('stores.products.destroy', [$this->store->slug, $this->kerepek->id]));
188
+        $this->assertNull($this->kerepek->fresh());
189
+    }
190
+
191
+    public function test_the_store_shows_what_is_inside()
192
+    {
193
+        $bundle = $this->createBundle();
194
+
195
+        $this->get(route('stores.preview.product', [$this->store->slug, $bundle->slug]))
196
+            ->assertInertia(fn (Assert $page) => $page
197
+                ->where('view.product.price', 30)
198
+                ->where('view.product.stock_left', 3)
199
+                ->where('view.product.bundle.0.name', 'Sambal (250g)')
200
+                ->where('view.product.bundle.0.quantity', 2)
201
+                ->where('view.product.bundle.1.slug', $this->kerepek->slug));
202
+    }
203
+
204
+    public function test_paying_for_a_bundle_lowers_the_stock_of_what_is_inside()
205
+    {
206
+        $gateway = new FakeGateway;
207
+        $this->app->instance(PaymentGateway::class, $gateway);
208
+        $bundle = $this->createBundle();
209
+
210
+        $this->addToCart($bundle, null, 2)->assertSessionHasNoErrors();
211
+        $this->checkout()->assertRedirect();
212
+
213
+        $order = Order::with('items')->firstOrFail();
214
+        $item = $order->items->first();
215
+
216
+        $this->assertSame('Combo Pedas', $item->name);
217
+        $this->assertSame(6000, $order->subtotal);
218
+        $this->assertSame(['2 × Sambal (250g)', '1 × Kerepek'], array_column($item->bundle_contents, 'label'));
219
+
220
+        $gateway->pay($order);
221
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
222
+
223
+        // Two bundles: 4 small sambal and 2 kerepek.
224
+        $this->assertSame(6, $this->small->fresh()->stock);
225
+        $this->assertSame(4, $this->big->fresh()->stock);
226
+        $this->assertSame(10, $this->sambal->fresh()->stock);
227
+        $this->assertSame(1, $this->kerepek->fresh()->stock);
228
+        $this->assertSame(1, $bundle->fresh()->stock);
229
+
230
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
231
+            ->assertInertia(fn (Assert $page) => $page
232
+                ->where('order.items.0.contents', ['2 × Sambal (250g)', '1 × Kerepek']));
233
+    }
234
+
235
+    public function test_a_bundle_and_its_items_in_one_cart_share_the_stock()
236
+    {
237
+        $this->app->instance(PaymentGateway::class, new FakeGateway);
238
+        $bundle = $this->createBundle();
239
+
240
+        // 3 kerepek in stock: 2 bundles need 2, plus 2 on their own makes 4.
241
+        $this->addToCart($bundle, null, 2)->assertSessionHasNoErrors();
242
+        $this->addToCart($this->kerepek, null, 2)->assertSessionHasNoErrors();
243
+
244
+        $this->checkout()->assertSessionHasErrors('cart');
245
+        $this->assertSame(0, Order::count());
246
+
247
+        $this->patch(route('stores.preview.cart.update', [$this->store->slug, (string) $this->kerepek->id]), ['quantity' => 1]);
248
+
249
+        $this->checkout()->assertSessionHasNoErrors()->assertRedirect();
250
+        $this->assertSame(1, Order::count());
251
+    }
252
+}

Chargement…
Annuler
Enregistrer