Sfoglia il codice sorgente

Add product variants

- Up to 2 options per product, each combination with its own price and stock
- Option buttons on the product page; sold-out choices crossed out
- Variant shown in cart, checkout, Stripe, orders and email
- Paying lowers the stock of the chosen variant
feature/product-variants
fahmisaad 4 giorni fa
parent
commit
36a7b2e358

+ 60
- 48
PROGRESS.md Vedi File

@@ -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 done; next: product variants)
8
-**Next action:** Merge `feature/discount-codes` into `main`, then build product variants (size, colour, flavour, each with its own price and stock). Step 7 part 2 still waits for an EasyParcel API key
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
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -143,6 +143,16 @@ Changing from Claude to another AI model (or back) must be a settings change, no
143 143
 - Stripe gets a one-off coupon worth exactly the discount, so its page shows the code and the saving.
144 144
 - Days are Malaysian days: a code runs from the start of its first day to the end of its last day in Malaysian time.
145 145
 
146
+### How product variants work (added in Step 8)
147
+
148
+- A product's `options` hold up to 2 options with their choices, such as `[{"name": "Size", "values": ["250g", "500g"]}]`. Null means a simple product.
149
+- `product_variants` has one row per combination (`option1`, `option2`), each with its own price, "price before discount" and stock, in sen.
150
+- For a product with options, the product's own price is the lowest variant price and its stock is all variants together. This keeps lists, cards and the featured section right; they show "From RM X" when variant prices differ.
151
+- In the cart each line is named after the product, or "product-variant" (for example `12-34`). A product with options must be bought as one of its variants.
152
+- Order lines keep the variant's name (`variant_name`) and include it in the line name, such as "Sambal (500g / Pedas)", so emails, Stripe and order pages all show the choice. Paying lowers the chosen variant's stock.
153
+- Editing a product keeps variants whose choices did not change, so carts holding them stay valid. Combinations that disappear are removed.
154
+- Limits: 2 options, 20 choices per option, 50 combinations.
155
+
146 156
 ### How the featured product section works (fixed in Step 7)
147 157
 
148 158
 - 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.
@@ -268,7 +278,7 @@ Part 2 (needs outside accounts):
268 278
 Agreed on 2026-11-15. Build in this order. It comes after Step 7 because automatic discounts such as free shipping need shipping to exist.
269 279
 
270 280
 - [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
271
-- [ ] Product variants: size, colour, flavour and so on, each with its own price and stock
281
+- [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
272 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
273 283
 - [ ] 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
274 284
 - [ ] Later: automatic discounts ("buy 2, get 10% off", "free shipping over RM 100")
@@ -328,51 +338,52 @@ Then, from the project folder:
328 338
 
329 339
 ## 4b. Where things are in the code
330 340
 
331
-| Thing                                  | Location                                                                                                                 |
332
-| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
333
-| Store model                            | `app/Models/Store.php`                                                                                                   |
334
-| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                                               |
335
-| Store categories, languages, statuses  | `app/Enums/`                                                                                                             |
336
-| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                                                        |
337
-| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                                                         |
338
-| Store tests                            | `tests/Feature/Stores/`                                                                                                  |
339
-| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                                           |
340
-| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                                                        |
341
-| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                                           |
342
-| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                                                         |
343
-| AI settings                            | `config/ai.php` (providers, models per task)                                                                             |
344
-| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                                             |
345
-| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                                                      |
346
-| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                                                     |
347
-| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                                                        |
348
-| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                                                        |
349
-| Progress screen and chat box           | `resources/js/components/stores/`                                                                                        |
350
-| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                                                  |
351
-| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                                             |
352
-| Product screens                        | `resources/js/pages/stores/products/`                                                                                    |
353
-| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                                                         |
354
-| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                                               |
355
-| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                                          |
356
-| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                                          |
357
-| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                                          |
358
-| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                                                         |
359
-| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                                          |
360
-| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                                                         |
361
-| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                                                        |
362
-| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`                              |
363
-| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                                           |
364
-| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                                              |
365
-| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php`                           |
366
-| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                                                 |
367
-| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                                                     |
368
-| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                                                 |
369
-| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                                                   |
370
-| Discount codes                         | `app/Models/DiscountCode.php`, `app/Http/Controllers/DiscountCodeController.php`, `resources/js/pages/stores/discounts/` |
371
-| Discount in the cart and checkout      | `Cart::applyCode` and `Cart::discount`, `Checkout::placeOrder`                                                           |
372
-| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                       |
373
-| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                        |
374
-| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                       |
375
-| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                              |
341
+| Thing                                  | Location                                                                                                                                      |
342
+| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
343
+| Store model                            | `app/Models/Store.php`                                                                                                                        |
344
+| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                                                                    |
345
+| Store categories, languages, statuses  | `app/Enums/`                                                                                                                                  |
346
+| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                                                                             |
347
+| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                                                                              |
348
+| Store tests                            | `tests/Feature/Stores/`                                                                                                                       |
349
+| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                                                                |
350
+| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                                                                             |
351
+| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                                                                |
352
+| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                                                                              |
353
+| AI settings                            | `config/ai.php` (providers, models per task)                                                                                                  |
354
+| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                                                                  |
355
+| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                                                                           |
356
+| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                                                                          |
357
+| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                                                                             |
358
+| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                                                                             |
359
+| Progress screen and chat box           | `resources/js/components/stores/`                                                                                                             |
360
+| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                                                                       |
361
+| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                                                                  |
362
+| Product screens                        | `resources/js/pages/stores/products/`                                                                                                         |
363
+| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                                                                              |
364
+| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                                                                    |
365
+| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                                                               |
366
+| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                                                               |
367
+| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                                                               |
368
+| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                                                                              |
369
+| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                                                               |
370
+| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                                                                              |
371
+| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                                                                             |
372
+| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`                                                   |
373
+| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                                                                |
374
+| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                                                                   |
375
+| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php`                                                |
376
+| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                                                                      |
377
+| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                                                                          |
378
+| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                                                                      |
379
+| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                                                                        |
380
+| Discount codes                         | `app/Models/DiscountCode.php`, `app/Http/Controllers/DiscountCodeController.php`, `resources/js/pages/stores/discounts/`                      |
381
+| Discount in the cart and checkout      | `Cart::applyCode` and `Cart::discount`, `Checkout::placeOrder`                                                                                |
382
+| Product variants                       | `app/Models/ProductVariant.php`, `SaveProductRequest`, `ProductController::syncVariants`, `resources/js/components/stores/variant-editor.tsx` |
383
+| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                                            |
384
+| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                             |
385
+| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                            |
386
+| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                   |
376 387
 
377 388
 ## 5. Open questions
378 389
 
@@ -438,3 +449,4 @@ Add one line per work session: date, what was done, what is next.
438 449
 | 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek. | Merge both branches, then Step 7 part 2 or Step 8               |
439 450
 | 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                    |
440 451
 | 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
+| 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                               |

+ 2
- 1
README.md Vedi File

@@ -20,7 +20,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
20 20
 | 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting            |
21 21
 | 6    | Our own subscription billing                            | Done                                                           |
22 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: discount codes done; variants next                |
23
+| 8    | Discounts and product options: codes, variants, bundles | In progress: codes and variants done; bundles next             |
24 24
 | 9    | Before launch: hosting, legal pages, backups            | Not started                                                    |
25 25
 
26 26
 ## What works today
@@ -38,6 +38,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
38 38
 - Usage counting and limits for regenerations and AI edits
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
+- Product options such as Size and Flavour, each choice with its own price and stock
41 42
 - A Shop page with all products and a page for each product, in the store's design
42 43
 - The home page shows the merchant's real products, with a "View all" button
43 44
 - Cart: add products, change quantities, remove items, see the subtotal. No account needed

+ 113
- 30
app/Commerce/Cart.php Vedi File

@@ -4,6 +4,7 @@ namespace App\Commerce;
4 4
 
5 5
 use App\Models\DiscountCode;
6 6
 use App\Models\Product;
7
+use App\Models\ProductVariant;
7 8
 use App\Models\Store;
8 9
 use App\Storefront\StorefrontText;
9 10
 use Illuminate\Contracts\Session\Session;
@@ -13,7 +14,7 @@ use Illuminate\Support\Collection;
13 14
  * A shopper's cart for one store.
14 15
  *
15 16
  * It is kept in the browser session, so shoppers do not need an account, and each store
16
- * has its own cart. Only product ids and quantities are saved. Names, prices and stock are
17
+ * has its own cart. Only product and variant ids and quantities are saved. Names, prices and stock are
17 18
  * always read fresh from the database, so the cart can never show an old price.
18 19
  */
19 20
 class Cart
@@ -33,31 +34,61 @@ class Cart
33 34
     ) {}
34 35
 
35 36
     /**
36
-     * Put more of a product in the cart. Returns how many are in the cart afterwards.
37
+     * Put more of a product (and, for a product with options, one of its variants) in the cart.
38
+     * Returns how many of that line are in the cart afterwards.
37 39
      */
38
-    public function add(Product $product, int $quantity): int
40
+    public function add(Product $product, ?ProductVariant $variant, int $quantity): int
39 41
     {
40
-        return $this->store(($this->quantities()[$product->id] ?? 0) + $quantity, $product);
42
+        $key = self::lineKey($product, $variant);
43
+
44
+        return $this->store($key, ($this->quantities()[$key] ?? 0) + $quantity, $variant !== null ? $variant->stock : $product->stock);
41 45
     }
42 46
 
43 47
     /**
44
-     * Set exactly how many of a product are in the cart. Zero removes it.
45
-     * The number is capped by the stock and by MAX_QUANTITY.
48
+     * Set exactly how many of one cart line there are. Zero removes it.
49
+     * Returns null when the line does not point at something this store sells.
46 50
      */
47
-    public function set(Product $product, int $quantity): int
51
+    public function setLine(string $key, int $quantity): ?int
48 52
     {
49
-        return $this->store($quantity, $product);
53
+        $item = $this->find($key);
54
+
55
+        if ($item === null) {
56
+            return null;
57
+        }
58
+
59
+        [$product, $variant] = $item;
60
+
61
+        return $this->store(self::lineKey($product, $variant), $quantity, $variant !== null ? $variant->stock : $product->stock);
50 62
     }
51 63
 
52
-    private function store(int $wanted, Product $product): int
64
+    public function removeLine(string $key): void
53 65
     {
54 66
         $quantities = $this->quantities();
55
-        $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY));
67
+        unset($quantities[$key]);
68
+
69
+        $this->save($quantities);
70
+    }
71
+
72
+    /**
73
+     * The name of a cart line: the product id, or "product-variant" for a product with options.
74
+     */
75
+    public static function lineKey(Product $product, ?ProductVariant $variant): string
76
+    {
77
+        return $variant !== null ? $product->id.'-'.$variant->id : (string) $product->id;
78
+    }
79
+
80
+    /**
81
+     * The quantity is capped by the stock and by MAX_QUANTITY.
82
+     */
83
+    private function store(string $key, int $wanted, int $stock): int
84
+    {
85
+        $quantities = $this->quantities();
86
+        $allowed = max(0, min($wanted, $stock, self::MAX_QUANTITY));
56 87
 
57 88
         if ($allowed === 0) {
58
-            unset($quantities[$product->id]);
89
+            unset($quantities[$key]);
59 90
         } else {
60
-            $quantities[$product->id] = $allowed;
91
+            $quantities[$key] = $allowed;
61 92
         }
62 93
 
63 94
         $this->save($quantities);
@@ -65,12 +96,46 @@ class Cart
65 96
         return $allowed;
66 97
     }
67 98
 
68
-    public function remove(int $productId): void
99
+    /**
100
+     * The product and variant a cart line points at, if this store sells them.
101
+     *
102
+     * @return array{0: Product, 1: ProductVariant|null}|null
103
+     */
104
+    private function find(string $key): ?array
69 105
     {
70
-        $quantities = $this->quantities();
71
-        unset($quantities[$productId]);
106
+        $parsed = self::parseKey($key);
72 107
 
73
-        $this->save($quantities);
108
+        if ($parsed === null) {
109
+            return null;
110
+        }
111
+
112
+        [$productId, $variantId] = $parsed;
113
+        $product = $this->store->products()->active()->with('variants')->whereKey($productId)->first();
114
+
115
+        if ($product === null) {
116
+            return null;
117
+        }
118
+
119
+        $variant = $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
120
+
121
+        // A product with options must name one of its variants; a simple product must not name any.
122
+        if ($product->hasVariants() !== ($variant !== null)) {
123
+            return null;
124
+        }
125
+
126
+        return [$product, $variant];
127
+    }
128
+
129
+    /**
130
+     * @return array{0: int, 1: int|null}|null
131
+     */
132
+    private static function parseKey(string $key): ?array
133
+    {
134
+        if (preg_match('/^(\d+)(?:-(\d+))?$/', $key, $match) !== 1) {
135
+            return null;
136
+        }
137
+
138
+        return [(int) $match[1], isset($match[2]) ? (int) $match[2] : null];
74 139
     }
75 140
 
76 141
     public function clear(): void
@@ -143,8 +208,9 @@ class Cart
143 208
     /**
144 209
      * The cart lines, with fresh product details.
145 210
      * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
211
+     * A line whose variant was removed, or whose product gained or lost its options, is dropped too.
146 212
      *
147
-     * @return Collection<int, array{product: Product, quantity: int, line_total: int}>
213
+     * @return Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}>
148 214
      */
149 215
     public function lines(): Collection
150 216
     {
@@ -154,33 +220,45 @@ class Cart
154 220
             return collect();
155 221
         }
156 222
 
223
+        $productIds = array_filter(array_map(fn (string $key) => self::parseKey($key)[0] ?? null, array_keys($quantities)));
224
+
157 225
         $products = $this->store->products()
158 226
             ->active()
159
-            ->with('images')
160
-            ->whereKey(array_keys($quantities))
227
+            ->with(['images', 'variants'])
228
+            ->whereKey($productIds)
161 229
             ->get()
162 230
             ->keyBy('id');
163 231
 
164 232
         $kept = [];
165 233
         $lines = collect();
166 234
 
167
-        foreach ($quantities as $productId => $quantity) {
235
+        foreach ($quantities as $key => $quantity) {
236
+            [$productId, $variantId] = self::parseKey($key) ?? [0, null];
168 237
             $product = $products->get($productId);
169
-            $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0;
238
+            $variant = $product !== null && $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
239
+            $valid = $product !== null && $product->hasVariants() === ($variant !== null);
240
+            $stock = $variant !== null ? $variant->stock : ($product !== null ? $product->stock : 0);
241
+            $allowed = $valid ? min($quantity, $stock, self::MAX_QUANTITY) : 0;
170 242
 
171 243
             if ($allowed !== $quantity) {
172 244
                 $this->adjusted = true;
173 245
             }
174 246
 
175
-            if ($product === null || $allowed < 1) {
247
+            if (! $valid || $allowed < 1) {
176 248
                 continue;
177 249
             }
178 250
 
179
-            $kept[$productId] = $allowed;
251
+            $unitPrice = $variant !== null ? $variant->price : $product->price;
252
+
253
+            $kept[$key] = $allowed;
180 254
             $lines->push([
255
+                // PHP turns a session key such as "12" into the number 12; the frontend always gets text.
256
+                'key' => (string) $key,
181 257
                 'product' => $product,
258
+                'variant' => $variant,
259
+                'unit_price' => $unitPrice,
182 260
                 'quantity' => $allowed,
183
-                'line_total' => $product->price * $allowed,
261
+                'line_total' => $unitPrice * $allowed,
184 262
             ]);
185 263
         }
186 264
 
@@ -219,16 +297,21 @@ class Cart
219 297
             'total' => ($subtotal - ($discount !== null ? $discount->amount : 0)) / 100,
220 298
             'adjusted' => $this->adjusted || $this->discountRemoved,
221 299
             'lines' => $lines->map(fn (array $line) => [
300
+                'key' => $line['key'],
222 301
                 'product' => $line['product']->toStorefront(),
302
+                'variant' => $line['variant'] !== null
303
+                    ? ['id' => $line['variant']->id, 'name' => $line['variant']->name()]
304
+                    : null,
305
+                'unit_price' => $line['unit_price'] / 100,
223 306
                 'quantity' => $line['quantity'],
224
-                'max' => min($line['product']->stock, self::MAX_QUANTITY),
307
+                'max' => min($line['variant'] !== null ? $line['variant']->stock : $line['product']->stock, self::MAX_QUANTITY),
225 308
                 'line_total' => $line['line_total'] / 100,
226 309
             ])->values()->all(),
227 310
         ];
228 311
     }
229 312
 
230 313
     /**
231
-     * @return array<int, int> Product id to quantity.
314
+     * @return array<string, int> Cart line name ("12" or "12-34") to quantity.
232 315
      */
233 316
     private function quantities(): array
234 317
     {
@@ -240,9 +323,9 @@ class Cart
240 323
 
241 324
         $clean = [];
242 325
 
243
-        foreach ($saved as $productId => $quantity) {
244
-            if (is_int($productId) && is_int($quantity) && $quantity > 0) {
245
-                $clean[$productId] = $quantity;
326
+        foreach ($saved as $key => $quantity) {
327
+            if (self::parseKey((string) $key) !== null && is_int($quantity) && $quantity > 0) {
328
+                $clean[(string) $key] = $quantity;
246 329
             }
247 330
         }
248 331
 
@@ -250,7 +333,7 @@ class Cart
250 333
     }
251 334
 
252 335
     /**
253
-     * @param  array<int, int>  $quantities
336
+     * @param  array<string, int>  $quantities
254 337
      */
255 338
     private function save(array $quantities): void
256 339
     {

+ 17
- 4
app/Commerce/Checkout.php Vedi File

@@ -9,6 +9,7 @@ use App\Mail\OrderConfirmation;
9 9
 use App\Models\DiscountCode;
10 10
 use App\Models\Order;
11 11
 use App\Models\Product;
12
+use App\Models\ProductVariant;
12 13
 use App\Models\Store;
13 14
 use App\Storefront\StorefrontText;
14 15
 use Illuminate\Support\Facades\DB;
@@ -99,11 +100,16 @@ class Checkout
99 100
             $order->save();
100 101
 
101 102
             foreach ($lines as $line) {
103
+                $variantName = $line['variant']?->name();
104
+
102 105
                 $order->items()->create([
103 106
                     'store_id' => $store->id,
104 107
                     'product_id' => $line['product']->id,
105
-                    'name' => $line['product']->name,
106
-                    'unit_price' => $line['product']->price,
108
+                    'variant_id' => $line['variant']?->id,
109
+                    // "Sambal Hijau (500g / Pedas)", so every place that shows the order shows the choice too.
110
+                    'name' => $line['product']->name.($variantName !== null ? " ({$variantName})" : ''),
111
+                    'variant_name' => $variantName,
112
+                    'unit_price' => $line['unit_price'],
107 113
                     'quantity' => $line['quantity'],
108 114
                     'line_total' => $line['line_total'],
109 115
                 ]);
@@ -145,13 +151,20 @@ class Checkout
145 151
             $locked->save();
146 152
 
147 153
             foreach ($locked->items as $item) {
148
-                // The product may have been deleted since the order was placed.
154
+                // The product or variant may have been deleted since the order was placed.
149 155
                 $product = $item->product_id !== null
150 156
                     ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
151 157
                     : null;
158
+                $variant = $item->variant_id !== null
159
+                    ? ProductVariant::query()->whereKey($item->variant_id)->lockForUpdate()->first()
160
+                    : null;
152 161
 
153
-                if ($product !== null) {
162
+                if ($variant !== null) {
154 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) {
155 168
                     $product->stock = max(0, $product->stock - $item->quantity);
156 169
                     $product->save();
157 170
                 }

+ 19
- 4
app/Http/Controllers/CartController.php Vedi File

@@ -33,16 +33,29 @@ class CartController extends Controller
33 33
 
34 34
         $validated = $request->validate([
35 35
             'product_id' => ['required', 'integer'],
36
+            'variant_id' => ['nullable', 'integer'],
36 37
             'quantity' => ['required', 'integer', 'min:1', 'max:'.Cart::MAX_QUANTITY],
37 38
         ]);
38 39
 
39 40
         $product = $this->buyableProduct($store, $validated['product_id']);
41
+        $variant = null;
40 42
 
41
-        if ($product->stock < 1) {
43
+        // A product with options must be bought as one of its variants; a simple product never is.
44
+        if ($product->hasVariants()) {
45
+            $variant = $product->variants()->whereKey($validated['variant_id'] ?? 0)->first();
46
+
47
+            if ($variant === null) {
48
+                throw ValidationException::withMessages(['variant_id' => StorefrontText::line($store->language->value, 'choose_option')]);
49
+            }
50
+        } elseif (($validated['variant_id'] ?? null) !== null) {
51
+            abort(404);
52
+        }
53
+
54
+        if (($variant !== null ? $variant->stock : $product->stock) < 1) {
42 55
             throw ValidationException::withMessages(['quantity' => StorefrontText::line($store->language->value, 'sold_out')]);
43 56
         }
44 57
 
45
-        $this->cart($request, $store)->add($product, $validated['quantity']);
58
+        $this->cart($request, $store)->add($product, $variant, $validated['quantity']);
46 59
 
47 60
         return back();
48 61
     }
@@ -58,7 +71,9 @@ class CartController extends Controller
58 71
             'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
59 72
         ]);
60 73
 
61
-        $this->cart($request, $store)->set($this->buyableProduct($store, (int) $request->route('product')), $validated['quantity']);
74
+        $result = $this->cart($request, $store)->setLine((string) $request->route('line'), $validated['quantity']);
75
+
76
+        abort_if($result === null, 404);
62 77
 
63 78
         return back();
64 79
     }
@@ -95,7 +110,7 @@ class CartController extends Controller
95 110
     {
96 111
         $store = $this->storefront($request)->store;
97 112
 
98
-        $this->cart($request, $store)->remove((int) $request->route('product'));
113
+        $this->cart($request, $store)->removeLine((string) $request->route('line'));
99 114
 
100 115
         return back();
101 116
     }

+ 2
- 2
app/Http/Controllers/Concerns/RendersStorefront.php Vedi File

@@ -47,7 +47,7 @@ trait RendersStorefront
47 47
             'view' => $view,
48 48
             'products' => $store->products()
49 49
                 ->active()
50
-                ->with('images')
50
+                ->with(['images', 'variants'])
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')
59
+                ->with(['images', 'variants'])
60 60
                 ->whereIn('slug', FeaturedProducts::slugs($storefront->plan))
61 61
                 ->get()
62 62
                 ->mapWithKeys(fn (Product $product) => [$product->slug => $product->toStorefront()])

+ 67
- 4
app/Http/Controllers/ProductController.php Vedi File

@@ -6,10 +6,12 @@ use App\Enums\ProductStatus;
6 6
 use App\Http\Requests\Products\SaveProductRequest;
7 7
 use App\Models\Product;
8 8
 use App\Models\ProductImage;
9
+use App\Models\ProductVariant;
9 10
 use App\Models\Store;
10 11
 use Illuminate\Http\RedirectResponse;
11 12
 use Illuminate\Http\Request;
12 13
 use Illuminate\Http\UploadedFile;
14
+use Illuminate\Support\Facades\DB;
13 15
 use Illuminate\Validation\ValidationException;
14 16
 use Inertia\Inertia;
15 17
 use Inertia\Response;
@@ -27,7 +29,7 @@ class ProductController extends Controller
27 29
         return Inertia::render('stores/products/index', [
28 30
             'store' => $this->presentStore($store),
29 31
             'products' => $store->products()
30
-                ->with('images')
32
+                ->with(['images', 'variants'])
31 33
                 ->latest('id')
32 34
                 ->get()
33 35
                 ->map(fn (Product $product) => $this->present($product)),
@@ -47,7 +49,15 @@ class ProductController extends Controller
47 49
     {
48 50
         $store = $this->ownedStore($request, $slug);
49 51
 
50
-        $product = $store->products()->create($request->productData());
52
+        $product = DB::transaction(function () use ($store, $request): Product {
53
+            $product = $store->products()->make($request->productData());
54
+            $product->options = $request->hasOptions() ? $request->optionsData() : null;
55
+            $product->save();
56
+            $this->syncVariants($product, $request->variantsData());
57
+
58
+            return $product;
59
+        });
60
+
51 61
         $this->addImages($product, $request->file('images', []));
52 62
 
53 63
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Product added.')]);
@@ -79,7 +89,13 @@ class ProductController extends Controller
79 89
             ]);
80 90
         }
81 91
 
82
-        $product->update($request->productData());
92
+        DB::transaction(function () use ($product, $request): void {
93
+            $product->fill($request->productData());
94
+            $product->options = $request->hasOptions() ? $request->optionsData() : null;
95
+            $product->save();
96
+            $this->syncVariants($product, $request->variantsData());
97
+        });
98
+
83 99
         $this->addImages($product, $files);
84 100
 
85 101
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Product saved.')]);
@@ -108,6 +124,38 @@ class ProductController extends Controller
108 124
         return back();
109 125
     }
110 126
 
127
+    /**
128
+     * Make the product's variants match the form. A variant whose option values did not change keeps
129
+     * its id, so carts holding it stay valid; combinations that are gone are removed.
130
+     *
131
+     * @param  list<array{option1: string, option2: string|null, price: int, compare_at_price: int|null, stock: int}>  $rows
132
+     */
133
+    private function syncVariants(Product $product, array $rows): void
134
+    {
135
+        $key = fn (?string $first, ?string $second) => mb_strtolower((string) $first).'|'.mb_strtolower((string) $second);
136
+        $existing = $product->variants()->get()->keyBy(fn (ProductVariant $variant) => $key($variant->option1, $variant->option2));
137
+        $kept = [];
138
+
139
+        foreach ($rows as $position => $row) {
140
+            $variant = $existing->get($key($row['option1'], $row['option2'])) ?? new ProductVariant;
141
+
142
+            $variant->store_id = $product->store_id;
143
+            $variant->product_id = $product->id;
144
+            $variant->option1 = $row['option1'];
145
+            $variant->option2 = $row['option2'];
146
+            $variant->price = $row['price'];
147
+            $variant->compare_at_price = $row['compare_at_price'];
148
+            $variant->stock = $row['stock'];
149
+            $variant->position = $position;
150
+            $variant->save();
151
+
152
+            $kept[] = $variant->id;
153
+        }
154
+
155
+        $product->variants()->whereNotIn('id', $kept)->delete();
156
+        $product->unsetRelation('variants');
157
+    }
158
+
111 159
     /**
112 160
      * @param  array<int, UploadedFile>  $files
113 161
      */
@@ -141,6 +189,21 @@ class ProductController extends Controller
141 189
                 ? number_format($product->compare_at_price / 100, 2, '.', '')
142 190
                 : null,
143 191
             'stock' => $product->stock,
192
+            // Options with their choices as one comma-separated line, the way the form edits them.
193
+            'options' => collect($product->options ?? [])
194
+                ->map(fn (array $option) => ['name' => $option['name'], 'values' => implode(', ', $option['values'])])
195
+                ->all(),
196
+            'variants' => $product->variants
197
+                ->map(fn (ProductVariant $variant) => [
198
+                    'option1' => $variant->option1,
199
+                    'option2' => $variant->option2,
200
+                    'price' => number_format($variant->price / 100, 2, '.', ''),
201
+                    'compare_at_price' => $variant->compare_at_price !== null
202
+                        ? number_format($variant->compare_at_price / 100, 2, '.', '')
203
+                        : null,
204
+                    'stock' => $variant->stock,
205
+                ])
206
+                ->all(),
144 207
             'status' => $product->status->value,
145 208
             'status_label' => $product->status->label(),
146 209
             'images' => $product->images
@@ -164,6 +227,6 @@ class ProductController extends Controller
164 227
 
165 228
     private function ownedProduct(Store $store, int $id): Product
166 229
     {
167
-        return $store->products()->with('images')->whereKey($id)->firstOrFail();
230
+        return $store->products()->with(['images', 'variants'])->whereKey($id)->firstOrFail();
168 231
     }
169 232
 }

+ 1
- 1
app/Http/Controllers/StoreDesignController.php Vedi File

@@ -61,7 +61,7 @@ class StoreDesignController extends Controller
61 61
 
62 62
         $product = $storefront->store->products()
63 63
             ->active()
64
-            ->with('images')
64
+            ->with(['images', 'variants'])
65 65
             ->where('slug', (string) $request->route('productSlug'))
66 66
             ->firstOrFail();
67 67
 

+ 209
- 4
app/Http/Requests/Products/SaveProductRequest.php Vedi File

@@ -5,12 +5,26 @@ namespace App\Http\Requests\Products;
5 5
 use App\Enums\ProductStatus;
6 6
 use Illuminate\Foundation\Http\FormRequest;
7 7
 use Illuminate\Validation\Rule;
8
+use Illuminate\Validation\Validator;
8 9
 
10
+/**
11
+ * The add-product and edit-product form.
12
+ *
13
+ * A simple product has one price and one stock count. A product with options (up to 2, such as
14
+ * Size and Flavour) has a price and stock for every combination of their values instead.
15
+ */
9 16
 class SaveProductRequest extends FormRequest
10 17
 {
11 18
     /** The most photos one product may have. */
12 19
     public const int MAX_IMAGES = 5;
13 20
 
21
+    public const int MAX_OPTIONS = 2;
22
+
23
+    public const int MAX_VALUES = 20;
24
+
25
+    /** The most combinations, so the variant table stays usable. */
26
+    public const int MAX_VARIANTS = 50;
27
+
14 28
     /**
15 29
      * Prices arrive in ringgit, as typed by the merchant, such as "12.90".
16 30
      *
@@ -18,15 +32,28 @@ class SaveProductRequest extends FormRequest
18 32
      */
19 33
     public function rules(): array
20 34
     {
35
+        $simple = ! $this->hasOptions();
36
+
21 37
         return [
22 38
             'name' => ['required', 'string', 'min:2', 'max:120'],
23 39
             'description' => ['nullable', 'string', 'max:5000'],
24
-            'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
25
-            'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'gt:price', 'max:999999.99'],
26
-            'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
40
+            'price' => [Rule::requiredIf($simple), 'nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
41
+            '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'],
27 43
             'status' => ['required', Rule::enum(ProductStatus::class)],
28 44
             'images' => ['nullable', 'array', 'max:'.self::MAX_IMAGES],
29 45
             'images.*' => ['image', 'mimes:jpg,jpeg,png,webp', 'max:4096'],
46
+
47
+            'options' => ['nullable', 'array', 'max:'.self::MAX_OPTIONS],
48
+            'options.*.name' => ['required', 'string', 'max:30'],
49
+            // Typed as one line, separated by commas: "250g, 500g, 1kg".
50
+            'options.*.values' => ['required', 'string', 'max:800'],
51
+            'variants' => [Rule::requiredIf(! $simple), 'array', 'max:'.self::MAX_VARIANTS],
52
+            'variants.*.option1' => ['required', 'string', 'max:40'],
53
+            'variants.*.option2' => ['nullable', 'string', 'max:40'],
54
+            'variants.*.price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
55
+            'variants.*.compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
56
+            'variants.*.stock' => ['required', 'integer', 'min:0', 'max:1000000'],
30 57
         ];
31 58
     }
32 59
 
@@ -40,26 +67,204 @@ class SaveProductRequest extends FormRequest
40 67
             'images.max' => 'A product can have at most '.self::MAX_IMAGES.' photos.',
41 68
             'images.*.max' => 'Each photo must be 4 MB or smaller.',
42 69
             'images.*.mimes' => 'Photos must be JPG, PNG or WebP files.',
70
+            'options.max' => 'A product can have at most '.self::MAX_OPTIONS.' options.',
71
+            'options.*.name.required' => 'Give each option a name, such as Size.',
72
+            'options.*.values.required' => 'List the choices for each option, separated by commas.',
73
+            'variants.*.price.required' => 'Every combination needs a price.',
74
+            'variants.*.stock.required' => 'Every combination needs a stock number.',
43 75
         ];
44 76
     }
45 77
 
78
+    /**
79
+     * Checks that need the options read first.
80
+     */
81
+    public function withValidator(Validator $validator): void
82
+    {
83
+        $validator->after(function (Validator $validator): void {
84
+            if ($validator->errors()->isNotEmpty() || ! $this->hasOptions()) {
85
+                return;
86
+            }
87
+
88
+            $options = $this->optionsData();
89
+            $names = array_map(fn (array $option) => mb_strtolower($option['name']), $options);
90
+
91
+            if (count(array_unique($names)) !== count($names)) {
92
+                $validator->errors()->add('options', 'Two options have the same name.');
93
+            }
94
+
95
+            foreach ($options as $index => $option) {
96
+                if ($option['values'] === []) {
97
+                    $validator->errors()->add("options.$index.values", 'List the choices for this option, separated by commas.');
98
+                } elseif (count($option['values']) > self::MAX_VALUES) {
99
+                    $validator->errors()->add("options.$index.values", 'An option can have at most '.self::MAX_VALUES.' choices.');
100
+                } elseif (max(array_map('mb_strlen', $option['values'])) > 40) {
101
+                    $validator->errors()->add("options.$index.values", 'Each choice can be at most 40 characters.');
102
+                }
103
+            }
104
+
105
+            if ($validator->errors()->isNotEmpty()) {
106
+                return;
107
+            }
108
+
109
+            if (count($this->combinations()) > self::MAX_VARIANTS) {
110
+                $validator->errors()->add('options', 'Too many combinations. A product can have at most '.self::MAX_VARIANTS.'.');
111
+
112
+                return;
113
+            }
114
+
115
+            foreach ($this->combinations() as $combination) {
116
+                if ($this->submittedVariant($combination) === null) {
117
+                    $validator->errors()->add('variants', 'Set a price and stock for every combination.');
118
+
119
+                    return;
120
+                }
121
+            }
122
+
123
+            foreach ($this->input('variants', []) as $index => $row) {
124
+                $compare = $row['compare_at_price'] ?? null;
125
+
126
+                if ($compare !== null && $compare !== '' && (float) $compare <= (float) ($row['price'] ?? 0)) {
127
+                    $validator->errors()->add("variants.$index.compare_at_price", 'The "was" price must be higher than the price.');
128
+                }
129
+            }
130
+        });
131
+    }
132
+
133
+    public function hasOptions(): bool
134
+    {
135
+        return is_array($this->input('options')) && $this->input('options') !== [];
136
+    }
137
+
138
+    /**
139
+     * The options with their choices read from the comma-separated lines. Repeated choices are dropped.
140
+     *
141
+     * @return list<array{name: string, values: list<string>}>
142
+     */
143
+    public function optionsData(): array
144
+    {
145
+        $options = [];
146
+
147
+        foreach (array_values((array) $this->input('options', [])) as $option) {
148
+            $values = [];
149
+
150
+            foreach (explode(',', (string) ($option['values'] ?? '')) as $value) {
151
+                $value = trim($value);
152
+
153
+                if ($value !== '' && ! in_array(mb_strtolower($value), array_map('mb_strtolower', $values), true)) {
154
+                    $values[] = $value;
155
+                }
156
+            }
157
+
158
+            $options[] = ['name' => trim((string) ($option['name'] ?? '')), 'values' => $values];
159
+        }
160
+
161
+        return $options;
162
+    }
163
+
164
+    /**
165
+     * One row per combination, in a steady order, with prices in sen. Empty for a simple product.
166
+     *
167
+     * @return list<array{option1: string, option2: string|null, price: int, compare_at_price: int|null, stock: int}>
168
+     */
169
+    public function variantsData(): array
170
+    {
171
+        if (! $this->hasOptions()) {
172
+            return [];
173
+        }
174
+
175
+        $rows = [];
176
+
177
+        foreach ($this->combinations() as $combination) {
178
+            $row = $this->submittedVariant($combination) ?? [];
179
+            $compare = $row['compare_at_price'] ?? null;
180
+
181
+            $rows[] = [
182
+                'option1' => $combination[0],
183
+                'option2' => $combination[1],
184
+                'price' => self::toSen($row['price'] ?? 0),
185
+                'compare_at_price' => $compare === null || $compare === '' ? null : self::toSen($compare),
186
+                'stock' => (int) ($row['stock'] ?? 0),
187
+            ];
188
+        }
189
+
190
+        return $rows;
191
+    }
192
+
46 193
     /**
47 194
      * The product fields, with prices converted from ringgit to sen.
195
+     * For a product with options, the price and stock come from its variants.
48 196
      *
49 197
      * @return array<string, mixed>
50 198
      */
51 199
     public function productData(): array
52 200
     {
53
-        $data = $this->safe()->only(['name', 'description', 'stock', 'status']);
201
+        $data = $this->safe()->only(['name', 'description', 'status']);
202
+
203
+        if ($this->hasOptions()) {
204
+            $variants = $this->variantsData();
205
+            $cheapest = collect($variants)->sortBy('price')->first();
206
+
207
+            return [
208
+                ...$data,
209
+                'price' => $cheapest['price'] ?? 0,
210
+                'compare_at_price' => $cheapest['compare_at_price'] ?? null,
211
+                'stock' => (int) collect($variants)->sum('stock'),
212
+            ];
213
+        }
214
+
54 215
         $compare = $this->validated('compare_at_price');
55 216
 
56 217
         return [
57 218
             ...$data,
58 219
             'price' => self::toSen($this->validated('price')),
59 220
             'compare_at_price' => $compare === null || $compare === '' ? null : self::toSen($compare),
221
+            'stock' => (int) $this->validated('stock'),
60 222
         ];
61 223
     }
62 224
 
225
+    /**
226
+     * Every combination of the option values: [["250g", "Pedas"], ["250g", "Manis"], ...].
227
+     * With one option the second value is null.
228
+     *
229
+     * @return list<array{0: string, 1: string|null}>
230
+     */
231
+    private function combinations(): array
232
+    {
233
+        $options = $this->optionsData();
234
+        $first = $options[0]['values'] ?? [];
235
+        $second = $options[1]['values'] ?? [null];
236
+        $combinations = [];
237
+
238
+        foreach ($first as $a) {
239
+            foreach ($second as $b) {
240
+                $combinations[] = [$a, $b];
241
+            }
242
+        }
243
+
244
+        return $combinations;
245
+    }
246
+
247
+    /**
248
+     * The row the merchant filled in for one combination, matched by its values (letter case ignored).
249
+     *
250
+     * @param  array{0: string, 1: string|null}  $combination
251
+     * @return array<string, mixed>|null
252
+     */
253
+    private function submittedVariant(array $combination): ?array
254
+    {
255
+        foreach ((array) $this->input('variants', []) as $row) {
256
+            $first = mb_strtolower(trim((string) ($row['option1'] ?? '')));
257
+            $second = trim((string) ($row['option2'] ?? ''));
258
+
259
+            if ($first === mb_strtolower($combination[0])
260
+                && mb_strtolower($second) === mb_strtolower((string) $combination[1])) {
261
+                return $row;
262
+            }
263
+        }
264
+
265
+        return null;
266
+    }
267
+
63 268
     private static function toSen(mixed $ringgit): int
64 269
     {
65 270
         return (int) round(((float) $ringgit) * 100);

+ 3
- 1
app/Models/OrderItem.php Vedi File

@@ -13,12 +13,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
13 13
  * @property int $store_id
14 14
  * @property int $order_id
15 15
  * @property int|null $product_id
16
+ * @property int|null $variant_id
17
+ * @property string|null $variant_name
16 18
  * @property string $name
17 19
  * @property int $unit_price
18 20
  * @property int $quantity
19 21
  * @property int $line_total
20 22
  */
21
-#[Fillable(['store_id', 'product_id', 'name', 'unit_price', 'quantity', 'line_total'])]
23
+#[Fillable(['store_id', 'product_id', 'variant_id', 'name', 'variant_name', 'unit_price', 'quantity', 'line_total'])]
22 24
 class OrderItem extends Model
23 25
 {
24 26
     /**

+ 45
- 0
app/Models/Product.php Vedi File

@@ -22,6 +22,7 @@ use Illuminate\Support\Str;
22 22
  * @property string $name
23 23
  * @property string $slug
24 24
  * @property string|null $description
25
+ * @property list<array{name: string, values: list<string>}>|null $options Up to 2 options. Null for a simple product.
25 26
  * @property int $price
26 27
  * @property int|null $compare_at_price
27 28
  * @property int $stock
@@ -30,6 +31,7 @@ use Illuminate\Support\Str;
30 31
  * @property CarbonInterface|null $updated_at
31 32
  * @property-read Store $store
32 33
  * @property-read Collection<int, ProductImage> $images
34
+ * @property-read Collection<int, ProductVariant> $variants
33 35
  */
34 36
 #[Fillable(['name', 'description', 'price', 'compare_at_price', 'stock', 'status'])]
35 37
 class Product extends Model
@@ -81,6 +83,42 @@ class Product extends Model
81 83
         return $this->hasMany(ProductImage::class)->orderBy('position')->orderBy('id');
82 84
     }
83 85
 
86
+    /**
87
+     * @return HasMany<ProductVariant, $this>
88
+     */
89
+    public function variants(): HasMany
90
+    {
91
+        return $this->hasMany(ProductVariant::class)->orderBy('position')->orderBy('id');
92
+    }
93
+
94
+    /**
95
+     * True when the product comes in options, such as sizes. Then price and stock live on each variant.
96
+     */
97
+    public function hasVariants(): bool
98
+    {
99
+        return ! empty($this->options);
100
+    }
101
+
102
+    /**
103
+     * For a product with options: the product's own price and stock follow its variants
104
+     * (the lowest price, and the stock of all variants together), so lists and cards stay right.
105
+     */
106
+    public function syncFromVariants(): void
107
+    {
108
+        $variants = $this->variants()->get();
109
+
110
+        if (! $this->hasVariants() || $variants->isEmpty()) {
111
+            return;
112
+        }
113
+
114
+        $cheapest = $variants->sortBy('price')->first();
115
+
116
+        $this->price = (int) $cheapest->price;
117
+        $this->compare_at_price = $cheapest->compare_at_price;
118
+        $this->stock = (int) $variants->sum('stock');
119
+        $this->save();
120
+    }
121
+
84 122
     /**
85 123
      * Products shoppers may see.
86 124
      *
@@ -111,6 +149,12 @@ class Product extends Model
111 149
             'stock_left' => $this->stock,
112 150
             'image' => $images[0] ?? null,
113 151
             'images' => $images,
152
+            'options' => $this->hasVariants() ? $this->options : [],
153
+            'variants' => $this->hasVariants()
154
+                ? $this->variants->map(fn (ProductVariant $variant) => $variant->toStorefront())->all()
155
+                : [],
156
+            // True when variants cost different amounts, so lists show "From RM X".
157
+            'price_varies' => $this->hasVariants() && $this->variants->pluck('price')->unique()->count() > 1,
114 158
         ];
115 159
     }
116 160
 
@@ -124,6 +168,7 @@ class Product extends Model
124 168
             'price' => 'integer',
125 169
             'compare_at_price' => 'integer',
126 170
             'stock' => 'integer',
171
+            'options' => 'array',
127 172
         ];
128 173
     }
129 174
 }

+ 81
- 0
app/Models/ProductVariant.php Vedi File

@@ -0,0 +1,81 @@
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 combination of a product's options, such as "500g / Pedas", with its own price and stock.
10
+ * Prices are in sen (1 ringgit = 100 sen).
11
+ *
12
+ * @property int $id
13
+ * @property int $store_id
14
+ * @property int $product_id
15
+ * @property string $option1
16
+ * @property string|null $option2
17
+ * @property int $price
18
+ * @property int|null $compare_at_price
19
+ * @property int $stock
20
+ * @property int $position
21
+ * @property-read Product $product
22
+ */
23
+class ProductVariant extends Model
24
+{
25
+    /**
26
+     * @return BelongsTo<Product, $this>
27
+     */
28
+    public function product(): BelongsTo
29
+    {
30
+        return $this->belongsTo(Product::class);
31
+    }
32
+
33
+    /**
34
+     * The option values in order, without empty ones.
35
+     *
36
+     * @return list<string>
37
+     */
38
+    public function values(): array
39
+    {
40
+        return array_values(array_filter([$this->option1, $this->option2], fn (?string $value) => $value !== null && $value !== ''));
41
+    }
42
+
43
+    /**
44
+     * "500g / Pedas".
45
+     */
46
+    public function name(): string
47
+    {
48
+        return implode(' / ', $this->values());
49
+    }
50
+
51
+    /**
52
+     * What the storefront is allowed to see. Prices are in ringgit here.
53
+     *
54
+     * @return array<string, mixed>
55
+     */
56
+    public function toStorefront(): array
57
+    {
58
+        return [
59
+            'id' => $this->id,
60
+            'name' => $this->name(),
61
+            'options' => $this->values(),
62
+            'price' => $this->price / 100,
63
+            'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
64
+            'in_stock' => $this->stock > 0,
65
+            'stock_left' => $this->stock,
66
+        ];
67
+    }
68
+
69
+    /**
70
+     * @return array<string, string>
71
+     */
72
+    protected function casts(): array
73
+    {
74
+        return [
75
+            'price' => 'integer',
76
+            'compare_at_price' => 'integer',
77
+            'stock' => 'integer',
78
+            'position' => 'integer',
79
+        ];
80
+    }
81
+}

+ 2
- 0
app/Storefront/StorefrontText.php Vedi File

@@ -13,6 +13,7 @@ final class StorefrontText
13 13
             'cart_empty' => 'Your cart is empty.',
14 14
             'minimum_total' => 'The order total must be at least RM 2.00.',
15 15
             'sold_out' => 'This product is sold out.',
16
+            'choose_option' => 'Please choose an option first.',
16 17
             'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
17 18
             'discount_invalid' => 'This code is not valid.',
18 19
             'discount_not_started' => 'This code cannot be used yet.',
@@ -26,6 +27,7 @@ final class StorefrontText
26 27
             'cart_empty' => 'Troli anda kosong.',
27 28
             'minimum_total' => 'Jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
28 29
             'sold_out' => 'Produk ini telah habis dijual.',
30
+            'choose_option' => 'Sila pilih satu pilihan dahulu.',
29 31
             'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',
30 32
             'discount_invalid' => 'Kod ini tidak sah.',
31 33
             'discount_not_started' => 'Kod ini belum boleh digunakan.',

+ 52
- 0
database/migrations/2026_11_16_000003_create_product_variants_table.php Vedi File

@@ -0,0 +1,52 @@
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
+            // Up to 2 options, such as [{"name": "Size", "values": ["250g", "500g"]}]. Null for a simple product.
13
+            $table->json('options')->nullable()->after('description');
14
+        });
15
+
16
+        // One row per combination of option values, such as "500g / Pedas". Prices in sen.
17
+        Schema::create('product_variants', function (Blueprint $table) {
18
+            $table->id();
19
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
20
+            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
21
+            $table->string('option1', 40);
22
+            $table->string('option2', 40)->nullable();
23
+            $table->unsignedInteger('price');
24
+            $table->unsignedInteger('compare_at_price')->nullable();
25
+            $table->unsignedInteger('stock')->default(0);
26
+            $table->unsignedSmallInteger('position')->default(0);
27
+            $table->timestamps();
28
+
29
+            $table->index(['product_id', 'position']);
30
+        });
31
+
32
+        Schema::table('order_items', function (Blueprint $table) {
33
+            // Kept even if the variant is deleted later; "variant_name" is the record.
34
+            $table->foreignId('variant_id')->nullable()->after('product_id')->constrained('product_variants')->nullOnDelete();
35
+            $table->string('variant_name', 90)->nullable()->after('name');
36
+        });
37
+    }
38
+
39
+    public function down(): void
40
+    {
41
+        Schema::table('order_items', function (Blueprint $table) {
42
+            $table->dropConstrainedForeignId('variant_id');
43
+            $table->dropColumn('variant_name');
44
+        });
45
+
46
+        Schema::dropIfExists('product_variants');
47
+
48
+        Schema::table('products', function (Blueprint $table) {
49
+            $table->dropColumn('options');
50
+        });
51
+    }
52
+};

+ 65
- 45
resources/js/components/stores/product-form.tsx Vedi File

@@ -1,7 +1,9 @@
1 1
 import { Form, Link, router } from '@inertiajs/react';
2 2
 import { Trash2 } from 'lucide-react';
3
+import { useState } from 'react';
3 4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4 5
 import InputError from '@/components/input-error';
6
+import VariantEditor from '@/components/stores/variant-editor';
5 7
 import { Button } from '@/components/ui/button';
6 8
 import { Input } from '@/components/ui/input';
7 9
 import { Label } from '@/components/ui/label';
@@ -29,6 +31,9 @@ export default function ProductForm({
29 31
           })
30 32
         : ProductController.store.form(store.slug);
31 33
     const photosLeft = maxImages - (product?.images.length ?? 0);
34
+    const [hasOptions, setHasOptions] = useState(
35
+        (product?.options.length ?? 0) > 0,
36
+    );
32 37
 
33 38
     function removeImage(imageId: number) {
34 39
         if (!product) {
@@ -77,53 +82,61 @@ export default function ProductForm({
77 82
                     </div>
78 83
 
79 84
                     <div className="grid gap-6 sm:grid-cols-2">
80
-                        <div className="grid gap-2">
81
-                            <Label htmlFor="price">Price (RM)</Label>
82
-                            <Input
83
-                                id="price"
84
-                                name="price"
85
-                                required
86
-                                inputMode="decimal"
87
-                                defaultValue={product?.price}
88
-                                placeholder="12.90"
89
-                            />
90
-                            <InputError message={errors.price} />
91
-                        </div>
85
+                        {!hasOptions && (
86
+                            <>
87
+                                <div className="grid gap-2">
88
+                                    <Label htmlFor="price">Price (RM)</Label>
89
+                                    <Input
90
+                                        id="price"
91
+                                        name="price"
92
+                                        required
93
+                                        inputMode="decimal"
94
+                                        defaultValue={product?.price}
95
+                                        placeholder="12.90"
96
+                                    />
97
+                                    <InputError message={errors.price} />
98
+                                </div>
92 99
 
93
-                        <div className="grid gap-2">
94
-                            <Label htmlFor="compare_at_price">
95
-                                Price before discount (RM, optional)
96
-                            </Label>
97
-                            <Input
98
-                                id="compare_at_price"
99
-                                name="compare_at_price"
100
-                                inputMode="decimal"
101
-                                defaultValue={product?.compare_at_price ?? ''}
102
-                                placeholder="15.90"
103
-                                aria-describedby="compare-help"
104
-                            />
105
-                            <p
106
-                                id="compare-help"
107
-                                className="text-xs text-muted-foreground"
108
-                            >
109
-                                Shown crossed out next to the price.
110
-                            </p>
111
-                            <InputError message={errors.compare_at_price} />
112
-                        </div>
100
+                                <div className="grid gap-2">
101
+                                    <Label htmlFor="compare_at_price">
102
+                                        Price before discount (RM, optional)
103
+                                    </Label>
104
+                                    <Input
105
+                                        id="compare_at_price"
106
+                                        name="compare_at_price"
107
+                                        inputMode="decimal"
108
+                                        defaultValue={
109
+                                            product?.compare_at_price ?? ''
110
+                                        }
111
+                                        placeholder="15.90"
112
+                                        aria-describedby="compare-help"
113
+                                    />
114
+                                    <p
115
+                                        id="compare-help"
116
+                                        className="text-xs text-muted-foreground"
117
+                                    >
118
+                                        Shown crossed out next to the price.
119
+                                    </p>
120
+                                    <InputError
121
+                                        message={errors.compare_at_price}
122
+                                    />
123
+                                </div>
113 124
 
114
-                        <div className="grid gap-2">
115
-                            <Label htmlFor="stock">Stock</Label>
116
-                            <Input
117
-                                id="stock"
118
-                                name="stock"
119
-                                type="number"
120
-                                required
121
-                                min={0}
122
-                                step={1}
123
-                                defaultValue={product?.stock ?? 0}
124
-                            />
125
-                            <InputError message={errors.stock} />
126
-                        </div>
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>
138
+                            </>
139
+                        )}
127 140
 
128 141
                         <div className="grid gap-2">
129 142
                             <Label htmlFor="status">Status</Label>
@@ -155,6 +168,13 @@ export default function ProductForm({
155 168
                         </div>
156 169
                     </div>
157 170
 
171
+                    <VariantEditor
172
+                        product={product}
173
+                        enabled={hasOptions}
174
+                        onEnabledChange={setHasOptions}
175
+                        errors={errors}
176
+                    />
177
+
158 178
                     <div className="grid gap-3">
159 179
                         <Label htmlFor="images">Photos</Label>
160 180
 

+ 389
- 0
resources/js/components/stores/variant-editor.tsx Vedi File

@@ -0,0 +1,389 @@
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 { Product, ProductVariantRow } from '@/types';
9
+
10
+type OptionInput = { name: string; values: string };
11
+type Prices = { price: string; compare_at_price: string; stock: string };
12
+
13
+const MAX_OPTIONS = 2;
14
+
15
+/** "250g, 500g, 250g" becomes ["250g", "500g"]. */
16
+function choices(line: string): string[] {
17
+    const seen = new Set<string>();
18
+
19
+    return line
20
+        .split(',')
21
+        .map((value) => value.trim())
22
+        .filter((value) => {
23
+            const key = value.toLowerCase();
24
+
25
+            if (value === '' || seen.has(key)) {
26
+                return false;
27
+            }
28
+
29
+            seen.add(key);
30
+
31
+            return true;
32
+        });
33
+}
34
+
35
+function comboKey(first: string, second: string | null): string {
36
+    return `${first.toLowerCase()}|${(second ?? '').toLowerCase()}`;
37
+}
38
+
39
+/**
40
+ * Options such as Size and Flavour, and a price and stock for every combination of their choices.
41
+ * The inputs carry the names the server reads: options[i][name], variants[j][price] and so on.
42
+ */
43
+export default function VariantEditor({
44
+    product,
45
+    enabled,
46
+    onEnabledChange,
47
+    errors,
48
+}: {
49
+    product?: Product;
50
+    enabled: boolean;
51
+    onEnabledChange: (enabled: boolean) => void;
52
+    errors: Record<string, string>;
53
+}) {
54
+    const [options, setOptions] = useState<OptionInput[]>(
55
+        product && product.options.length > 0
56
+            ? product.options
57
+            : [{ name: '', values: '' }],
58
+    );
59
+    const [prices, setPrices] = useState<Record<string, Prices>>(() =>
60
+        Object.fromEntries(
61
+            (product?.variants ?? []).map((row: ProductVariantRow) => [
62
+                comboKey(row.option1, row.option2),
63
+                {
64
+                    price: row.price,
65
+                    compare_at_price: row.compare_at_price ?? '',
66
+                    stock: String(row.stock),
67
+                },
68
+            ]),
69
+        ),
70
+    );
71
+
72
+    const first = choices(options[0]?.values ?? '');
73
+    const second = options[1] ? choices(options[1].values) : [];
74
+    const combinations: [string, string | null][] = first.flatMap((a) =>
75
+        second.length > 0
76
+            ? second.map((b): [string, string | null] => [a, b])
77
+            : [[a, null]],
78
+    );
79
+
80
+    function setOption(index: number, field: keyof OptionInput, value: string) {
81
+        setOptions((current) =>
82
+            current.map((option, i) =>
83
+                i === index ? { ...option, [field]: value } : option,
84
+            ),
85
+        );
86
+    }
87
+
88
+    function setPrice(key: string, field: keyof Prices, value: string) {
89
+        const empty: Prices = { price: '', compare_at_price: '', stock: '0' };
90
+
91
+        setPrices((current) => ({
92
+            ...current,
93
+            [key]: { ...(current[key] ?? empty), [field]: value },
94
+        }));
95
+    }
96
+
97
+    /** Copy the first row's price and stock to every row. */
98
+    function fillAll() {
99
+        const firstKey = combinations[0]
100
+            ? comboKey(combinations[0][0], combinations[0][1])
101
+            : null;
102
+        const source = firstKey ? prices[firstKey] : undefined;
103
+
104
+        if (!source) {
105
+            return;
106
+        }
107
+
108
+        setPrices((current) => {
109
+            const next = { ...current };
110
+
111
+            for (const [a, b] of combinations) {
112
+                next[comboKey(a, b)] = { ...source };
113
+            }
114
+
115
+            return next;
116
+        });
117
+    }
118
+
119
+    const optionErrors = Object.entries(errors)
120
+        .filter(([key]) => key === 'options' || key.startsWith('options.'))
121
+        .map(([, message]) => message);
122
+    const variantErrors = [
123
+        ...new Set(
124
+            Object.entries(errors)
125
+                .filter(
126
+                    ([key]) =>
127
+                        key === 'variants' || key.startsWith('variants.'),
128
+                )
129
+                .map(([, message]) => message),
130
+        ),
131
+    ];
132
+
133
+    return (
134
+        <div className="space-y-4 rounded-xl border p-4">
135
+            <div className="flex items-start gap-3">
136
+                <Checkbox
137
+                    id="has-options"
138
+                    className="mt-0.5"
139
+                    checked={enabled}
140
+                    onCheckedChange={(checked) =>
141
+                        onEnabledChange(checked === true)
142
+                    }
143
+                />
144
+                <div>
145
+                    <Label htmlFor="has-options">
146
+                        This product has options
147
+                    </Label>
148
+                    <p className="mt-0.5 text-sm text-muted-foreground">
149
+                        Such as sizes, colours or flavours, each with its own
150
+                        price and stock.
151
+                    </p>
152
+                </div>
153
+            </div>
154
+
155
+            {enabled && (
156
+                <>
157
+                    <div className="space-y-3">
158
+                        {options.map((option, index) => (
159
+                            <div
160
+                                key={index}
161
+                                className="grid gap-3 sm:grid-cols-[180px_1fr_auto] sm:items-start"
162
+                            >
163
+                                <div className="grid gap-1.5">
164
+                                    <Label htmlFor={`option-name-${index}`}>
165
+                                        Option {index + 1}
166
+                                    </Label>
167
+                                    <Input
168
+                                        id={`option-name-${index}`}
169
+                                        name={`options[${index}][name]`}
170
+                                        maxLength={30}
171
+                                        value={option.name}
172
+                                        onChange={(event) =>
173
+                                            setOption(
174
+                                                index,
175
+                                                'name',
176
+                                                event.target.value,
177
+                                            )
178
+                                        }
179
+                                        placeholder={
180
+                                            index === 0 ? 'Size' : 'Flavour'
181
+                                        }
182
+                                    />
183
+                                </div>
184
+                                <div className="grid gap-1.5">
185
+                                    <Label htmlFor={`option-values-${index}`}>
186
+                                        Choices, separated by commas
187
+                                    </Label>
188
+                                    <Input
189
+                                        id={`option-values-${index}`}
190
+                                        name={`options[${index}][values]`}
191
+                                        value={option.values}
192
+                                        onChange={(event) =>
193
+                                            setOption(
194
+                                                index,
195
+                                                'values',
196
+                                                event.target.value,
197
+                                            )
198
+                                        }
199
+                                        placeholder={
200
+                                            index === 0
201
+                                                ? '250g, 500g'
202
+                                                : 'Original, Pedas'
203
+                                        }
204
+                                    />
205
+                                </div>
206
+                                {index > 0 && (
207
+                                    <Button
208
+                                        type="button"
209
+                                        variant="ghost"
210
+                                        size="icon"
211
+                                        className="sm:mt-6"
212
+                                        aria-label={`Remove option ${index + 1}`}
213
+                                        onClick={() =>
214
+                                            setOptions((current) =>
215
+                                                current.filter(
216
+                                                    (_, i) => i !== index,
217
+                                                ),
218
+                                            )
219
+                                        }
220
+                                    >
221
+                                        <X />
222
+                                    </Button>
223
+                                )}
224
+                            </div>
225
+                        ))}
226
+
227
+                        {options.length < MAX_OPTIONS && (
228
+                            <Button
229
+                                type="button"
230
+                                variant="outline"
231
+                                size="sm"
232
+                                onClick={() =>
233
+                                    setOptions((current) => [
234
+                                        ...current,
235
+                                        { name: '', values: '' },
236
+                                    ])
237
+                                }
238
+                            >
239
+                                <Plus />
240
+                                Add a second option
241
+                            </Button>
242
+                        )}
243
+
244
+                        {optionErrors.map((message) => (
245
+                            <InputError key={message} message={message} />
246
+                        ))}
247
+                    </div>
248
+
249
+                    {combinations.length > 0 && (
250
+                        <div className="space-y-2">
251
+                            <div className="flex flex-wrap items-center justify-between gap-2">
252
+                                <p className="text-sm font-medium">
253
+                                    Price and stock for each choice (
254
+                                    {combinations.length})
255
+                                </p>
256
+                                {combinations.length > 1 && (
257
+                                    <Button
258
+                                        type="button"
259
+                                        variant="ghost"
260
+                                        size="sm"
261
+                                        onClick={fillAll}
262
+                                    >
263
+                                        Copy first row to all
264
+                                    </Button>
265
+                                )}
266
+                            </div>
267
+
268
+                            <div className="overflow-x-auto rounded-md border">
269
+                                <table className="w-full text-sm">
270
+                                    <thead className="bg-muted/40 text-left text-muted-foreground">
271
+                                        <tr>
272
+                                            <th className="px-3 py-2 font-medium">
273
+                                                Choice
274
+                                            </th>
275
+                                            <th className="px-3 py-2 font-medium">
276
+                                                Price (RM)
277
+                                            </th>
278
+                                            <th className="px-3 py-2 font-medium">
279
+                                                Before discount
280
+                                            </th>
281
+                                            <th className="px-3 py-2 font-medium">
282
+                                                Stock
283
+                                            </th>
284
+                                        </tr>
285
+                                    </thead>
286
+                                    <tbody className="divide-y">
287
+                                        {combinations.map(([a, b], row) => {
288
+                                            const key = comboKey(a, b);
289
+                                            const value = prices[key];
290
+                                            const label = b ? `${a} / ${b}` : a;
291
+
292
+                                            return (
293
+                                                <tr key={key}>
294
+                                                    <td className="px-3 py-2 whitespace-nowrap">
295
+                                                        {label}
296
+                                                        <input
297
+                                                            type="hidden"
298
+                                                            name={`variants[${row}][option1]`}
299
+                                                            value={a}
300
+                                                        />
301
+                                                        {b && (
302
+                                                            <input
303
+                                                                type="hidden"
304
+                                                                name={`variants[${row}][option2]`}
305
+                                                                value={b}
306
+                                                            />
307
+                                                        )}
308
+                                                    </td>
309
+                                                    <td className="px-3 py-1.5">
310
+                                                        <Input
311
+                                                            name={`variants[${row}][price]`}
312
+                                                            aria-label={`Price for ${label}`}
313
+                                                            inputMode="decimal"
314
+                                                            className="h-8 min-w-24"
315
+                                                            value={
316
+                                                                value?.price ??
317
+                                                                ''
318
+                                                            }
319
+                                                            onChange={(event) =>
320
+                                                                setPrice(
321
+                                                                    key,
322
+                                                                    'price',
323
+                                                                    event.target
324
+                                                                        .value,
325
+                                                                )
326
+                                                            }
327
+                                                            placeholder="12.90"
328
+                                                        />
329
+                                                    </td>
330
+                                                    <td className="px-3 py-1.5">
331
+                                                        <Input
332
+                                                            name={`variants[${row}][compare_at_price]`}
333
+                                                            aria-label={`Price before discount for ${label}`}
334
+                                                            inputMode="decimal"
335
+                                                            className="h-8 min-w-24"
336
+                                                            value={
337
+                                                                value?.compare_at_price ??
338
+                                                                ''
339
+                                                            }
340
+                                                            onChange={(event) =>
341
+                                                                setPrice(
342
+                                                                    key,
343
+                                                                    'compare_at_price',
344
+                                                                    event.target
345
+                                                                        .value,
346
+                                                                )
347
+                                                            }
348
+                                                            placeholder="Optional"
349
+                                                        />
350
+                                                    </td>
351
+                                                    <td className="px-3 py-1.5">
352
+                                                        <Input
353
+                                                            name={`variants[${row}][stock]`}
354
+                                                            aria-label={`Stock for ${label}`}
355
+                                                            type="number"
356
+                                                            min={0}
357
+                                                            step={1}
358
+                                                            className="h-8 min-w-20"
359
+                                                            value={
360
+                                                                value?.stock ??
361
+                                                                '0'
362
+                                                            }
363
+                                                            onChange={(event) =>
364
+                                                                setPrice(
365
+                                                                    key,
366
+                                                                    'stock',
367
+                                                                    event.target
368
+                                                                        .value,
369
+                                                                )
370
+                                                            }
371
+                                                        />
372
+                                                    </td>
373
+                                                </tr>
374
+                                            );
375
+                                        })}
376
+                                    </tbody>
377
+                                </table>
378
+                            </div>
379
+
380
+                            {variantErrors.map((message) => (
381
+                                <InputError key={message} message={message} />
382
+                            ))}
383
+                        </div>
384
+                    )}
385
+                </>
386
+            )}
387
+        </div>
388
+    );
389
+}

+ 5
- 0
resources/js/pages/stores/products/index.tsx Vedi File

@@ -89,10 +89,15 @@ export default function ProductsIndex({
89 89
                                         {product.name}
90 90
                                     </p>
91 91
                                     <p className="text-sm text-muted-foreground tabular-nums">
92
+                                        {product.variants.length > 0
93
+                                            ? 'From '
94
+                                            : ''}
92 95
                                         RM {product.price} ·{' '}
93 96
                                         {product.stock > 0
94 97
                                             ? `${product.stock} in stock`
95 98
                                             : 'Out of stock'}
99
+                                        {product.variants.length > 0 &&
100
+                                            ` · ${product.variants.length} choices`}
96 101
                                     </p>
97 102
                                 </div>
98 103
 

+ 11
- 6
resources/js/storefront/pages/cart.tsx Vedi File

@@ -24,7 +24,7 @@ export function CartPage() {
24 24
     const [busy, setBusy] = useState(false);
25 25
 
26 26
     function change(line: CartLine, quantity: number) {
27
-        const url = `${baseUrl}/cart/items/${line.product.id}`;
27
+        const url = `${baseUrl}/cart/items/${line.key}`;
28 28
         const options = {
29 29
             preserveScroll: true,
30 30
             onStart: () => setBusy(true),
@@ -66,7 +66,7 @@ export function CartPage() {
66 66
                         <ul className="space-y-4">
67 67
                             {cart.lines.map((line, index) => (
68 68
                                 <li
69
-                                    key={line.product.id}
69
+                                    key={line.key}
70 70
                                     className="flex gap-4 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-bg) p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-shadow hover:shadow-[0_4px_16px_rgb(0_0_0/0.06)] sm:gap-5 sm:p-5"
71 71
                                 >
72 72
                                     <SfLink
@@ -90,9 +90,14 @@ export function CartPage() {
90 90
                                                 >
91 91
                                                     {line.product.name}
92 92
                                                 </SfLink>
93
+                                                {line.variant && (
94
+                                                    <p className="mt-0.5 text-sm text-(--sf-muted)">
95
+                                                        {line.variant.name}
96
+                                                    </p>
97
+                                                )}
93 98
                                                 <p className="mt-1 text-sm text-(--sf-muted) tabular-nums">
94 99
                                                     {formatPrice(
95
-                                                        line.product.price,
100
+                                                        line.unit_price,
96 101
                                                     )}{' '}
97 102
                                                     {t.each}
98 103
                                                 </p>
@@ -115,14 +120,14 @@ export function CartPage() {
115 120
                                                 onChange={(quantity) =>
116 121
                                                     change(line, quantity)
117 122
                                                 }
118
-                                                decreaseLabel={`${t.decrease}: ${line.product.name}`}
119
-                                                increaseLabel={`${t.increase}: ${line.product.name}`}
123
+                                                decreaseLabel={`${t.decrease}: ${line.product.name}${line.variant ? ` (${line.variant.name})` : ''}`}
124
+                                                increaseLabel={`${t.increase}: ${line.product.name}${line.variant ? ` (${line.variant.name})` : ''}`}
120 125
                                             />
121 126
                                             <button
122 127
                                                 type="button"
123 128
                                                 disabled={busy}
124 129
                                                 onClick={() => change(line, 0)}
125
-                                                aria-label={`${t.remove}: ${line.product.name}`}
130
+                                                aria-label={`${t.remove}: ${line.product.name}${line.variant ? ` (${line.variant.name})` : ''}`}
126 131
                                                 className="inline-flex items-center gap-1.5 rounded-(--sf-radius) px-2.5 py-1.5 text-sm text-(--sf-muted) transition-colors hover:bg-(--sf-surface) hover:text-(--sf-fg) disabled:opacity-50"
127 132
                                             >
128 133
                                                 <Trash2

+ 4
- 2
resources/js/storefront/pages/checkout.tsx Vedi File

@@ -212,11 +212,13 @@ export function CheckoutPage({
212 212
                         <ul className="mt-4 space-y-3 text-sm">
213 213
                             {cart.lines.map((line) => (
214 214
                                 <li
215
-                                    key={line.product.id}
215
+                                    key={line.key}
216 216
                                     className="flex justify-between gap-4"
217 217
                                 >
218 218
                                     <span>
219
-                                        {line.product.name}{' '}
219
+                                        {line.product.name}
220
+                                        {line.variant &&
221
+                                            ` (${line.variant.name})`}{' '}
220 222
                                         <span className="text-(--sf-muted)">
221 223
                                             × {line.quantity}
222 224
                                         </span>

+ 131
- 16
resources/js/storefront/pages/product.tsx Vedi File

@@ -4,7 +4,8 @@ import { useStorefront } from '../context';
4 4
 import { ProductImage } from '../product-card';
5 5
 import { storefrontText } from '../text';
6 6
 import { formatPrice } from '../theme';
7
-import type { StoreProduct } from '../types';
7
+import { cn } from '@/lib/utils';
8
+import type { StoreProduct, StoreVariant } from '../types';
8 9
 import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
9 10
 
10 11
 /** One product's own page. Built by us, in the store's colours and fonts. */
@@ -14,6 +15,41 @@ export function ProductPage({ product }: { product: StoreProduct }) {
14 15
     const [selected, setSelected] = useState(0);
15 16
     const shown = product.images[selected] ?? product.image;
16 17
 
18
+    // Start on the first combination that is in stock, so the page opens ready to buy.
19
+    const start =
20
+        product.variants.find((candidate) => candidate.in_stock) ??
21
+        product.variants[0];
22
+    const [choice, setChoice] = useState<string[]>(start?.options ?? []);
23
+    const variant =
24
+        product.variants.find(
25
+            (candidate) =>
26
+                candidate.options.length === choice.length &&
27
+                candidate.options.every((value, i) => value === choice[i]),
28
+        ) ?? null;
29
+
30
+    const price = variant ? variant.price : product.price;
31
+    const compareAt = variant
32
+        ? variant.compare_at_price
33
+        : product.compare_at_price;
34
+    const inStock = variant ? variant.in_stock : product.in_stock;
35
+
36
+    function choose(index: number, value: string) {
37
+        setChoice((current) =>
38
+            current.map((old, i) => (i === index ? value : old)),
39
+        );
40
+    }
41
+
42
+    /** Whether picking this value, with the other choices kept, gives something in stock. */
43
+    function isAvailable(index: number, value: string): boolean {
44
+        const wanted = choice.map((old, i) => (i === index ? value : old));
45
+
46
+        return product.variants.some(
47
+            (candidate) =>
48
+                candidate.in_stock &&
49
+                candidate.options.every((v, i) => v === wanted[i]),
50
+        );
51
+    }
52
+
17 53
     return (
18 54
         <main className="py-10 md:py-14">
19 55
             <Container>
@@ -61,25 +97,80 @@ export function ProductPage({ product }: { product: StoreProduct }) {
61 97
                         </h1>
62 98
 
63 99
                         <p className="mt-4 text-2xl font-semibold tabular-nums">
64
-                            {formatPrice(product.price)}
65
-                            {product.compare_at_price !== null && (
100
+                            {formatPrice(price)}
101
+                            {compareAt !== null && (
66 102
                                 <s className="ml-3 text-base font-normal text-(--sf-muted)">
67
-                                    {formatPrice(product.compare_at_price)}
103
+                                    {formatPrice(compareAt)}
68 104
                                 </s>
69 105
                             )}
70 106
                         </p>
71 107
 
72 108
                         <p className="mt-2 text-sm text-(--sf-muted)">
73
-                            {product.in_stock ? t.inStock : t.soldOut}
109
+                            {inStock ? t.inStock : t.soldOut}
74 110
                         </p>
75 111
 
112
+                        {product.options.length > 0 && (
113
+                            <div className="mt-6 space-y-5">
114
+                                {product.options.map((option, index) => (
115
+                                    <fieldset key={option.name}>
116
+                                        <legend className="text-sm font-medium">
117
+                                            {option.name}:{' '}
118
+                                            <span className="font-normal text-(--sf-muted)">
119
+                                                {choice[index]}
120
+                                            </span>
121
+                                        </legend>
122
+                                        <div className="mt-2 flex flex-wrap gap-2">
123
+                                            {option.values.map((value) => {
124
+                                                const chosen =
125
+                                                    choice[index] === value;
126
+                                                const available = isAvailable(
127
+                                                    index,
128
+                                                    value,
129
+                                                );
130
+
131
+                                                return (
132
+                                                    <button
133
+                                                        key={value}
134
+                                                        type="button"
135
+                                                        aria-pressed={chosen}
136
+                                                        aria-label={
137
+                                                            available
138
+                                                                ? value
139
+                                                                : `${value}, ${t.soldOut}`
140
+                                                        }
141
+                                                        onClick={() =>
142
+                                                            choose(index, value)
143
+                                                        }
144
+                                                        className={cn(
145
+                                                            'rounded-(--sf-radius) border px-4 py-2 text-sm transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary)',
146
+                                                            chosen
147
+                                                                ? 'border-(--sf-primary) bg-(--sf-primary) text-(--sf-primary-fg)'
148
+                                                                : 'border-(--sf-border) hover:bg-(--sf-surface)',
149
+                                                            !available &&
150
+                                                                'text-(--sf-muted) line-through',
151
+                                                        )}
152
+                                                    >
153
+                                                        {value}
154
+                                                    </button>
155
+                                                );
156
+                                            })}
157
+                                        </div>
158
+                                    </fieldset>
159
+                                ))}
160
+                            </div>
161
+                        )}
162
+
76 163
                         {product.description && (
77 164
                             <p className="mt-6 leading-relaxed whitespace-pre-line text-(--sf-muted)">
78 165
                                 {product.description}
79 166
                             </p>
80 167
                         )}
81 168
 
82
-                        <AddToCart product={product} />
169
+                        <AddToCart
170
+                            product={product}
171
+                            variant={variant}
172
+                            key={variant?.id ?? 'simple'}
173
+                        />
83 174
                     </div>
84 175
                 </div>
85 176
             </Container>
@@ -87,7 +178,13 @@ export function ProductPage({ product }: { product: StoreProduct }) {
87 178
     );
88 179
 }
89 180
 
90
-function AddToCart({ product }: { product: StoreProduct }) {
181
+function AddToCart({
182
+    product,
183
+    variant,
184
+}: {
185
+    product: StoreProduct;
186
+    variant: StoreVariant | null;
187
+}) {
91 188
     const { baseUrl, language, cart } = useStorefront();
92 189
     const t = storefrontText(language);
93 190
     const [quantity, setQuantity] = useState(1);
@@ -95,17 +192,26 @@ function AddToCart({ product }: { product: StoreProduct }) {
95 192
     const [added, setAdded] = useState(false);
96 193
     const [error, setError] = useState<string | null>(null);
97 194
 
195
+    const needsChoice = product.options.length > 0 && variant === null;
196
+    const lineKey = variant
197
+        ? `${product.id}-${variant.id}`
198
+        : String(product.id);
199
+    const stockLeft = variant ? variant.stock_left : product.stock_left;
200
+    const inStock = variant ? variant.in_stock : product.in_stock;
98 201
     const inCart =
99
-        cart.lines.find((line) => line.product.id === product.id)?.quantity ??
100
-        0;
101
-    const max = Math.max(0, Math.min(product.stock_left, 99) - inCart);
102
-    const canAdd = product.in_stock && max > 0;
202
+        cart.lines.find((line) => line.key === lineKey)?.quantity ?? 0;
203
+    const max = Math.max(0, Math.min(stockLeft, 99) - inCart);
204
+    const canAdd = !needsChoice && inStock && max > 0;
103 205
 
104 206
     function add() {
105 207
         setError(null);
106 208
         router.post(
107 209
             `${baseUrl}/cart/items`,
108
-            { product_id: product.id, quantity: Math.min(quantity, max) },
210
+            {
211
+                product_id: product.id,
212
+                variant_id: variant?.id ?? null,
213
+                quantity: Math.min(quantity, max),
214
+            },
109 215
             {
110 216
                 preserveScroll: true,
111 217
                 onStart: () => setBusy(true),
@@ -115,7 +221,12 @@ function AddToCart({ product }: { product: StoreProduct }) {
115 221
                     setQuantity(1);
116 222
                 },
117 223
                 onError: (errors) =>
118
-                    setError(errors.quantity ?? errors.product_id ?? null),
224
+                    setError(
225
+                        errors.quantity ??
226
+                            errors.variant_id ??
227
+                            errors.product_id ??
228
+                            null,
229
+                    ),
119 230
             },
120 231
         );
121 232
     }
@@ -134,9 +245,9 @@ function AddToCart({ product }: { product: StoreProduct }) {
134 245
                         decreaseLabel={t.decrease}
135 246
                         increaseLabel={t.increase}
136 247
                     />
137
-                    {product.stock_left <= 5 && (
248
+                    {stockLeft <= 5 && (
138 249
                         <span className="text-sm text-(--sf-muted)">
139
-                            {t.onlyLeft(product.stock_left)}
250
+                            {t.onlyLeft(stockLeft)}
140 251
                         </span>
141 252
                     )}
142 253
                 </div>
@@ -148,7 +259,11 @@ function AddToCart({ product }: { product: StoreProduct }) {
148 259
                 disabled={!canAdd || busy}
149 260
                 className="inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
150 261
             >
151
-                {product.in_stock ? t.addToCart : t.soldOut}
262
+                {needsChoice
263
+                    ? t.unavailable
264
+                    : inStock
265
+                      ? t.addToCart
266
+                      : t.soldOut}
152 267
             </button>
153 268
 
154 269
             <div aria-live="polite" className="mt-3 min-h-6 text-sm">

+ 7
- 2
resources/js/storefront/product-card.tsx Vedi File

@@ -33,12 +33,17 @@ export function ProductImage({
33 33
 }
34 34
 
35 35
 export function Price({ product }: { product: StoreProduct }) {
36
+    const { language } = useStorefront();
37
+    const t = storefrontText(language);
38
+
36 39
     return (
37 40
         <p className="text-sm tabular-nums">
38 41
             <span className="text-(--sf-muted)">
39
-                {formatPrice(product.price)}
42
+                {product.price_varies
43
+                    ? t.from(formatPrice(product.price))
44
+                    : formatPrice(product.price)}
40 45
             </span>
41
-            {product.compare_at_price !== null && (
46
+            {!product.price_varies && product.compare_at_price !== null && (
42 47
                 <s className="ml-2 text-(--sf-muted) opacity-70">
43 48
                     {formatPrice(product.compare_at_price)}
44 49
                 </s>

+ 9
- 6
resources/js/storefront/sections/featured-product.tsx Vedi File

@@ -61,12 +61,15 @@ export function FeaturedProduct({
61 61
                             className="mt-3 text-2xl font-semibold tabular-nums"
62 62
                             data-test="featured-price"
63 63
                         >
64
-                            {formatPrice(product.price)}
65
-                            {product.compare_at_price !== null && (
66
-                                <s className="ml-3 text-base font-normal text-(--sf-muted)">
67
-                                    {formatPrice(product.compare_at_price)}
68
-                                </s>
69
-                            )}
64
+                            {product.price_varies
65
+                                ? t.from(formatPrice(product.price))
66
+                                : formatPrice(product.price)}
67
+                            {!product.price_varies &&
68
+                                product.compare_at_price !== null && (
69
+                                    <s className="ml-3 text-base font-normal text-(--sf-muted)">
70
+                                        {formatPrice(product.compare_at_price)}
71
+                                    </s>
72
+                                )}
70 73
                         </p>
71 74
                     )}
72 75
                     {showExamplePrice && (

+ 6
- 0
resources/js/storefront/text.ts Vedi File

@@ -9,6 +9,9 @@ const words = {
9 9
         viewAll: 'View all',
10 10
         soldOut: 'Sold out',
11 11
         viewProduct: 'View product',
12
+        from: (amount: string) => `From ${amount}`,
13
+        chooseOption: 'Please choose an option first.',
14
+        unavailable: 'Not available',
12 15
         inStock: 'In stock',
13 16
         addToCart: 'Add to cart',
14 17
         quantity: 'Quantity',
@@ -85,6 +88,9 @@ const words = {
85 88
         viewAll: 'Lihat semua',
86 89
         soldOut: 'Habis dijual',
87 90
         viewProduct: 'Lihat produk',
91
+        from: (amount: string) => `Dari ${amount}`,
92
+        chooseOption: 'Sila pilih satu pilihan dahulu.',
93
+        unavailable: 'Tiada',
88 94
         inStock: 'Ada stok',
89 95
         addToCart: 'Tambah ke troli',
90 96
         quantity: 'Kuantiti',

+ 21
- 0
resources/js/storefront/types.ts Vedi File

@@ -171,10 +171,31 @@ export type StoreProduct = {
171 171
     stock_left: number;
172 172
     image: string | null;
173 173
     images: string[];
174
+    /** Up to 2 options, such as Size. Empty for a simple product. */
175
+    options: { name: string; values: string[] }[];
176
+    variants: StoreVariant[];
177
+    /** True when variants cost different amounts, so lists show "From RM X". */
178
+    price_varies: boolean;
179
+};
180
+
181
+/** One combination of a product's options, such as "500g / Pedas". Prices in ringgit. */
182
+export type StoreVariant = {
183
+    id: number;
184
+    name: string;
185
+    /** The chosen value of each option, in order. */
186
+    options: string[];
187
+    price: number;
188
+    compare_at_price: number | null;
189
+    in_stock: boolean;
190
+    stock_left: number;
174 191
 };
175 192
 
176 193
 export type CartLine = {
194
+    /** The line's name in the cart: the product id, or "product-variant". */
195
+    key: string;
177 196
     product: StoreProduct;
197
+    variant: { id: number; name: string } | null;
198
+    unit_price: number;
178 199
     quantity: number;
179 200
     /** The most the shopper may choose, from the stock. */
180 201
     max: number;

+ 12
- 0
resources/js/types/store.ts Vedi File

@@ -62,11 +62,23 @@ export type Product = {
62 62
     price: string;
63 63
     compare_at_price: string | null;
64 64
     stock: number;
65
+    /** Options with their choices as one comma-separated line, such as "250g, 500g". */
66
+    options: { name: string; values: string }[];
67
+    variants: ProductVariantRow[];
65 68
     status: 'draft' | 'active';
66 69
     status_label: string;
67 70
     images: { id: number; url: string }[];
68 71
 };
69 72
 
73
+/** One combination of a product's options in the dashboard. Prices are text in ringgit. */
74
+export type ProductVariantRow = {
75
+    option1: string;
76
+    option2: string | null;
77
+    price: string;
78
+    compare_at_price: string | null;
79
+    stock: number;
80
+};
81
+
70 82
 export type StoreSummary = {
71 83
     name: string;
72 84
     slug: string;

+ 4
- 4
routes/web.php Vedi File

@@ -35,8 +35,8 @@ Route::domain('{storeSlug}.'.config('storefront.domain'))
35 35
 
36 36
         Route::get('cart', [CartController::class, 'show'])->name('cart');
37 37
         Route::post('cart/items', [CartController::class, 'add'])->name('cart.add');
38
-        Route::patch('cart/items/{product}', [CartController::class, 'update'])->name('cart.update')->whereNumber('product');
39
-        Route::delete('cart/items/{product}', [CartController::class, 'remove'])->name('cart.remove')->whereNumber('product');
38
+        Route::patch('cart/items/{line}', [CartController::class, 'update'])->name('cart.update')->where('line', '[0-9]+(?:-[0-9]+)?');
39
+        Route::delete('cart/items/{line}', [CartController::class, 'remove'])->name('cart.remove')->where('line', '[0-9]+(?:-[0-9]+)?');
40 40
         Route::post('cart/discount', [CartController::class, 'applyDiscount'])->middleware('throttle:20,1')->name('cart.discount');
41 41
         Route::delete('cart/discount', [CartController::class, 'removeDiscount'])->name('cart.discount.remove');
42 42
 
@@ -73,8 +73,8 @@ Route::middleware(['auth', 'verified'])->group(function () {
73 73
 
74 74
     Route::get('stores/{slug}/preview/cart', [CartController::class, 'show'])->name('stores.preview.cart');
75 75
     Route::post('stores/{slug}/preview/cart/items', [CartController::class, 'add'])->name('stores.preview.cart.add');
76
-    Route::patch('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'update'])->name('stores.preview.cart.update')->whereNumber('product');
77
-    Route::delete('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'remove'])->name('stores.preview.cart.remove')->whereNumber('product');
76
+    Route::patch('stores/{slug}/preview/cart/items/{line}', [CartController::class, 'update'])->name('stores.preview.cart.update')->where('line', '[0-9]+(?:-[0-9]+)?');
77
+    Route::delete('stores/{slug}/preview/cart/items/{line}', [CartController::class, 'remove'])->name('stores.preview.cart.remove')->where('line', '[0-9]+(?:-[0-9]+)?');
78 78
     Route::post('stores/{slug}/preview/cart/discount', [CartController::class, 'applyDiscount'])->name('stores.preview.cart.discount');
79 79
     Route::delete('stores/{slug}/preview/cart/discount', [CartController::class, 'removeDiscount'])->name('stores.preview.cart.discount.remove');
80 80
 

+ 298
- 0
tests/Feature/Stores/ProductVariantTest.php Vedi File

@@ -0,0 +1,298 @@
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\Store;
9
+use App\Models\User;
10
+use App\StorePlan\SamplePlan;
11
+use Illuminate\Foundation\Testing\RefreshDatabase;
12
+use Illuminate\Support\Facades\Mail;
13
+use Inertia\Testing\AssertableInertia as Assert;
14
+use Tests\Support\FakeGateway;
15
+use Tests\TestCase;
16
+
17
+class ProductVariantTest extends TestCase
18
+{
19
+    use RefreshDatabase;
20
+
21
+    private User $user;
22
+
23
+    private Store $store;
24
+
25
+    protected function setUp(): void
26
+    {
27
+        parent::setUp();
28
+
29
+        Mail::fake();
30
+
31
+        $this->user = User::factory()->create();
32
+        $this->store = Store::factory()->for($this->user)->create();
33
+        $this->store->plan = SamplePlan::for($this->store);
34
+        $this->store->save();
35
+        $this->actingAs($this->user);
36
+    }
37
+
38
+    /**
39
+     * A sambal in two sizes and two flavours: four combinations.
40
+     *
41
+     * @return array<string, mixed>
42
+     */
43
+    private function form(array $overrides = []): array
44
+    {
45
+        return [
46
+            'name' => 'Sambal',
47
+            'description' => '',
48
+            'status' => 'active',
49
+            'options' => [
50
+                ['name' => 'Size', 'values' => '250g, 500g'],
51
+                ['name' => 'Flavour', 'values' => 'Original, Pedas'],
52
+            ],
53
+            'variants' => [
54
+                ['option1' => '250g', 'option2' => 'Original', 'price' => '12.90', 'stock' => 10],
55
+                ['option1' => '250g', 'option2' => 'Pedas', 'price' => '12.90', 'stock' => 0],
56
+                ['option1' => '500g', 'option2' => 'Original', 'price' => '22.90', 'compare_at_price' => '25.00', 'stock' => 5],
57
+                ['option1' => '500g', 'option2' => 'Pedas', 'price' => '22.90', 'stock' => 3],
58
+            ],
59
+            ...$overrides,
60
+        ];
61
+    }
62
+
63
+    private function createProduct(array $overrides = []): Product
64
+    {
65
+        $this->post(route('stores.products.store', $this->store->slug), $this->form($overrides))
66
+            ->assertSessionHasNoErrors();
67
+
68
+        return $this->store->products()->latest('id')->firstOrFail();
69
+    }
70
+
71
+    private function variant(Product $product, string $first, ?string $second = null)
72
+    {
73
+        return $product->variants()->where('option1', $first)->where('option2', $second)->firstOrFail();
74
+    }
75
+
76
+    private function addToCart(Product $product, ?int $variantId, int $quantity = 1)
77
+    {
78
+        return $this->post(route('stores.preview.cart.add', $this->store->slug), [
79
+            'product_id' => $product->id,
80
+            'variant_id' => $variantId,
81
+            'quantity' => $quantity,
82
+        ]);
83
+    }
84
+
85
+    public function test_a_product_can_have_options_with_a_price_and_stock_for_each_combination()
86
+    {
87
+        $product = $this->createProduct();
88
+
89
+        $this->assertSame([
90
+            ['name' => 'Size', 'values' => ['250g', '500g']],
91
+            ['name' => 'Flavour', 'values' => ['Original', 'Pedas']],
92
+        ], $product->options);
93
+        $this->assertCount(4, $product->variants);
94
+        $this->assertSame(['250g / Original', '250g / Pedas', '500g / Original', '500g / Pedas'], $product->variants->map->name()->all());
95
+        $this->assertSame(2500, $this->variant($product, '500g', 'Original')->compare_at_price);
96
+
97
+        // The product itself shows the lowest price and all the stock together.
98
+        $this->assertSame(1290, $product->price);
99
+        $this->assertSame(18, $product->stock);
100
+
101
+        $this->get(route('stores.products.edit', [$this->store->slug, $product->id]))
102
+            ->assertInertia(fn (Assert $page) => $page
103
+                ->where('product.options.0.values', '250g, 500g')
104
+                ->has('product.variants', 4)
105
+                ->where('product.variants.2.price', '22.90'));
106
+    }
107
+
108
+    public function test_a_single_option_works_too()
109
+    {
110
+        $product = $this->createProduct([
111
+            'options' => [['name' => 'Size', 'values' => 'S, M, L']],
112
+            'variants' => [
113
+                ['option1' => 'S', 'price' => '30', 'stock' => 1],
114
+                ['option1' => 'M', 'price' => '30', 'stock' => 2],
115
+                ['option1' => 'L', 'price' => '32', 'stock' => 3],
116
+            ],
117
+        ]);
118
+
119
+        $this->assertSame(['S', 'M', 'L'], $product->variants->map->name()->all());
120
+        $this->assertNull($this->variant($product, 'L')->option2);
121
+    }
122
+
123
+    public function test_every_combination_needs_a_price_and_stock()
124
+    {
125
+        $form = $this->form();
126
+        array_pop($form['variants']);
127
+
128
+        $this->post(route('stores.products.store', $this->store->slug), $form)->assertSessionHasErrors('variants');
129
+
130
+        $this->post(route('stores.products.store', $this->store->slug), $this->form([
131
+            'options' => [['name' => 'Size', 'values' => ' , ']],
132
+        ]))->assertSessionHasErrors('options.0.values');
133
+
134
+        $this->post(route('stores.products.store', $this->store->slug), $this->form([
135
+            'options' => [['name' => 'Size', 'values' => 'S'], ['name' => 'size', 'values' => 'M']],
136
+        ]))->assertSessionHasErrors('options');
137
+
138
+        $this->assertSame(0, $this->store->products()->count());
139
+    }
140
+
141
+    public function test_editing_keeps_variants_whose_choices_did_not_change()
142
+    {
143
+        $product = $this->createProduct();
144
+        $kept = $this->variant($product, '500g', 'Pedas');
145
+
146
+        $form = $this->form([
147
+            'options' => [
148
+                ['name' => 'Size', 'values' => '500g, 1kg'],
149
+                ['name' => 'Flavour', 'values' => 'Original, Pedas'],
150
+            ],
151
+            'variants' => [
152
+                ['option1' => '500g', 'option2' => 'Original', 'price' => '22.90', 'stock' => 5],
153
+                ['option1' => '500g', 'option2' => 'Pedas', 'price' => '21.00', 'stock' => 9],
154
+                ['option1' => '1kg', 'option2' => 'Original', 'price' => '40.00', 'stock' => 2],
155
+                ['option1' => '1kg', 'option2' => 'Pedas', 'price' => '40.00', 'stock' => 2],
156
+            ],
157
+        ]);
158
+
159
+        $this->post(route('stores.products.update', [$this->store->slug, $product->id]), $form)->assertSessionHasNoErrors();
160
+
161
+        $product->refresh();
162
+        $this->assertCount(4, $product->variants);
163
+        $this->assertSame($kept->id, $this->variant($product, '500g', 'Pedas')->id);
164
+        $this->assertSame(2100, $kept->fresh()->price);
165
+        $this->assertSame(0, $product->variants()->where('option1', '250g')->count());
166
+        $this->assertSame(2100, $product->price);
167
+        $this->assertSame(18, $product->stock);
168
+    }
169
+
170
+    public function test_turning_options_off_makes_it_a_simple_product_again()
171
+    {
172
+        $product = $this->createProduct();
173
+
174
+        $this->post(route('stores.products.update', [$this->store->slug, $product->id]), [
175
+            'name' => 'Sambal', 'status' => 'active', 'price' => '15.00', 'stock' => 7,
176
+        ])->assertSessionHasNoErrors();
177
+
178
+        $product->refresh();
179
+        $this->assertNull($product->options);
180
+        $this->assertCount(0, $product->variants);
181
+        $this->assertSame(1500, $product->price);
182
+        $this->assertSame(7, $product->stock);
183
+    }
184
+
185
+    public function test_the_store_gets_the_options_and_a_from_price()
186
+    {
187
+        $product = $this->createProduct();
188
+
189
+        $this->get(route('stores.preview.product', [$this->store->slug, $product->slug]))
190
+            ->assertInertia(fn (Assert $page) => $page
191
+                ->where('view.product.price_varies', true)
192
+                ->where('view.product.options.0.name', 'Size')
193
+                ->has('view.product.variants', 4)
194
+                ->where('view.product.variants.1.name', '250g / Pedas')
195
+                ->where('view.product.variants.1.in_stock', false)
196
+                ->where('view.product.variants.2.price', 22.9)
197
+                ->where('view.product.variants.2.compare_at_price', 25));
198
+    }
199
+
200
+    public function test_shoppers_must_choose_a_variant_and_each_one_has_its_own_cart_line()
201
+    {
202
+        $product = $this->createProduct();
203
+        $small = $this->variant($product, '250g', 'Original');
204
+        $big = $this->variant($product, '500g', 'Pedas');
205
+        $soldOut = $this->variant($product, '250g', 'Pedas');
206
+        $elsewhere = $this->store->products()->create(['name' => 'Other', 'price' => 100, 'stock' => 1, 'status' => 'active']);
207
+
208
+        $this->addToCart($product, null)->assertSessionHasErrors('variant_id');
209
+        $this->addToCart($product, $soldOut->id)->assertSessionHasErrors('quantity');
210
+        $this->addToCart($elsewhere, $small->id)->assertNotFound();
211
+
212
+        $this->addToCart($product, $small->id, 2)->assertSessionHasNoErrors();
213
+        $this->addToCart($product, $big->id, 5)->assertSessionHasNoErrors();
214
+
215
+        $this->get(route('stores.preview.cart', $this->store->slug))
216
+            ->assertInertia(fn (Assert $page) => $page
217
+                ->has('cart.lines', 2)
218
+                ->where('cart.lines.0.key', $product->id.'-'.$small->id)
219
+                ->where('cart.lines.0.variant.name', '250g / Original')
220
+                ->where('cart.lines.0.unit_price', 12.9)
221
+                ->where('cart.lines.0.line_total', 25.8)
222
+                // Only 3 of the big spicy one are in stock.
223
+                ->where('cart.lines.1.quantity', 3)
224
+                ->where('cart.lines.1.max', 3)
225
+                ->where('cart.subtotal', 94.5));
226
+
227
+        $line = $product->id.'-'.$big->id;
228
+        $this->patch(route('stores.preview.cart.update', [$this->store->slug, $line]), ['quantity' => 1])->assertRedirect();
229
+        $this->delete(route('stores.preview.cart.remove', [$this->store->slug, $product->id.'-'.$small->id]))->assertRedirect();
230
+
231
+        $this->get(route('stores.preview.cart', $this->store->slug))
232
+            ->assertInertia(fn (Assert $page) => $page
233
+                ->has('cart.lines', 1)
234
+                ->where('cart.lines.0.quantity', 1)
235
+                ->where('cart.subtotal', 22.9));
236
+    }
237
+
238
+    public function test_a_variant_removed_after_it_was_added_drops_out_of_the_cart()
239
+    {
240
+        $product = $this->createProduct();
241
+        $big = $this->variant($product, '500g', 'Pedas');
242
+        $this->addToCart($product, $big->id);
243
+
244
+        $big->delete();
245
+
246
+        $this->get(route('stores.preview.cart', $this->store->slug))
247
+            ->assertInertia(fn (Assert $page) => $page->has('cart.lines', 0)->where('cart.adjusted', true));
248
+    }
249
+
250
+    public function test_paying_lowers_the_stock_of_the_chosen_variant_and_the_order_names_it()
251
+    {
252
+        $gateway = new FakeGateway;
253
+        $this->app->instance(PaymentGateway::class, $gateway);
254
+
255
+        $product = $this->createProduct();
256
+        $big = $this->variant($product, '500g', 'Original');
257
+        $this->addToCart($product, $big->id, 2);
258
+
259
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
260
+            'name' => 'Aminah', 'email' => 'a@example.com', 'phone' => '0123456789',
261
+            'line1' => '12 Jalan Mawar', 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor',
262
+        ])->assertRedirect();
263
+
264
+        $order = Order::with('items')->firstOrFail();
265
+        $item = $order->items->first();
266
+
267
+        $this->assertSame('Sambal (500g / Original)', $item->name);
268
+        $this->assertSame('500g / Original', $item->variant_name);
269
+        $this->assertSame($big->id, $item->variant_id);
270
+        $this->assertSame(2290, $item->unit_price);
271
+        $this->assertSame(4580, $order->subtotal);
272
+
273
+        $gateway->pay($order);
274
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
275
+
276
+        $this->assertSame(3, $big->fresh()->stock);
277
+        // The product's own stock is all its variants together.
278
+        $this->assertSame(16, $product->fresh()->stock);
279
+
280
+        // Deleting the variant later keeps the order's record.
281
+        $big->delete();
282
+        $this->assertNull($item->fresh()->variant_id);
283
+        $this->assertSame('Sambal (500g / Original)', $item->fresh()->name);
284
+    }
285
+
286
+    public function test_simple_products_still_work_without_a_variant()
287
+    {
288
+        $product = $this->store->products()->create(['name' => 'Kerepek', 'price' => 500, 'stock' => 4, 'status' => 'active']);
289
+
290
+        $this->addToCart($product, null, 2)->assertSessionHasNoErrors();
291
+
292
+        $this->get(route('stores.preview.cart', $this->store->slug))
293
+            ->assertInertia(fn (Assert $page) => $page
294
+                ->where('cart.lines.0.key', (string) $product->id)
295
+                ->where('cart.lines.0.variant', null)
296
+                ->where('cart.lines.0.unit_price', 5));
297
+    }
298
+}

Loading…
Annulla
Salva