Просмотр исходного кода

Add discount codes

- Discounts tab: percent or fixed off, min spend, dates, usage limit
- Code box in cart; discount on products only, not shipping
- Orders save code and amount; Stripe shows it as a coupon
- Use counted only when the order is paid
feature/discount-codes
fahmisaad 4 дней назад
Родитель
Сommit
99621929a1

+ 62
- 46
PROGRESS.md Просмотреть файл

@@ -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 7 — Malaysia features (part 1 done, plus the featured product fix; part 2 needs EasyParcel and WhatsApp Business accounts)
8
-**Next action:** Merge `feature/malaysia-shipping`, then `feature/featured-product-link` (built on top of it), into `main`. Then either Step 7 part 2 (needs an EasyParcel demo account and API key) or go on to Step 8 (discounts) and come back to part 2 later
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
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -130,6 +130,19 @@ Changing from Claude to another AI model (or back) must be a settings change, no
130 130
 - WhatsApp numbers are saved as digits with country code (`60123456789`). Only Malaysian numbers are accepted. `MalaysianPhone` does the cleaning.
131 131
 - Messages the server shows to shoppers live in `App\Storefront\StorefrontText`; words drawn in the browser live in `resources/js/storefront/text.ts`.
132 132
 
133
+### How discount codes work (added in Step 8)
134
+
135
+- Codes live in the `discount_codes` table, per store, saved in capital letters. Shoppers may type them in any case.
136
+- A code takes money off the **products only**, never off shipping. Percentages are rounded down to the sen. A fixed amount never takes off more than the products cost.
137
+- Free shipping is judged on the product price **after** the discount.
138
+- The code in a cart is kept in the shopper's session. The cart checks it every time: a code that was switched off, expired or used up is taken out, and the shopper is told. A code that needs a bigger cart stays, with a "spend at least RM X" message, and is worth nothing until then.
139
+- If the code stopped working between the cart and paying, checkout stops with a message, so the total never surprises the shopper.
140
+- After the discount, the order total must still be at least RM 2.00 (Stripe's minimum).
141
+- The order saves `discount_code` and `discount_total`. Deleting or changing a code later never changes old orders.
142
+- A code counts as used only when its order is **paid**, once per order. Two shoppers paying at the same moment could both use the last remaining use; this is accepted.
143
+- Stripe gets a one-off coupon worth exactly the discount, so its page shows the code and the saving.
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
+
133 146
 ### How the featured product section works (fixed in Step 7)
134 147
 
135 148
 - 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.
@@ -254,7 +267,7 @@ Part 2 (needs outside accounts):
254 267
 
255 268
 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.
256 269
 
257
-- [ ] Discount codes: a "Discounts" tab for the merchant (code, percent or fixed amount off, optional minimum spend, start and end date, usage limit); a "Discount code" box in the cart; the order records the code and the amount taken off; the final amount is sent to Stripe
270
+- [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
258 271
 - [ ] Product variants: size, colour, flavour and so on, each with its own price and stock
259 272
 - [ ] 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
260 273
 - [ ] 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
@@ -315,49 +328,51 @@ Then, from the project folder:
315 328
 
316 329
 ## 4b. Where things are in the code
317 330
 
318
-| Thing                                  | Location                                                                                       |
319
-| -------------------------------------- | ---------------------------------------------------------------------------------------------- |
320
-| Store model                            | `app/Models/Store.php`                                                                         |
321
-| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                     |
322
-| Store categories, languages, statuses  | `app/Enums/`                                                                                   |
323
-| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                              |
324
-| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                               |
325
-| Store tests                            | `tests/Feature/Stores/`                                                                        |
326
-| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                 |
327
-| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                              |
328
-| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                 |
329
-| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                               |
330
-| AI settings                            | `config/ai.php` (providers, models per task)                                                   |
331
-| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                   |
332
-| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                            |
333
-| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                           |
334
-| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                              |
335
-| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                              |
336
-| Progress screen and chat box           | `resources/js/components/stores/`                                                              |
337
-| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                        |
338
-| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                   |
339
-| Product screens                        | `resources/js/pages/stores/products/`                                                          |
340
-| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                               |
341
-| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                     |
342
-| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                |
343
-| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                |
344
-| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                |
345
-| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                               |
346
-| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                |
347
-| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                               |
348
-| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                              |
349
-| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`    |
350
-| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                 |
351
-| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                    |
352
-| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php` |
353
-| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                       |
354
-| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                           |
355
-| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                       |
356
-| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                         |
357
-| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                             |
358
-| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                              |
359
-| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                             |
360
-| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                    |
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/`                                              |
361 376
 
362 377
 ## 5. Open questions
363 378
 
@@ -422,3 +437,4 @@ Add one line per work session: date, what was done, what is next.
422 437
 | 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.         | Merge, then Step 7 part 2 or Step 8                             |
423 438
 | 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               |
424 439
 | 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
+| 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                                    |

+ 2
- 1
README.md Просмотреть файл

@@ -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 | Not started                                                    |
23
+| 8    | Discounts and product options: codes, variants, bundles | In progress: discount codes done; variants next                |
24 24
 | 9    | Before launch: hosting, legal pages, backups            | Not started                                                    |
25 25
 
26 26
 ## What works today
@@ -47,6 +47,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
47 47
 - Design changes stay private until the merchant clicks "Publish changes"
48 48
 - Shipping fees for Peninsular and East Malaysia, with optional free shipping, and "mark as shipped" with a tracking number
49 49
 - WhatsApp chat button on the store, and WhatsApp links on order pages
50
+- Discount codes: percent or fixed amount off, with optional minimum spend, dates and number of uses
50 51
 - Billing: 14-day free trial, then Starter, Growth or Pro through Stripe. Merchants can switch or cancel on the Billing page, and plan limits are enforced
51 52
 
52 53
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.

+ 19
- 0
app/Commerce/AppliedDiscount.php Просмотреть файл

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Models\DiscountCode;
6
+
7
+/**
8
+ * The discount code in a cart and what it is worth right now. Amounts are in sen.
9
+ */
10
+final readonly class AppliedDiscount
11
+{
12
+    public function __construct(
13
+        public DiscountCode $code,
14
+        /** What comes off the products. Zero while the code cannot be used. */
15
+        public int $amount,
16
+        /** Why the code cannot be used yet (a StorefrontText key), or null when it works. */
17
+        public ?string $problem,
18
+    ) {}
19
+}

+ 89
- 3
app/Commerce/Cart.php Просмотреть файл

@@ -2,8 +2,10 @@
2 2
 
3 3
 namespace App\Commerce;
4 4
 
5
+use App\Models\DiscountCode;
5 6
 use App\Models\Product;
6 7
 use App\Models\Store;
8
+use App\Storefront\StorefrontText;
7 9
 use Illuminate\Contracts\Session\Session;
8 10
 use Illuminate\Support\Collection;
9 11
 
@@ -22,6 +24,9 @@ class Cart
22 24
     /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
23 25
     private bool $adjusted = false;
24 26
 
27
+    /** True when the discount code was taken out because it can no longer be used. */
28
+    private bool $discountRemoved = false;
29
+
25 30
     public function __construct(
26 31
         private readonly Session $session,
27 32
         private readonly Store $store,
@@ -71,6 +76,68 @@ class Cart
71 76
     public function clear(): void
72 77
     {
73 78
         $this->session->forget($this->key());
79
+        $this->session->forget($this->discountKey());
80
+    }
81
+
82
+    /**
83
+     * Put a discount code in the cart. Returns the problem (a StorefrontText key) when the code
84
+     * does not exist or cannot be used at all; a code that only needs a bigger cart is kept.
85
+     */
86
+    public function applyCode(string $code): ?string
87
+    {
88
+        $discount = $this->store->discountCodes()->where('code', DiscountCode::normalize($code))->first();
89
+
90
+        if ($discount === null) {
91
+            return 'discount_invalid';
92
+        }
93
+
94
+        $problem = $discount->problemFor((int) $this->lines()->sum('line_total'));
95
+
96
+        if ($problem !== null && $problem !== 'discount_minimum') {
97
+            return $problem;
98
+        }
99
+
100
+        $this->session->put($this->discountKey(), $discount->code);
101
+
102
+        return null;
103
+    }
104
+
105
+    /**
106
+     * True when the last discount() call took the code out because it can no longer be used.
107
+     */
108
+    public function discountWasRemoved(): bool
109
+    {
110
+        return $this->discountRemoved;
111
+    }
112
+
113
+    public function removeCode(): void
114
+    {
115
+        $this->session->forget($this->discountKey());
116
+    }
117
+
118
+    /**
119
+     * The code in the cart and what it is worth for these products.
120
+     * A code that was deleted, switched off, expired or used up is taken out, and the cart says so once.
121
+     */
122
+    public function discount(int $subtotal): ?AppliedDiscount
123
+    {
124
+        $code = $this->session->get($this->discountKey());
125
+
126
+        if (! is_string($code)) {
127
+            return null;
128
+        }
129
+
130
+        $discount = $this->store->discountCodes()->where('code', $code)->first();
131
+        $problem = $discount?->problemFor($subtotal);
132
+
133
+        if ($discount === null || ($problem !== null && $problem !== 'discount_minimum')) {
134
+            $this->removeCode();
135
+            $this->discountRemoved = true;
136
+
137
+            return null;
138
+        }
139
+
140
+        return new AppliedDiscount($discount, $problem === null ? $discount->amountFor($subtotal) : 0, $problem);
74 141
     }
75 142
 
76 143
     /**
@@ -127,16 +194,30 @@ class Cart
127 194
     /**
128 195
      * What the storefront is allowed to see. Money is in ringgit here.
129 196
      *
130
-     * @return array{count: int, subtotal: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
197
+     * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
131 198
      */
132 199
     public function toStorefront(): array
133 200
     {
134 201
         $lines = $this->lines();
202
+        $subtotal = (int) $lines->sum('line_total');
203
+        $discount = $lines->isEmpty() ? null : $this->discount($subtotal);
204
+        $language = $this->store->language->value;
135 205
 
136 206
         return [
137 207
             'count' => (int) $lines->sum('quantity'),
138
-            'subtotal' => $lines->sum('line_total') / 100,
139
-            'adjusted' => $this->adjusted,
208
+            'subtotal' => $subtotal / 100,
209
+            'discount' => $discount === null ? null : [
210
+                'code' => $discount->code->code,
211
+                'label' => $discount->code->label($language),
212
+                'amount' => $discount->amount / 100,
213
+                // Why it does not count yet, for example "Spend at least RM 50.00 ...".
214
+                'message' => $discount->problem === null ? null : StorefrontText::line($language, $discount->problem, [
215
+                    ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
216
+                ]),
217
+            ],
218
+            // Products after the discount, before shipping.
219
+            'total' => ($subtotal - ($discount !== null ? $discount->amount : 0)) / 100,
220
+            'adjusted' => $this->adjusted || $this->discountRemoved,
140 221
             'lines' => $lines->map(fn (array $line) => [
141 222
                 'product' => $line['product']->toStorefront(),
142 223
                 'quantity' => $line['quantity'],
@@ -180,4 +261,9 @@ class Cart
180 261
     {
181 262
         return 'cart.'.$this->store->id;
182 263
     }
264
+
265
+    private function discountKey(): string
266
+    {
267
+        return 'cart_discount.'.$this->store->id;
268
+    }
183 269
 }

+ 32
- 3
app/Commerce/Checkout.php Просмотреть файл

@@ -6,6 +6,7 @@ use App\Commerce\Payments\PaymentStatus;
6 6
 use App\Commerce\Shipping\ShippingProvider;
7 7
 use App\Enums\OrderStatus;
8 8
 use App\Mail\OrderConfirmation;
9
+use App\Models\DiscountCode;
9 10
 use App\Models\Order;
10 11
 use App\Models\Product;
11 12
 use App\Models\Store;
@@ -49,9 +50,27 @@ class Checkout
49 50
             throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]);
50 51
         }
51 52
 
52
-        $shipping = $this->shipping->quote($store, $subtotal, $details['state']);
53
+        $language = $store->language->value;
54
+        $applied = $cart->discount($subtotal);
53 55
 
54
-        return DB::transaction(function () use ($store, $lines, $subtotal, $shipping, $details): Order {
56
+        // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
57
+        if ($cart->discountWasRemoved()) {
58
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]);
59
+        }
60
+
61
+        // A code that still needs a bigger cart is worth nothing; the cart already showed that.
62
+        $usable = $applied !== null && $applied->problem === null ? $applied : null;
63
+        $discount = $usable !== null ? $usable->amount : 0;
64
+        $discountCode = $usable !== null && $discount > 0 ? $usable->code->code : null;
65
+
66
+        // Free shipping is decided on what the shopper pays for the products, after the discount.
67
+        $shipping = $this->shipping->quote($store, $subtotal - $discount, $details['state']);
68
+
69
+        if ($subtotal - $discount + $shipping < self::MINIMUM_TOTAL) {
70
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_total_too_low')]);
71
+        }
72
+
73
+        return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $shipping, $details): Order {
55 74
             // Lock the store row so two orders placed at the same moment cannot get the same number.
56 75
             Store::query()->whereKey($store->id)->lockForUpdate()->first();
57 76
 
@@ -72,8 +91,10 @@ class Checkout
72 91
                 'country' => 'MY',
73 92
             ];
74 93
             $order->subtotal = $subtotal;
94
+            $order->discount_code = $discountCode;
95
+            $order->discount_total = $discount;
75 96
             $order->shipping_total = $shipping;
76
-            $order->total = $subtotal + $shipping;
97
+            $order->total = $subtotal - $discount + $shipping;
77 98
             $order->currency = 'MYR';
78 99
             $order->save();
79 100
 
@@ -136,6 +157,14 @@ class Checkout
136 157
                 }
137 158
             }
138 159
 
160
+            // A code counts as used only once the order is paid.
161
+            if ($locked->discount_code !== null) {
162
+                DiscountCode::query()
163
+                    ->where('store_id', $locked->store_id)
164
+                    ->where('code', $locked->discount_code)
165
+                    ->increment('times_used');
166
+            }
167
+
139 168
             return true;
140 169
         });
141 170
 

+ 20
- 0
app/Commerce/Payments/StripeGateway.php Просмотреть файл

@@ -40,6 +40,8 @@ final class StripeGateway implements PaymentGateway
40 40
                         'product_data' => ['name' => $item->name],
41 41
                     ],
42 42
                 ])->values()->all(),
43
+                // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
44
+                ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order)]]] : []),
43 45
                 // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
44 46
                 'shipping_options' => [[
45 47
                     'shipping_rate_data' => [
@@ -63,6 +65,24 @@ final class StripeGateway implements PaymentGateway
63 65
         return new CheckoutLink($session->id, $session->url);
64 66
     }
65 67
 
68
+    /**
69
+     * A coupon that can be used once, worth exactly this order's discount.
70
+     * Stripe takes it off the products only, never off shipping, which matches our own rule.
71
+     *
72
+     * @throws ApiErrorException
73
+     */
74
+    private function couponFor(Order $order): string
75
+    {
76
+        return $this->client()->coupons->create([
77
+            'amount_off' => $order->discount_total,
78
+            'currency' => strtolower($order->currency),
79
+            'duration' => 'once',
80
+            'max_redemptions' => 1,
81
+            'name' => (string) $order->discount_code,
82
+            'metadata' => ['order_id' => (string) $order->id],
83
+        ])->id;
84
+    }
85
+
66 86
     private function shippingLabel(Order $order): string
67 87
     {
68 88
         $malay = $order->store->language->value === 'ms';

+ 28
- 0
app/Http/Controllers/CartController.php Просмотреть файл

@@ -63,6 +63,34 @@ class CartController extends Controller
63 63
         return back();
64 64
     }
65 65
 
66
+    /**
67
+     * Put a discount code in the cart.
68
+     */
69
+    public function applyDiscount(Request $request): RedirectResponse
70
+    {
71
+        $store = $this->storefront($request)->store;
72
+        $language = $store->language->value;
73
+
74
+        $validated = $request->validate(['code' => ['required', 'string', 'max:40']], [
75
+            'code.required' => StorefrontText::line($language, 'discount_invalid'),
76
+        ]);
77
+
78
+        $problem = $this->cart($request, $store)->applyCode($validated['code']);
79
+
80
+        if ($problem !== null) {
81
+            throw ValidationException::withMessages(['code' => StorefrontText::line($language, $problem)]);
82
+        }
83
+
84
+        return back();
85
+    }
86
+
87
+    public function removeDiscount(Request $request): RedirectResponse
88
+    {
89
+        $this->cart($request, $this->storefront($request)->store)->removeCode();
90
+
91
+        return back();
92
+    }
93
+
66 94
     public function remove(Request $request): RedirectResponse
67 95
     {
68 96
         $store = $this->storefront($request)->store;

+ 5
- 1
app/Http/Controllers/CheckoutController.php Просмотреть файл

@@ -37,14 +37,18 @@ class CheckoutController extends Controller
37 37
             return redirect($storefront->path('/cart'));
38 38
         }
39 39
 
40
+        $cart = $this->cart($request, $storefront->store);
40 41
         $subtotal = (int) $lines->sum('line_total');
42
+        $applied = $cart->discount($subtotal);
43
+        // Shipping is worked out on what the shopper pays for the products, after any discount.
44
+        $afterDiscount = $subtotal - ($applied !== null ? $applied->amount : 0);
41 45
 
42 46
         return $this->renderStorefront($request, $storefront, [
43 47
             'type' => 'checkout',
44 48
             'states' => MalaysianStates::ALL,
45 49
             // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
46 50
             'shippingByState' => collect(MalaysianStates::ALL)
47
-                ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $subtotal, $state) / 100])
51
+                ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $afterDiscount, $state) / 100])
48 52
                 ->all(),
49 53
         ]);
50 54
     }

+ 187
- 0
app/Http/Controllers/DiscountCodeController.php Просмотреть файл

@@ -0,0 +1,187 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Models\DiscountCode;
6
+use App\Models\Store;
7
+use Illuminate\Http\RedirectResponse;
8
+use Illuminate\Http\Request;
9
+use Illuminate\Support\Carbon;
10
+use Illuminate\Validation\Rule;
11
+use Inertia\Inertia;
12
+use Inertia\Response;
13
+
14
+/**
15
+ * The merchant's discount codes for one store.
16
+ * Dates are typed and shown in Malaysian time; a code runs from the start of its first day to the end of its last day.
17
+ */
18
+class DiscountCodeController extends Controller
19
+{
20
+    private const string TIMEZONE = 'Asia/Kuala_Lumpur';
21
+
22
+    public function index(Request $request, string $slug): Response
23
+    {
24
+        $store = $this->ownedStore($request, $slug);
25
+
26
+        return Inertia::render('stores/discounts/index', [
27
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
28
+            'codes' => $store->discountCodes()->latest('id')->get()->map(fn (DiscountCode $code) => $this->present($code)),
29
+        ]);
30
+    }
31
+
32
+    public function create(Request $request, string $slug): Response
33
+    {
34
+        return Inertia::render('stores/discounts/form', [
35
+            'store' => $this->presentStore($this->ownedStore($request, $slug)),
36
+            'code' => null,
37
+        ]);
38
+    }
39
+
40
+    public function store(Request $request, string $slug): RedirectResponse
41
+    {
42
+        $store = $this->ownedStore($request, $slug);
43
+
44
+        $code = new DiscountCode;
45
+        $code->store_id = $store->id;
46
+        $this->fill($code, $this->validated($request, $store));
47
+        $code->save();
48
+
49
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Discount code :code created.', ['code' => $code->code])]);
50
+
51
+        return to_route('stores.discounts.index', $store->slug);
52
+    }
53
+
54
+    public function edit(Request $request, string $slug, int $discount): Response
55
+    {
56
+        $store = $this->ownedStore($request, $slug);
57
+
58
+        return Inertia::render('stores/discounts/form', [
59
+            'store' => $this->presentStore($store),
60
+            'code' => $this->present($this->ownedCode($store, $discount)),
61
+        ]);
62
+    }
63
+
64
+    public function update(Request $request, string $slug, int $discount): RedirectResponse
65
+    {
66
+        $store = $this->ownedStore($request, $slug);
67
+        $code = $this->ownedCode($store, $discount);
68
+
69
+        $this->fill($code, $this->validated($request, $store, $code));
70
+        $code->save();
71
+
72
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Discount code saved.')]);
73
+
74
+        return to_route('stores.discounts.index', $store->slug);
75
+    }
76
+
77
+    public function destroy(Request $request, string $slug, int $discount): RedirectResponse
78
+    {
79
+        $store = $this->ownedStore($request, $slug);
80
+
81
+        // Orders keep their own copy of the code and the amount, so deleting it changes no order.
82
+        $this->ownedCode($store, $discount)->delete();
83
+
84
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Discount code deleted.')]);
85
+
86
+        return to_route('stores.discounts.index', $store->slug);
87
+    }
88
+
89
+    /**
90
+     * @return array<string, mixed>
91
+     */
92
+    private function validated(Request $request, Store $store, ?DiscountCode $existing = null): array
93
+    {
94
+        $request->merge(['code' => DiscountCode::normalize((string) $request->input('code'))]);
95
+
96
+        $percent = $request->input('type') === DiscountCode::PERCENT;
97
+
98
+        return $request->validate([
99
+            'code' => [
100
+                'required', 'string', 'regex:'.DiscountCode::CODE_PATTERN,
101
+                Rule::unique('discount_codes', 'code')->where('store_id', $store->id)->ignore($existing?->id),
102
+            ],
103
+            'type' => ['required', Rule::in([DiscountCode::PERCENT, DiscountCode::FIXED])],
104
+            'value' => $percent
105
+                ? ['required', 'integer', 'min:1', 'max:100']
106
+                : ['required', 'numeric', 'decimal:0,2', 'min:0.01', 'max:999999.99'],
107
+            'minimum_subtotal' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
108
+            'starts_on' => ['nullable', 'date_format:Y-m-d'],
109
+            'ends_on' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:starts_on'],
110
+            'usage_limit' => ['nullable', 'integer', 'min:1', 'max:1000000'],
111
+            'active' => ['boolean'],
112
+        ], [
113
+            'code.regex' => __('Use 3 to 30 letters, numbers or dashes, such as RAYA10.'),
114
+            'code.unique' => __('This store already has that code.'),
115
+            'value.max' => $percent ? __('A percentage cannot be more than 100.') : __('The amount is too large.'),
116
+            'ends_on.after_or_equal' => __('The last day cannot be before the first day.'),
117
+        ]);
118
+    }
119
+
120
+    /**
121
+     * @param  array<string, mixed>  $data
122
+     */
123
+    private function fill(DiscountCode $code, array $data): void
124
+    {
125
+        $percent = $data['type'] === DiscountCode::PERCENT;
126
+
127
+        $code->code = $data['code'];
128
+        $code->type = $data['type'];
129
+        $code->value = $percent ? (int) $data['value'] : self::sen($data['value']);
130
+        $code->minimum_subtotal = filled($data['minimum_subtotal'] ?? null) ? self::sen($data['minimum_subtotal']) : null;
131
+        $code->starts_at = filled($data['starts_on'] ?? null) ? Carbon::parse($data['starts_on'], self::TIMEZONE)->startOfDay()->utc() : null;
132
+        $code->ends_at = filled($data['ends_on'] ?? null) ? Carbon::parse($data['ends_on'], self::TIMEZONE)->endOfDay()->utc() : null;
133
+        $code->usage_limit = filled($data['usage_limit'] ?? null) ? (int) $data['usage_limit'] : null;
134
+        $code->active = (bool) ($data['active'] ?? false);
135
+    }
136
+
137
+    /**
138
+     * What the dashboard is allowed to see. Amounts are text in ringgit, such as "12.50"; dates are Malaysian days.
139
+     *
140
+     * @return array<string, mixed>
141
+     */
142
+    private function present(DiscountCode $code): array
143
+    {
144
+        return [
145
+            'id' => $code->id,
146
+            'code' => $code->code,
147
+            'type' => $code->type,
148
+            'value' => $code->type === DiscountCode::PERCENT ? (string) $code->value : self::ringgit($code->value),
149
+            'label' => $code->label(),
150
+            'minimum_subtotal' => $code->minimum_subtotal !== null ? self::ringgit($code->minimum_subtotal) : null,
151
+            'starts_on' => $code->starts_at?->setTimezone(self::TIMEZONE)->format('Y-m-d'),
152
+            'ends_on' => $code->ends_at?->setTimezone(self::TIMEZONE)->format('Y-m-d'),
153
+            'usage_limit' => $code->usage_limit,
154
+            'times_used' => $code->times_used,
155
+            'active' => $code->active,
156
+            'status' => $code->status(),
157
+        ];
158
+    }
159
+
160
+    /**
161
+     * @return array{name: string, slug: string}
162
+     */
163
+    private function presentStore(Store $store): array
164
+    {
165
+        return ['name' => $store->name, 'slug' => $store->slug];
166
+    }
167
+
168
+    private static function sen(mixed $ringgit): int
169
+    {
170
+        return (int) round(((float) $ringgit) * 100);
171
+    }
172
+
173
+    private static function ringgit(int $sen): string
174
+    {
175
+        return number_format($sen / 100, 2, '.', '');
176
+    }
177
+
178
+    private function ownedStore(Request $request, string $slug): Store
179
+    {
180
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
181
+    }
182
+
183
+    private function ownedCode(Store $store, int $id): DiscountCode
184
+    {
185
+        return $store->discountCodes()->whereKey($id)->firstOrFail();
186
+    }
187
+}

+ 127
- 0
app/Models/DiscountCode.php Просмотреть файл

@@ -0,0 +1,127 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Carbon\CarbonInterface;
6
+use Database\Factories\DiscountCodeFactory;
7
+use Illuminate\Database\Eloquent\Factories\HasFactory;
8
+use Illuminate\Database\Eloquent\Model;
9
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
10
+
11
+/**
12
+ * A code shoppers type in the cart to get money off. Amounts are in sen (1 ringgit = 100 sen).
13
+ *
14
+ * @property int $id
15
+ * @property int $store_id
16
+ * @property string $code
17
+ * @property string $type "percent" or "fixed"
18
+ * @property int $value A whole percentage, or an amount in sen
19
+ * @property int|null $minimum_subtotal
20
+ * @property CarbonInterface|null $starts_at
21
+ * @property CarbonInterface|null $ends_at
22
+ * @property int|null $usage_limit
23
+ * @property int $times_used
24
+ * @property bool $active
25
+ * @property CarbonInterface|null $created_at
26
+ * @property CarbonInterface|null $updated_at
27
+ * @property-read Store $store
28
+ */
29
+class DiscountCode extends Model
30
+{
31
+    /** @use HasFactory<DiscountCodeFactory> */
32
+    use HasFactory;
33
+
34
+    public const string PERCENT = 'percent';
35
+
36
+    public const string FIXED = 'fixed';
37
+
38
+    /** Letters, digits and dashes, 3 to 30 long. */
39
+    public const string CODE_PATTERN = '/^[A-Z0-9-]{3,30}$/';
40
+
41
+    /**
42
+     * Shoppers may type " raya10 "; we store and compare "RAYA10".
43
+     */
44
+    public static function normalize(string $code): string
45
+    {
46
+        return strtoupper(trim($code));
47
+    }
48
+
49
+    /**
50
+     * @return BelongsTo<Store, $this>
51
+     */
52
+    public function store(): BelongsTo
53
+    {
54
+        return $this->belongsTo(Store::class);
55
+    }
56
+
57
+    /**
58
+     * Why this code cannot be used right now for products adding up to $subtotal (in sen),
59
+     * as a key for StorefrontText. Null when it can be used.
60
+     */
61
+    public function problemFor(int $subtotal): ?string
62
+    {
63
+        return match (true) {
64
+            ! $this->active => 'discount_invalid',
65
+            $this->starts_at !== null && $this->starts_at->isFuture() => 'discount_not_started',
66
+            $this->ends_at !== null && $this->ends_at->isPast() => 'discount_expired',
67
+            $this->usage_limit !== null && $this->times_used >= $this->usage_limit => 'discount_used_up',
68
+            $this->minimum_subtotal !== null && $subtotal < $this->minimum_subtotal => 'discount_minimum',
69
+            default => null,
70
+        };
71
+    }
72
+
73
+    /**
74
+     * How much comes off products adding up to $subtotal, in sen. Never more than the subtotal.
75
+     * Percentages are rounded down to the sen, so the shopper never gets less than promised by more than a sen.
76
+     */
77
+    public function amountFor(int $subtotal): int
78
+    {
79
+        $amount = $this->type === self::PERCENT
80
+            ? intdiv($subtotal * min(100, $this->value), 100)
81
+            : $this->value;
82
+
83
+        return max(0, min($amount, $subtotal));
84
+    }
85
+
86
+    /**
87
+     * "10% off" or "RM 5.00 off", in the store's language.
88
+     */
89
+    public function label(string $language = 'en'): string
90
+    {
91
+        $amount = $this->type === self::PERCENT
92
+            ? $this->value.'%'
93
+            : 'RM '.number_format($this->value / 100, 2);
94
+
95
+        return $language === 'ms' ? 'Diskaun '.$amount : $amount.' off';
96
+    }
97
+
98
+    /**
99
+     * The state a merchant sees in the list.
100
+     */
101
+    public function status(): string
102
+    {
103
+        return match (true) {
104
+            ! $this->active => 'off',
105
+            $this->starts_at !== null && $this->starts_at->isFuture() => 'scheduled',
106
+            $this->ends_at !== null && $this->ends_at->isPast() => 'expired',
107
+            $this->usage_limit !== null && $this->times_used >= $this->usage_limit => 'used_up',
108
+            default => 'active',
109
+        };
110
+    }
111
+
112
+    /**
113
+     * @return array<string, string>
114
+     */
115
+    protected function casts(): array
116
+    {
117
+        return [
118
+            'value' => 'integer',
119
+            'minimum_subtotal' => 'integer',
120
+            'starts_at' => 'datetime',
121
+            'ends_at' => 'datetime',
122
+            'usage_limit' => 'integer',
123
+            'times_used' => 'integer',
124
+            'active' => 'boolean',
125
+        ];
126
+    }
127
+}

+ 4
- 0
app/Models/Order.php Просмотреть файл

@@ -27,6 +27,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
27 27
  * @property string $customer_phone
28 28
  * @property array{line1: string, line2: string|null, city: string, postcode: string, state: string, country: string} $shipping_address
29 29
  * @property int $subtotal
30
+ * @property string|null $discount_code
31
+ * @property int $discount_total
30 32
  * @property int $shipping_total
31 33
  * @property int $total
32 34
  * @property string $currency
@@ -86,6 +88,8 @@ class Order extends Model
86 88
             'customer_phone' => $this->customer_phone,
87 89
             'shipping_address' => $this->shipping_address,
88 90
             'subtotal' => $this->subtotal / 100,
91
+            'discount_code' => $this->discount_code,
92
+            'discount_total' => $this->discount_total / 100,
89 93
             'shipping_total' => $this->shipping_total / 100,
90 94
             'total' => $this->total / 100,
91 95
             'paid_at' => $this->paid_at?->toIso8601String(),

+ 8
- 0
app/Models/Store.php Просмотреть файл

@@ -135,6 +135,14 @@ class Store extends Model
135 135
         return $this->hasMany(Product::class);
136 136
     }
137 137
 
138
+    /**
139
+     * @return HasMany<DiscountCode, $this>
140
+     */
141
+    public function discountCodes(): HasMany
142
+    {
143
+        return $this->hasMany(DiscountCode::class);
144
+    }
145
+
138 146
     /**
139 147
      * @return HasMany<Order, $this>
140 148
      */

+ 19
- 2
app/Storefront/StorefrontText.php Просмотреть файл

@@ -14,18 +14,35 @@ final class StorefrontText
14 14
             'minimum_total' => 'The order total must be at least RM 2.00.',
15 15
             'sold_out' => 'This product is sold out.',
16 16
             'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
17
+            'discount_invalid' => 'This code is not valid.',
18
+            'discount_not_started' => 'This code cannot be used yet.',
19
+            'discount_expired' => 'This code has expired.',
20
+            'discount_used_up' => 'This code has been used up.',
21
+            'discount_minimum' => 'Spend at least :amount on products to use this code.',
22
+            'discount_total_too_low' => 'After the discount, the order total must be at least RM 2.00.',
23
+            'discount_changed' => 'Your discount code can no longer be used, so it was removed. Please check your total.',
17 24
         ],
18 25
         'ms' => [
19 26
             'cart_empty' => 'Troli anda kosong.',
20 27
             'minimum_total' => 'Jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
21 28
             'sold_out' => 'Produk ini telah habis dijual.',
22 29
             'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',
30
+            'discount_invalid' => 'Kod ini tidak sah.',
31
+            'discount_not_started' => 'Kod ini belum boleh digunakan.',
32
+            'discount_expired' => 'Kod ini telah tamat tempoh.',
33
+            'discount_used_up' => 'Kod ini telah habis digunakan.',
34
+            'discount_minimum' => 'Belanja sekurang-kurangnya :amount untuk produk bagi menggunakan kod ini.',
35
+            'discount_total_too_low' => 'Selepas diskaun, jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
36
+            'discount_changed' => 'Kod diskaun anda tidak lagi boleh digunakan, jadi ia telah dibuang. Sila semak jumlah anda.',
23 37
         ],
24 38
     ];
25 39
 
26
-    public static function line(string $language, string $key): string
40
+    /**
41
+     * @param  array<string, string>  $replace  Words to put in, such as [':amount' => 'RM 50.00'].
42
+     */
43
+    public static function line(string $language, string $key, array $replace = []): string
27 44
     {
28
-        return self::LINES[$language][$key] ?? self::LINES['en'][$key];
45
+        return strtr(self::LINES[$language][$key] ?? self::LINES['en'][$key], $replace);
29 46
     }
30 47
 
31 48
     /**

+ 38
- 0
database/factories/DiscountCodeFactory.php Просмотреть файл

@@ -0,0 +1,38 @@
1
+<?php
2
+
3
+namespace Database\Factories;
4
+
5
+use App\Models\DiscountCode;
6
+use App\Models\Store;
7
+use Illuminate\Database\Eloquent\Factories\Factory;
8
+
9
+/**
10
+ * @extends Factory<DiscountCode>
11
+ */
12
+class DiscountCodeFactory extends Factory
13
+{
14
+    /**
15
+     * @return array<string, mixed>
16
+     */
17
+    public function definition(): array
18
+    {
19
+        return [
20
+            'store_id' => Store::factory(),
21
+            'code' => 'SAVE'.fake()->unique()->numberBetween(10, 9999),
22
+            'type' => DiscountCode::PERCENT,
23
+            'value' => 10,
24
+            'active' => true,
25
+            'times_used' => 0,
26
+        ];
27
+    }
28
+
29
+    public function fixed(int $sen): static
30
+    {
31
+        return $this->state(['type' => DiscountCode::FIXED, 'value' => $sen]);
32
+    }
33
+
34
+    public function percent(int $percent): static
35
+    {
36
+        return $this->state(['type' => DiscountCode::PERCENT, 'value' => $percent]);
37
+    }
38
+}

+ 47
- 0
database/migrations/2026_11_16_000002_create_discount_codes_table.php Просмотреть файл

@@ -0,0 +1,47 @@
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::create('discount_codes', function (Blueprint $table) {
12
+            $table->id();
13
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
14
+            // Saved in capital letters, such as RAYA10. Shoppers may type it in any case.
15
+            $table->string('code', 30);
16
+            // "percent": value is a whole percentage (1 to 100). "fixed": value is an amount in sen.
17
+            $table->string('type', 10);
18
+            $table->unsignedInteger('value');
19
+            // The products in the cart must add up to at least this, in sen.
20
+            $table->unsignedInteger('minimum_subtotal')->nullable();
21
+            $table->timestamp('starts_at')->nullable();
22
+            $table->timestamp('ends_at')->nullable();
23
+            // How many paid orders may use the code. Null means no limit.
24
+            $table->unsignedInteger('usage_limit')->nullable();
25
+            $table->unsignedInteger('times_used')->default(0);
26
+            $table->boolean('active')->default(true);
27
+            $table->timestamps();
28
+
29
+            $table->unique(['store_id', 'code']);
30
+        });
31
+
32
+        Schema::table('orders', function (Blueprint $table) {
33
+            $table->string('discount_code', 30)->nullable()->after('subtotal');
34
+            // Amount taken off the products, in sen. Shipping is never discounted.
35
+            $table->unsignedInteger('discount_total')->default(0)->after('discount_code');
36
+        });
37
+    }
38
+
39
+    public function down(): void
40
+    {
41
+        Schema::table('orders', function (Blueprint $table) {
42
+            $table->dropColumn(['discount_code', 'discount_total']);
43
+        });
44
+
45
+        Schema::dropIfExists('discount_codes');
46
+    }
47
+};

+ 7
- 1
resources/js/components/stores/store-nav.tsx Просмотреть файл

@@ -1,11 +1,12 @@
1 1
 import { Link } from '@inertiajs/react';
2
+import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
2 3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
3 4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4 5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5 6
 import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
6 7
 import { cn } from '@/lib/utils';
7 8
 
8
-type Tab = 'design' | 'products' | 'orders' | 'settings';
9
+type Tab = 'design' | 'products' | 'orders' | 'discounts' | 'settings';
9 10
 
10 11
 /** The tabs at the top of every page of one store. */
11 12
 export default function StoreNav({
@@ -31,6 +32,11 @@ export default function StoreNav({
31 32
             label: 'Orders',
32 33
             href: OrderController.index.url(slug),
33 34
         },
35
+        {
36
+            key: 'discounts',
37
+            label: 'Discounts',
38
+            href: DiscountCodeController.index.url(slug),
39
+        },
34 40
         {
35 41
             key: 'settings',
36 42
             label: 'Settings',

+ 295
- 0
resources/js/pages/stores/discounts/form.tsx Просмотреть файл

@@ -0,0 +1,295 @@
1
+import { Form, Head, Link } from '@inertiajs/react';
2
+import { useState } from 'react';
3
+import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4
+import Heading from '@/components/heading';
5
+import InputError from '@/components/input-error';
6
+import { Button } from '@/components/ui/button';
7
+import { Checkbox } from '@/components/ui/checkbox';
8
+import {
9
+    Dialog,
10
+    DialogClose,
11
+    DialogContent,
12
+    DialogDescription,
13
+    DialogFooter,
14
+    DialogHeader,
15
+    DialogTitle,
16
+    DialogTrigger,
17
+} from '@/components/ui/dialog';
18
+import { Input } from '@/components/ui/input';
19
+import { Label } from '@/components/ui/label';
20
+import { dashboard } from '@/routes';
21
+import type { DiscountCode, StoreSummary } from '@/types';
22
+
23
+/** Add a new discount code, or edit one when `code` is given. */
24
+export default function DiscountForm({
25
+    store,
26
+    code,
27
+}: {
28
+    store: StoreSummary;
29
+    code: DiscountCode | null;
30
+}) {
31
+    const [type, setType] = useState<'percent' | 'fixed'>(
32
+        code?.type ?? 'percent',
33
+    );
34
+    const action = code
35
+        ? DiscountCodeController.update.form({
36
+              slug: store.slug,
37
+              discount: code.id,
38
+          })
39
+        : DiscountCodeController.store.form(store.slug);
40
+
41
+    return (
42
+        <>
43
+            <Head
44
+                title={`${code ? code.code : 'New discount code'} - ${store.name}`}
45
+            />
46
+
47
+            <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
48
+                <Heading
49
+                    title={code ? 'Edit discount code' : 'New discount code'}
50
+                    description={`For ${store.name}. Shoppers type the code in their cart.`}
51
+                />
52
+
53
+                <Form {...action} className="space-y-6">
54
+                    {({ processing, errors }) => (
55
+                        <>
56
+                            <div className="grid gap-2">
57
+                                <Label htmlFor="code">Code</Label>
58
+                                <Input
59
+                                    id="code"
60
+                                    name="code"
61
+                                    required
62
+                                    maxLength={30}
63
+                                    defaultValue={code?.code}
64
+                                    placeholder="RAYA10"
65
+                                    className="font-mono uppercase"
66
+                                    autoCapitalize="characters"
67
+                                    aria-describedby="code-help"
68
+                                />
69
+                                <p
70
+                                    id="code-help"
71
+                                    className="text-xs text-muted-foreground"
72
+                                >
73
+                                    Letters, numbers and dashes. Shoppers can
74
+                                    type it in small or capital letters.
75
+                                </p>
76
+                                <InputError message={errors.code} />
77
+                            </div>
78
+
79
+                            <fieldset className="grid gap-3">
80
+                                <legend className="mb-1 text-sm font-medium">
81
+                                    Discount
82
+                                </legend>
83
+                                <div className="flex flex-wrap gap-4 text-sm">
84
+                                    <label className="flex items-center gap-2">
85
+                                        <input
86
+                                            type="radio"
87
+                                            name="type"
88
+                                            value="percent"
89
+                                            checked={type === 'percent'}
90
+                                            onChange={() => setType('percent')}
91
+                                        />
92
+                                        Percentage off
93
+                                    </label>
94
+                                    <label className="flex items-center gap-2">
95
+                                        <input
96
+                                            type="radio"
97
+                                            name="type"
98
+                                            value="fixed"
99
+                                            checked={type === 'fixed'}
100
+                                            onChange={() => setType('fixed')}
101
+                                        />
102
+                                        Fixed amount off
103
+                                    </label>
104
+                                </div>
105
+                                <div className="grid gap-2 sm:max-w-xs">
106
+                                    <Label htmlFor="value">
107
+                                        {type === 'percent'
108
+                                            ? 'Percentage (%)'
109
+                                            : 'Amount (RM)'}
110
+                                    </Label>
111
+                                    <Input
112
+                                        id="value"
113
+                                        name="value"
114
+                                        required
115
+                                        inputMode={
116
+                                            type === 'percent'
117
+                                                ? 'numeric'
118
+                                                : 'decimal'
119
+                                        }
120
+                                        defaultValue={code?.value}
121
+                                        placeholder={
122
+                                            type === 'percent' ? '10' : '5.00'
123
+                                        }
124
+                                    />
125
+                                    <InputError message={errors.value} />
126
+                                </div>
127
+                                <InputError message={errors.type} />
128
+                            </fieldset>
129
+
130
+                            <div className="grid gap-2 sm:max-w-xs">
131
+                                <Label htmlFor="minimum_subtotal">
132
+                                    Minimum spend on products (RM, optional)
133
+                                </Label>
134
+                                <Input
135
+                                    id="minimum_subtotal"
136
+                                    name="minimum_subtotal"
137
+                                    inputMode="decimal"
138
+                                    defaultValue={code?.minimum_subtotal ?? ''}
139
+                                    placeholder="50.00"
140
+                                />
141
+                                <InputError message={errors.minimum_subtotal} />
142
+                            </div>
143
+
144
+                            <div className="grid gap-6 sm:grid-cols-2">
145
+                                <div className="grid gap-2">
146
+                                    <Label htmlFor="starts_on">
147
+                                        First day (optional)
148
+                                    </Label>
149
+                                    <Input
150
+                                        id="starts_on"
151
+                                        name="starts_on"
152
+                                        type="date"
153
+                                        defaultValue={code?.starts_on ?? ''}
154
+                                    />
155
+                                    <InputError message={errors.starts_on} />
156
+                                </div>
157
+                                <div className="grid gap-2">
158
+                                    <Label htmlFor="ends_on">
159
+                                        Last day (optional)
160
+                                    </Label>
161
+                                    <Input
162
+                                        id="ends_on"
163
+                                        name="ends_on"
164
+                                        type="date"
165
+                                        defaultValue={code?.ends_on ?? ''}
166
+                                    />
167
+                                    <InputError message={errors.ends_on} />
168
+                                </div>
169
+                            </div>
170
+
171
+                            <div className="grid gap-2 sm:max-w-xs">
172
+                                <Label htmlFor="usage_limit">
173
+                                    Number of uses (optional)
174
+                                </Label>
175
+                                <Input
176
+                                    id="usage_limit"
177
+                                    name="usage_limit"
178
+                                    type="number"
179
+                                    min={1}
180
+                                    step={1}
181
+                                    defaultValue={code?.usage_limit ?? ''}
182
+                                    placeholder="No limit"
183
+                                    aria-describedby="usage-help"
184
+                                />
185
+                                <p
186
+                                    id="usage-help"
187
+                                    className="text-xs text-muted-foreground"
188
+                                >
189
+                                    {code
190
+                                        ? `Used ${code.times_used} times so far. `
191
+                                        : ''}
192
+                                    A use is counted when an order with the code
193
+                                    is paid.
194
+                                </p>
195
+                                <InputError message={errors.usage_limit} />
196
+                            </div>
197
+
198
+                            <div className="flex items-center gap-3">
199
+                                <input type="hidden" name="active" value="0" />
200
+                                <Checkbox
201
+                                    id="active"
202
+                                    name="active"
203
+                                    value="1"
204
+                                    defaultChecked={code?.active ?? true}
205
+                                />
206
+                                <Label htmlFor="active">
207
+                                    Active (shoppers can use it)
208
+                                </Label>
209
+                            </div>
210
+
211
+                            <div className="flex items-center gap-3">
212
+                                <Button
213
+                                    disabled={processing}
214
+                                    data-test="save-discount-button"
215
+                                >
216
+                                    {code ? 'Save code' : 'Create code'}
217
+                                </Button>
218
+                                <Button variant="ghost" asChild>
219
+                                    <Link
220
+                                        href={DiscountCodeController.index.url(
221
+                                            store.slug,
222
+                                        )}
223
+                                    >
224
+                                        Cancel
225
+                                    </Link>
226
+                                </Button>
227
+                            </div>
228
+                        </>
229
+                    )}
230
+                </Form>
231
+
232
+                {code && (
233
+                    <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-destructive/30 p-4">
234
+                        <div>
235
+                            <p className="font-medium">Delete this code</p>
236
+                            <p className="text-sm text-muted-foreground">
237
+                                Shoppers can no longer use it. Past orders keep
238
+                                their discount.
239
+                            </p>
240
+                        </div>
241
+                        <Dialog>
242
+                            <DialogTrigger asChild>
243
+                                <Button variant="destructive" size="sm">
244
+                                    Delete
245
+                                </Button>
246
+                            </DialogTrigger>
247
+                            <DialogContent>
248
+                                <DialogHeader>
249
+                                    <DialogTitle>
250
+                                        Delete {code.code}?
251
+                                    </DialogTitle>
252
+                                    <DialogDescription>
253
+                                        This cannot be undone. Past orders that
254
+                                        used it are not changed.
255
+                                    </DialogDescription>
256
+                                </DialogHeader>
257
+                                <DialogFooter>
258
+                                    <DialogClose asChild>
259
+                                        <Button variant="outline">
260
+                                            Cancel
261
+                                        </Button>
262
+                                    </DialogClose>
263
+                                    <Form
264
+                                        {...DiscountCodeController.destroy.form(
265
+                                            {
266
+                                                slug: store.slug,
267
+                                                discount: code.id,
268
+                                            },
269
+                                        )}
270
+                                    >
271
+                                        {({ processing }) => (
272
+                                            <Button
273
+                                                variant="destructive"
274
+                                                disabled={processing}
275
+                                            >
276
+                                                Delete code
277
+                                            </Button>
278
+                                        )}
279
+                                    </Form>
280
+                                </DialogFooter>
281
+                            </DialogContent>
282
+                        </Dialog>
283
+                    </div>
284
+                )}
285
+            </div>
286
+        </>
287
+    );
288
+}
289
+
290
+DiscountForm.layout = {
291
+    breadcrumbs: [
292
+        { title: 'Dashboard', href: dashboard() },
293
+        { title: 'Discount code', href: '#' },
294
+    ],
295
+};

+ 169
- 0
resources/js/pages/stores/discounts/index.tsx Просмотреть файл

@@ -0,0 +1,169 @@
1
+import { Head, Link } from '@inertiajs/react';
2
+import { Plus, TicketPercent } from 'lucide-react';
3
+import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4
+import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
+import StoreNav from '@/components/stores/store-nav';
6
+import { Badge } from '@/components/ui/badge';
7
+import { Button } from '@/components/ui/button';
8
+import { dashboard } from '@/routes';
9
+import type { DiscountCode, StoreSummary } from '@/types';
10
+
11
+const statusLabel: Record<DiscountCode['status'], string> = {
12
+    active: 'Active',
13
+    off: 'Off',
14
+    scheduled: 'Scheduled',
15
+    expired: 'Expired',
16
+    used_up: 'Used up',
17
+};
18
+
19
+const dateFormat = new Intl.DateTimeFormat('en-MY', { dateStyle: 'medium' });
20
+
21
+function day(value: string): string {
22
+    return dateFormat.format(new Date(`${value}T00:00:00`));
23
+}
24
+
25
+/** "From 1 Apr 2027 to 30 Apr 2027", "Until 30 Apr 2027" and so on. */
26
+function dates(code: DiscountCode): string | null {
27
+    if (code.starts_on && code.ends_on) {
28
+        return `${day(code.starts_on)} to ${day(code.ends_on)}`;
29
+    }
30
+
31
+    if (code.starts_on) {
32
+        return `From ${day(code.starts_on)}`;
33
+    }
34
+
35
+    if (code.ends_on) {
36
+        return `Until ${day(code.ends_on)}`;
37
+    }
38
+
39
+    return null;
40
+}
41
+
42
+export default function DiscountsIndex({
43
+    store,
44
+    codes,
45
+}: {
46
+    store: StoreSummary;
47
+    codes: DiscountCode[];
48
+}) {
49
+    const createUrl = DiscountCodeController.create.url(store.slug);
50
+
51
+    return (
52
+        <>
53
+            <Head title={`Discounts - ${store.name}`} />
54
+
55
+            <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
56
+                <div>
57
+                    <h1 className="text-xl font-semibold">{store.name}</h1>
58
+                    <p className="text-sm text-muted-foreground">
59
+                        <Link
60
+                            href={StoreController.show.url(store.slug)}
61
+                            className="hover:underline"
62
+                        >
63
+                            Back to store
64
+                        </Link>
65
+                    </p>
66
+                </div>
67
+
68
+                <StoreNav slug={store.slug} current="discounts" />
69
+
70
+                <div className="flex flex-wrap items-center justify-between gap-3">
71
+                    <h2 className="font-medium">
72
+                        Discount codes{' '}
73
+                        <span className="text-muted-foreground">
74
+                            ({codes.length})
75
+                        </span>
76
+                    </h2>
77
+                    <Button asChild size="sm" data-test="add-discount-button">
78
+                        <Link href={createUrl}>
79
+                            <Plus />
80
+                            New code
81
+                        </Link>
82
+                    </Button>
83
+                </div>
84
+
85
+                {codes.length === 0 ? (
86
+                    <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed p-10 text-center">
87
+                        <TicketPercent className="size-6 text-muted-foreground" />
88
+                        <div>
89
+                            <p className="font-medium">No discount codes yet</p>
90
+                            <p className="mt-1 max-w-sm text-sm text-muted-foreground">
91
+                                Create a code such as RAYA10. Shoppers type it
92
+                                in their cart to get money off.
93
+                            </p>
94
+                        </div>
95
+                        <Button asChild size="sm">
96
+                            <Link href={createUrl}>New code</Link>
97
+                        </Button>
98
+                    </div>
99
+                ) : (
100
+                    <ul className="divide-y rounded-xl border">
101
+                        {codes.map((code) => {
102
+                            const when = dates(code);
103
+
104
+                            return (
105
+                                <li
106
+                                    key={code.id}
107
+                                    className="flex flex-wrap items-center gap-x-4 gap-y-2 p-4"
108
+                                >
109
+                                    <div className="min-w-0 flex-1">
110
+                                        <p className="font-mono font-semibold">
111
+                                            {code.code}
112
+                                        </p>
113
+                                        <p className="text-sm text-muted-foreground">
114
+                                            {code.label}
115
+                                            {code.minimum_subtotal &&
116
+                                                ` · on orders over RM ${code.minimum_subtotal}`}
117
+                                            {when && ` · ${when}`}
118
+                                        </p>
119
+                                    </div>
120
+
121
+                                    <p className="text-sm text-muted-foreground tabular-nums">
122
+                                        Used {code.times_used}
123
+                                        {code.usage_limit !== null &&
124
+                                            ` of ${code.usage_limit}`}
125
+                                    </p>
126
+
127
+                                    <Badge
128
+                                        variant={
129
+                                            code.status === 'active'
130
+                                                ? 'default'
131
+                                                : 'secondary'
132
+                                        }
133
+                                    >
134
+                                        {statusLabel[code.status]}
135
+                                    </Badge>
136
+
137
+                                    <Button variant="outline" size="sm" asChild>
138
+                                        <Link
139
+                                            href={DiscountCodeController.edit.url(
140
+                                                {
141
+                                                    slug: store.slug,
142
+                                                    discount: code.id,
143
+                                                },
144
+                                            )}
145
+                                        >
146
+                                            Edit
147
+                                        </Link>
148
+                                    </Button>
149
+                                </li>
150
+                            );
151
+                        })}
152
+                    </ul>
153
+                )}
154
+
155
+                <p className="text-xs text-muted-foreground">
156
+                    A code takes money off the products only, never off
157
+                    shipping. It counts as used when an order with it is paid.
158
+                </p>
159
+            </div>
160
+        </>
161
+    );
162
+}
163
+
164
+DiscountsIndex.layout = {
165
+    breadcrumbs: [
166
+        { title: 'Dashboard', href: dashboard() },
167
+        { title: 'Discounts', href: '#' },
168
+    ],
169
+};

+ 12
- 0
resources/js/pages/stores/orders/show.tsx Просмотреть файл

@@ -98,6 +98,18 @@ export default function ShowOrder({
98 98
                                     {formatRinggit(order.subtotal)}
99 99
                                 </span>
100 100
                             </div>
101
+                            {order.discount_total > 0 && (
102
+                                <div className="flex justify-between gap-4">
103
+                                    <span>
104
+                                        Discount
105
+                                        {order.discount_code &&
106
+                                            ` (${order.discount_code})`}
107
+                                    </span>
108
+                                    <span className="tabular-nums">
109
+                                        −{formatRinggit(order.discount_total)}
110
+                                    </span>
111
+                                </div>
112
+                            )}
101 113
                             <div className="flex justify-between gap-4">
102 114
                                 <span>Shipping</span>
103 115
                                 <span className="tabular-nums">

+ 8
- 1
resources/js/storefront/context.tsx Просмотреть файл

@@ -21,7 +21,14 @@ const StorefrontContext = createContext<Storefront>({
21 21
     isHome: true,
22 22
     language: 'en',
23 23
     products: [],
24
-    cart: { count: 0, subtotal: 0, adjusted: false, lines: [] },
24
+    cart: {
25
+        count: 0,
26
+        subtotal: 0,
27
+        discount: null,
28
+        total: 0,
29
+        adjusted: false,
30
+        lines: [],
31
+    },
25 32
     storeName: '',
26 33
     shop: { whatsapp: null, free_shipping_over: null },
27 34
     featuredProducts: {},

+ 128
- 5
resources/js/storefront/pages/cart.tsx Просмотреть файл

@@ -1,6 +1,7 @@
1
-import { router } from '@inertiajs/react';
1
+import { router, useForm } from '@inertiajs/react';
2 2
 import { Trash2 } from 'lucide-react';
3 3
 import { useState } from 'react';
4
+import type { FormEvent } from 'react';
4 5
 import { useStorefront } from '../context';
5 6
 import { ProductImage } from '../product-card';
6 7
 import { storefrontText } from '../text';
@@ -17,9 +18,9 @@ export function CartPage() {
17 18
     const freeShippingNote =
18 19
         freeOver === null || freeOver === 0
19 20
             ? null
20
-            : cart.subtotal >= freeOver
21
+            : cart.total >= freeOver
21 22
               ? t.youGetFreeShipping
22
-              : t.spendMoreForFree(formatPrice(freeOver - cart.subtotal));
23
+              : t.spendMoreForFree(formatPrice(freeOver - cart.total));
23 24
     const [busy, setBusy] = useState(false);
24 25
 
25 26
     function change(line: CartLine, quantity: number) {
@@ -137,12 +138,38 @@ export function CartPage() {
137 138
                         </ul>
138 139
 
139 140
                         <aside className="h-fit rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
141
+                            <DiscountBox />
142
+
143
+                            {cart.discount && cart.discount.amount > 0 && (
144
+                                <div className="mb-3 space-y-1.5 text-sm">
145
+                                    <div className="flex justify-between gap-4">
146
+                                        <span>{t.subtotal}</span>
147
+                                        <span className="tabular-nums">
148
+                                            {formatPrice(cart.subtotal)}
149
+                                        </span>
150
+                                    </div>
151
+                                    <div
152
+                                        className="flex justify-between gap-4"
153
+                                        data-test="cart-discount-line"
154
+                                    >
155
+                                        <span>
156
+                                            {t.discount} ({cart.discount.code})
157
+                                        </span>
158
+                                        <span className="tabular-nums">
159
+                                            −{formatPrice(cart.discount.amount)}
160
+                                        </span>
161
+                                    </div>
162
+                                </div>
163
+                            )}
164
+
140 165
                             <div className="flex items-baseline justify-between gap-4">
141 166
                                 <span className="font-medium">
142
-                                    {t.subtotal}
167
+                                    {cart.discount && cart.discount.amount > 0
168
+                                        ? t.total
169
+                                        : t.subtotal}
143 170
                                 </span>
144 171
                                 <span className="text-xl font-semibold tabular-nums">
145
-                                    {formatPrice(cart.subtotal)}
172
+                                    {formatPrice(cart.total)}
146 173
                                 </span>
147 174
                             </div>
148 175
                             <p className="mt-2 text-sm text-(--sf-muted)">
@@ -177,3 +204,99 @@ export function CartPage() {
177 204
         </main>
178 205
     );
179 206
 }
207
+
208
+/**
209
+ * Type a discount code, or see the one in use with a way to take it out.
210
+ */
211
+function DiscountBox() {
212
+    const { cart, language, baseUrl } = useStorefront();
213
+    const t = storefrontText(language);
214
+    const form = useForm({ code: '' });
215
+
216
+    function apply(event: FormEvent) {
217
+        event.preventDefault();
218
+        form.post(`${baseUrl}/cart/discount`, {
219
+            preserveScroll: true,
220
+            onSuccess: () => form.reset(),
221
+        });
222
+    }
223
+
224
+    function remove() {
225
+        router.delete(`${baseUrl}/cart/discount`, { preserveScroll: true });
226
+    }
227
+
228
+    if (cart.discount) {
229
+        return (
230
+            <div className="mb-5 border-b border-(--sf-border) pb-5">
231
+                <div className="flex items-center justify-between gap-3 text-sm">
232
+                    <span>
233
+                        <span className="font-mono font-semibold">
234
+                            {cart.discount.code}
235
+                        </span>{' '}
236
+                        <span className="text-(--sf-muted)">
237
+                            · {cart.discount.label}
238
+                        </span>
239
+                    </span>
240
+                    <button
241
+                        type="button"
242
+                        onClick={remove}
243
+                        className="text-(--sf-muted) underline underline-offset-2 hover:text-(--sf-fg)"
244
+                    >
245
+                        {t.removeCode}
246
+                    </button>
247
+                </div>
248
+                {cart.discount.message && (
249
+                    <p className="mt-2 text-sm" role="status">
250
+                        {cart.discount.message}
251
+                    </p>
252
+                )}
253
+            </div>
254
+        );
255
+    }
256
+
257
+    return (
258
+        <form
259
+            onSubmit={apply}
260
+            className="mb-5 border-b border-(--sf-border) pb-5"
261
+            noValidate
262
+        >
263
+            <label htmlFor="discount-code" className="text-sm font-medium">
264
+                {t.discountCode}
265
+            </label>
266
+            <div className="mt-2 flex gap-2">
267
+                <input
268
+                    id="discount-code"
269
+                    name="code"
270
+                    value={form.data.code}
271
+                    onChange={(event) =>
272
+                        form.setData('code', event.target.value)
273
+                    }
274
+                    placeholder={t.codePlaceholder}
275
+                    autoComplete="off"
276
+                    autoCapitalize="characters"
277
+                    aria-invalid={form.errors.code ? true : undefined}
278
+                    aria-describedby={
279
+                        form.errors.code ? 'discount-code-error' : undefined
280
+                    }
281
+                    className="min-w-0 flex-1 rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) px-3 py-2 text-base uppercase outline-none focus-visible:border-(--sf-primary) focus-visible:ring-2 focus-visible:ring-(--sf-primary)/30 sm:text-sm"
282
+                />
283
+                <button
284
+                    type="submit"
285
+                    disabled={form.processing || form.data.code.trim() === ''}
286
+                    className="rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) px-4 py-2 text-sm font-semibold transition-colors hover:bg-(--sf-surface) disabled:opacity-50"
287
+                >
288
+                    {t.apply}
289
+                </button>
290
+            </div>
291
+            {form.errors.code && (
292
+                <p
293
+                    id="discount-code-error"
294
+                    className="mt-2 text-sm text-red-700"
295
+                    role="alert"
296
+                >
297
+                    {form.errors.code}
298
+                </p>
299
+            )}
300
+        </form>
301
+    );
302
+}

+ 11
- 1
resources/js/storefront/pages/checkout.tsx Просмотреть файл

@@ -234,6 +234,16 @@ export function CheckoutPage({
234 234
                                     {formatPrice(cart.subtotal)}
235 235
                                 </span>
236 236
                             </div>
237
+                            {cart.discount && cart.discount.amount > 0 && (
238
+                                <div className="flex justify-between gap-4">
239
+                                    <span>
240
+                                        {t.discount} ({cart.discount.code})
241
+                                    </span>
242
+                                    <span className="tabular-nums">
243
+                                        −{formatPrice(cart.discount.amount)}
244
+                                    </span>
245
+                                </div>
246
+                            )}
237 247
                             <div className="flex justify-between gap-4">
238 248
                                 <span>{t.shipping}</span>
239 249
                                 <span
@@ -256,7 +266,7 @@ export function CheckoutPage({
256 266
                         <div className="mt-4 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
257 267
                             <span className="font-medium">{t.total}</span>
258 268
                             <span className="text-xl font-semibold tabular-nums">
259
-                                {formatPrice(cart.subtotal + (shipping ?? 0))}
269
+                                {formatPrice(cart.total + (shipping ?? 0))}
260 270
                             </span>
261 271
                         </div>
262 272
                     </aside>

+ 12
- 0
resources/js/storefront/pages/order.tsx Просмотреть файл

@@ -51,6 +51,18 @@ export function OrderPage({ order }: { order: StoreOrder }) {
51 51
                                 {formatPrice(order.subtotal)}
52 52
                             </span>
53 53
                         </div>
54
+                        {order.discount_total > 0 && (
55
+                            <div className="flex justify-between gap-4">
56
+                                <span>
57
+                                    {t.discount}
58
+                                    {order.discount_code &&
59
+                                        ` (${order.discount_code})`}
60
+                                </span>
61
+                                <span className="tabular-nums">
62
+                                    −{formatPrice(order.discount_total)}
63
+                                </span>
64
+                            </div>
65
+                        )}
54 66
                         <div className="flex justify-between gap-4">
55 67
                             <span>{t.shipping}</span>
56 68
                             <span className="tabular-nums">

+ 10
- 0
resources/js/storefront/text.ts Просмотреть файл

@@ -49,6 +49,11 @@ const words = {
49 49
             `Order #${number} has not been paid yet. Your cart is still saved, so you can try again.`,
50 50
         deliverTo: 'Deliver to',
51 51
         quantityShort: 'Qty',
52
+        discountCode: 'Discount code',
53
+        apply: 'Apply',
54
+        discount: 'Discount',
55
+        removeCode: 'Remove code',
56
+        codePlaceholder: 'Enter code',
52 57
         shipping: 'Shipping',
53 58
         shippingFree: 'Free',
54 59
         chooseStateForShipping: 'Choose your state to see the shipping fee.',
@@ -120,6 +125,11 @@ const words = {
120 125
             `Pesanan #${number} belum dibayar. Troli anda masih disimpan, jadi anda boleh cuba lagi.`,
121 126
         deliverTo: 'Hantar ke',
122 127
         quantityShort: 'Kuantiti',
128
+        discountCode: 'Kod diskaun',
129
+        apply: 'Guna',
130
+        discount: 'Diskaun',
131
+        removeCode: 'Buang kod',
132
+        codePlaceholder: 'Masukkan kod',
123 133
         shipping: 'Penghantaran',
124 134
         shippingFree: 'Percuma',
125 135
         chooseStateForShipping:

+ 13
- 0
resources/js/storefront/types.ts Просмотреть файл

@@ -185,6 +185,17 @@ export type CartLine = {
185 185
 export type StoreCart = {
186 186
     count: number;
187 187
     subtotal: number;
188
+    /** The discount code in the cart, or null. */
189
+    discount: {
190
+        code: string;
191
+        label: string;
192
+        /** Money off the products, in ringgit. Zero while the code does not count yet. */
193
+        amount: number;
194
+        /** Why the code does not count yet, such as a minimum spend. */
195
+        message: string | null;
196
+    } | null;
197
+    /** Products after the discount, before shipping. */
198
+    total: number;
188 199
     /** True when stock changed and the cart was corrected. */
189 200
     adjusted: boolean;
190 201
     lines: CartLine[];
@@ -211,6 +222,8 @@ export type StoreOrder = {
211 222
     customer_phone: string;
212 223
     shipping_address: OrderAddress;
213 224
     subtotal: number;
225
+    discount_code: string | null;
226
+    discount_total: number;
214 227
     shipping_total: number;
215 228
     total: number;
216 229
     paid_at: string | null;

+ 19
- 0
resources/js/types/store.ts Просмотреть файл

@@ -91,6 +91,8 @@ export type Order = {
91 91
         country: string;
92 92
     };
93 93
     subtotal: number;
94
+    discount_code: string | null;
95
+    discount_total: number;
94 96
     shipping_total: number;
95 97
     total: number;
96 98
     paid_at: string | null;
@@ -143,3 +145,20 @@ export type ProductOption = {
143 145
     name: string;
144 146
     price: number;
145 147
 };
148
+
149
+/** A discount code as the dashboard sees it. Amounts are text in ringgit; dates are Malaysian days (YYYY-MM-DD). */
150
+export type DiscountCode = {
151
+    id: number;
152
+    code: string;
153
+    type: 'percent' | 'fixed';
154
+    /** A whole percentage, or an amount in ringgit such as "5.00". */
155
+    value: string;
156
+    label: string;
157
+    minimum_subtotal: string | null;
158
+    starts_on: string | null;
159
+    ends_on: string | null;
160
+    usage_limit: number | null;
161
+    times_used: number;
162
+    active: boolean;
163
+    status: 'active' | 'off' | 'scheduled' | 'expired' | 'used_up';
164
+};

+ 3
- 0
resources/views/mail/orders/confirmation.blade.php Просмотреть файл

@@ -13,6 +13,9 @@
13 13
 @foreach ($order->items as $item)
14 14
 | {{ $item->name }} | {{ $item->quantity }} | {{ $money($item->line_total) }} |
15 15
 @endforeach
16
+@if ($order->discount_total > 0)
17
+| {{ $malay ? 'Diskaun' : 'Discount' }}{{ $order->discount_code ? ' ('.$order->discount_code.')' : '' }} | | -{{ $money($order->discount_total) }} |
18
+@endif
16 19
 | {{ $malay ? 'Penghantaran' : 'Shipping' }} | | {{ $order->shipping_total === 0 ? ($malay ? 'Percuma' : 'Free') : $money($order->shipping_total) }} |
17 20
 | **{{ $malay ? 'Jumlah dibayar' : 'Total paid' }}** | | **{{ $money($order->total) }}** |
18 21
 </x-mail::table>

+ 12
- 0
routes/web.php Просмотреть файл

@@ -3,6 +3,7 @@
3 3
 use App\Http\Controllers\BillingController;
4 4
 use App\Http\Controllers\CartController;
5 5
 use App\Http\Controllers\CheckoutController;
6
+use App\Http\Controllers\DiscountCodeController;
6 7
 use App\Http\Controllers\FeaturedProductController;
7 8
 use App\Http\Controllers\OrderController;
8 9
 use App\Http\Controllers\ProductController;
@@ -36,6 +37,8 @@ Route::domain('{storeSlug}.'.config('storefront.domain'))
36 37
         Route::post('cart/items', [CartController::class, 'add'])->name('cart.add');
37 38
         Route::patch('cart/items/{product}', [CartController::class, 'update'])->name('cart.update')->whereNumber('product');
38 39
         Route::delete('cart/items/{product}', [CartController::class, 'remove'])->name('cart.remove')->whereNumber('product');
40
+        Route::post('cart/discount', [CartController::class, 'applyDiscount'])->middleware('throttle:20,1')->name('cart.discount');
41
+        Route::delete('cart/discount', [CartController::class, 'removeDiscount'])->name('cart.discount.remove');
39 42
 
40 43
         Route::get('checkout', [CheckoutController::class, 'show'])->name('checkout');
41 44
         Route::post('checkout', [CheckoutController::class, 'store'])->middleware('throttle:20,1')->name('checkout.store');
@@ -72,6 +75,8 @@ Route::middleware(['auth', 'verified'])->group(function () {
72 75
     Route::post('stores/{slug}/preview/cart/items', [CartController::class, 'add'])->name('stores.preview.cart.add');
73 76
     Route::patch('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'update'])->name('stores.preview.cart.update')->whereNumber('product');
74 77
     Route::delete('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'remove'])->name('stores.preview.cart.remove')->whereNumber('product');
78
+    Route::post('stores/{slug}/preview/cart/discount', [CartController::class, 'applyDiscount'])->name('stores.preview.cart.discount');
79
+    Route::delete('stores/{slug}/preview/cart/discount', [CartController::class, 'removeDiscount'])->name('stores.preview.cart.discount.remove');
75 80
 
76 81
     Route::get('stores/{slug}/preview/checkout', [CheckoutController::class, 'show'])->name('stores.preview.checkout');
77 82
     Route::post('stores/{slug}/preview/checkout', [CheckoutController::class, 'store'])->name('stores.preview.checkout.store');
@@ -80,6 +85,13 @@ Route::middleware(['auth', 'verified'])->group(function () {
80 85
     // Pages the merchant added, such as /about. Listed after the store's own pages so those win.
81 86
     Route::get('stores/{slug}/preview/{pageId}', [StoreDesignController::class, 'page'])->name('stores.preview.page')->where('pageId', '[a-z][a-z0-9-]*');
82 87
 
88
+    Route::get('stores/{slug}/discounts', [DiscountCodeController::class, 'index'])->name('stores.discounts.index');
89
+    Route::get('stores/{slug}/discounts/create', [DiscountCodeController::class, 'create'])->name('stores.discounts.create');
90
+    Route::post('stores/{slug}/discounts', [DiscountCodeController::class, 'store'])->name('stores.discounts.store');
91
+    Route::get('stores/{slug}/discounts/{discount}/edit', [DiscountCodeController::class, 'edit'])->name('stores.discounts.edit')->whereNumber('discount');
92
+    Route::put('stores/{slug}/discounts/{discount}', [DiscountCodeController::class, 'update'])->name('stores.discounts.update')->whereNumber('discount');
93
+    Route::delete('stores/{slug}/discounts/{discount}', [DiscountCodeController::class, 'destroy'])->name('stores.discounts.destroy')->whereNumber('discount');
94
+
83 95
     Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
84 96
     Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');
85 97
     Route::post('stores/{slug}/orders/{order}/ship', [OrderController::class, 'ship'])->name('stores.orders.ship')->whereNumber('order');

+ 373
- 0
tests/Feature/Stores/DiscountCodeTest.php Просмотреть файл

@@ -0,0 +1,373 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Mail\OrderConfirmation;
7
+use App\Models\DiscountCode;
8
+use App\Models\Order;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use App\Models\User;
12
+use App\StorePlan\SamplePlan;
13
+use Illuminate\Foundation\Testing\RefreshDatabase;
14
+use Illuminate\Support\Facades\Mail;
15
+use Inertia\Testing\AssertableInertia as Assert;
16
+use Tests\Support\FakeGateway;
17
+use Tests\TestCase;
18
+
19
+class DiscountCodeTest extends TestCase
20
+{
21
+    use RefreshDatabase;
22
+
23
+    private User $user;
24
+
25
+    private Store $store;
26
+
27
+    private FakeGateway $gateway;
28
+
29
+    protected function setUp(): void
30
+    {
31
+        parent::setUp();
32
+
33
+        Mail::fake();
34
+        $this->gateway = new FakeGateway;
35
+        $this->app->instance(PaymentGateway::class, $this->gateway);
36
+
37
+        $this->user = User::factory()->create();
38
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
39
+        $this->store->plan = SamplePlan::for($this->store);
40
+        $this->store->save();
41
+        $this->actingAs($this->user);
42
+    }
43
+
44
+    private function addToCart(int $price, int $quantity = 1): Product
45
+    {
46
+        $product = Product::factory()->for($this->store)->create(['price' => $price, 'stock' => 50]);
47
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity]);
48
+
49
+        return $product;
50
+    }
51
+
52
+    private function apply(string $code)
53
+    {
54
+        return $this->post(route('stores.preview.cart.discount', $this->store->slug), ['code' => $code]);
55
+    }
56
+
57
+    private function cart(): Assert|callable
58
+    {
59
+        return fn (callable $assert) => $this->get(route('stores.preview.cart', $this->store->slug))
60
+            ->assertInertia(fn (Assert $page) => $assert($page));
61
+    }
62
+
63
+    private function placeOrder(string $state = 'Selangor'): Order
64
+    {
65
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
66
+            'name' => 'Aminah binti Ali',
67
+            'email' => 'aminah@example.com',
68
+            'phone' => '0123456789',
69
+            'line1' => '12 Jalan Mawar',
70
+            'city' => 'Shah Alam',
71
+            'postcode' => '40000',
72
+            'state' => $state,
73
+        ])->assertRedirect();
74
+
75
+        return Order::latest('id')->firstOrFail();
76
+    }
77
+
78
+    /** @return array<string, mixed> */
79
+    private function form(array $overrides = []): array
80
+    {
81
+        return [
82
+            'code' => 'raya10',
83
+            'type' => 'percent',
84
+            'value' => '10',
85
+            'minimum_subtotal' => '',
86
+            'starts_on' => '',
87
+            'ends_on' => '',
88
+            'usage_limit' => '',
89
+            'active' => '1',
90
+            ...$overrides,
91
+        ];
92
+    }
93
+
94
+    public function test_the_merchant_can_create_edit_and_delete_codes()
95
+    {
96
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form([
97
+            'minimum_subtotal' => '50',
98
+            'starts_on' => '2027-04-01',
99
+            'ends_on' => '2027-04-30',
100
+            'usage_limit' => '100',
101
+        ]))->assertRedirect(route('stores.discounts.index', $this->store->slug));
102
+
103
+        $code = $this->store->discountCodes()->firstOrFail();
104
+
105
+        $this->assertSame('RAYA10', $code->code);
106
+        $this->assertSame(10, $code->value);
107
+        $this->assertSame(5000, $code->minimum_subtotal);
108
+        $this->assertSame(100, $code->usage_limit);
109
+        // Days are Malaysian days: 1 April 00:00 in Kuala Lumpur is 31 March 16:00 UTC.
110
+        $this->assertSame('2027-03-31 16:00:00', $code->starts_at->utc()->toDateTimeString());
111
+        $this->assertSame('2027-04-30 15:59:59', $code->ends_at->utc()->toDateTimeString());
112
+
113
+        $this->get(route('stores.discounts.index', $this->store->slug))
114
+            ->assertInertia(fn (Assert $page) => $page
115
+                ->component('stores/discounts/index')
116
+                ->has('codes', 1)
117
+                ->where('codes.0.label', '10% off')
118
+                ->where('codes.0.starts_on', '2027-04-01')
119
+                ->where('codes.0.ends_on', '2027-04-30'));
120
+
121
+        $this->put(route('stores.discounts.update', [$this->store->slug, $code->id]), $this->form([
122
+            'code' => 'RAYA10', 'type' => 'fixed', 'value' => '7.50', 'active' => '0',
123
+        ]))->assertRedirect(route('stores.discounts.index', $this->store->slug));
124
+
125
+        $code->refresh();
126
+        $this->assertSame('fixed', $code->type);
127
+        $this->assertSame(750, $code->value);
128
+        $this->assertFalse($code->active);
129
+        $this->assertSame('off', $code->status());
130
+
131
+        $this->delete(route('stores.discounts.destroy', [$this->store->slug, $code->id]));
132
+        $this->assertSame(0, $this->store->discountCodes()->count());
133
+    }
134
+
135
+    public function test_code_details_are_checked()
136
+    {
137
+        DiscountCode::factory()->for($this->store)->create(['code' => 'TAKEN']);
138
+
139
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form([
140
+            'code' => 'no spaces!', 'value' => '150', 'ends_on' => '2027-01-01', 'starts_on' => '2027-02-01',
141
+        ]))->assertSessionHasErrors(['code', 'value', 'ends_on']);
142
+
143
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form(['code' => 'taken']))
144
+            ->assertSessionHasErrors('code');
145
+
146
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form(['type' => 'fixed', 'value' => '0']))
147
+            ->assertSessionHasErrors('value');
148
+
149
+        // The same code may exist in another store.
150
+        DiscountCode::factory()->create(['code' => 'RAYA10']);
151
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form())->assertSessionHasNoErrors();
152
+    }
153
+
154
+    public function test_a_percentage_code_takes_money_off_the_products_in_the_cart()
155
+    {
156
+        DiscountCode::factory()->for($this->store)->percent(10)->create(['code' => 'RAYA10']);
157
+        $this->addToCart(1999, 3);
158
+
159
+        // Shoppers may type it in small letters with spaces.
160
+        $this->apply(' raya10 ')->assertSessionHasNoErrors();
161
+
162
+        ($this->cart())(fn (Assert $page) => $page
163
+            ->where('cart.subtotal', 59.97)
164
+            // 10% of 59.97 is 5.997, rounded down to 5.99.
165
+            ->where('cart.discount.code', 'RAYA10')
166
+            ->where('cart.discount.label', '10% off')
167
+            ->where('cart.discount.amount', 5.99)
168
+            ->where('cart.discount.message', null)
169
+            ->where('cart.total', 53.98));
170
+    }
171
+
172
+    public function test_a_fixed_code_never_takes_off_more_than_the_products_cost()
173
+    {
174
+        DiscountCode::factory()->for($this->store)->fixed(5000)->create(['code' => 'BIG']);
175
+        $this->addToCart(3000);
176
+
177
+        $this->apply('BIG');
178
+
179
+        ($this->cart())(fn (Assert $page) => $page->where('cart.discount.amount', 30)->where('cart.total', 0));
180
+    }
181
+
182
+    public function test_unusable_codes_are_refused_with_a_reason()
183
+    {
184
+        $this->addToCart(2000);
185
+
186
+        DiscountCode::factory()->for($this->store)->create(['code' => 'OFF', 'active' => false]);
187
+        DiscountCode::factory()->for($this->store)->create(['code' => 'LATER', 'starts_at' => now()->addDay()]);
188
+        DiscountCode::factory()->for($this->store)->create(['code' => 'OLD', 'ends_at' => now()->subMinute()]);
189
+        DiscountCode::factory()->for($this->store)->create(['code' => 'GONE', 'usage_limit' => 5, 'times_used' => 5]);
190
+        DiscountCode::factory()->create(['code' => 'OTHERSTORE']);
191
+
192
+        $this->apply('NOPE')->assertSessionHasErrors(['code' => 'This code is not valid.']);
193
+        $this->apply('OFF')->assertSessionHasErrors(['code' => 'This code is not valid.']);
194
+        $this->apply('LATER')->assertSessionHasErrors(['code' => 'This code cannot be used yet.']);
195
+        $this->apply('OLD')->assertSessionHasErrors(['code' => 'This code has expired.']);
196
+        $this->apply('GONE')->assertSessionHasErrors(['code' => 'This code has been used up.']);
197
+        $this->apply('OTHERSTORE')->assertSessionHasErrors(['code' => 'This code is not valid.']);
198
+
199
+        ($this->cart())(fn (Assert $page) => $page->where('cart.discount', null));
200
+    }
201
+
202
+    public function test_a_code_with_a_minimum_spend_waits_until_the_cart_is_big_enough()
203
+    {
204
+        DiscountCode::factory()->for($this->store)->fixed(500)->create(['code' => 'MIN50', 'minimum_subtotal' => 5000]);
205
+        $this->addToCart(3000);
206
+
207
+        $this->apply('MIN50')->assertSessionHasNoErrors();
208
+
209
+        ($this->cart())(fn (Assert $page) => $page
210
+            ->where('cart.discount.code', 'MIN50')
211
+            ->where('cart.discount.amount', 0)
212
+            ->where('cart.discount.message', 'Spend at least RM 50.00 on products to use this code.')
213
+            ->where('cart.total', 30));
214
+
215
+        $this->addToCart(2000);
216
+
217
+        ($this->cart())(fn (Assert $page) => $page
218
+            ->where('cart.discount.amount', 5)
219
+            ->where('cart.discount.message', null)
220
+            ->where('cart.total', 45));
221
+    }
222
+
223
+    public function test_the_code_can_be_removed()
224
+    {
225
+        DiscountCode::factory()->for($this->store)->create(['code' => 'RAYA10']);
226
+        $this->addToCart(2000);
227
+        $this->apply('RAYA10');
228
+
229
+        $this->delete(route('stores.preview.cart.discount.remove', $this->store->slug))->assertRedirect();
230
+
231
+        ($this->cart())(fn (Assert $page) => $page->where('cart.discount', null)->where('cart.total', 20));
232
+    }
233
+
234
+    public function test_a_code_switched_off_after_it_was_applied_is_taken_out_and_the_shopper_is_told()
235
+    {
236
+        $code = DiscountCode::factory()->for($this->store)->create(['code' => 'RAYA10']);
237
+        $this->addToCart(2000);
238
+        $this->apply('RAYA10');
239
+
240
+        $code->forceFill(['active' => false])->save();
241
+
242
+        ($this->cart())(fn (Assert $page) => $page->where('cart.discount', null)->where('cart.adjusted', true));
243
+    }
244
+
245
+    public function test_the_order_records_the_discount_and_shipping_is_charged_in_full()
246
+    {
247
+        DiscountCode::factory()->for($this->store)->percent(20)->create(['code' => 'SAVE20']);
248
+        $this->addToCart(5000);
249
+        $this->apply('SAVE20');
250
+
251
+        $order = $this->placeOrder('Sabah');
252
+
253
+        $this->assertSame(5000, $order->subtotal);
254
+        $this->assertSame('SAVE20', $order->discount_code);
255
+        $this->assertSame(1000, $order->discount_total);
256
+        $this->assertSame(1500, $order->shipping_total);
257
+        $this->assertSame(5500, $order->total);
258
+    }
259
+
260
+    public function test_free_shipping_is_judged_on_the_price_after_the_discount()
261
+    {
262
+        $this->store->forceFill(['free_shipping_over' => 10000])->save();
263
+        DiscountCode::factory()->for($this->store)->percent(10)->create(['code' => 'SAVE10']);
264
+        $this->addToCart(10000);
265
+        $this->apply('SAVE10');
266
+
267
+        // RM 100 of products minus 10% is RM 90, which is under the RM 100 free-shipping amount.
268
+        $this->get(route('stores.preview.checkout', $this->store->slug))
269
+            ->assertInertia(fn (Assert $page) => $page->where('view.shippingByState.Selangor', 8));
270
+
271
+        $this->assertSame(800, $this->placeOrder()->shipping_total);
272
+    }
273
+
274
+    public function test_a_code_that_stopped_working_stops_checkout_so_the_total_never_surprises()
275
+    {
276
+        $code = DiscountCode::factory()->for($this->store)->create(['code' => 'RAYA10']);
277
+        $this->addToCart(2000);
278
+        $this->apply('RAYA10');
279
+
280
+        $code->forceFill(['ends_at' => now()->subMinute()])->save();
281
+
282
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
283
+            'name' => 'Aminah', 'email' => 'a@example.com', 'phone' => '0123456789',
284
+            'line1' => '12 Jalan Mawar', 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor',
285
+        ])->assertSessionHasErrors(['cart' => 'Your discount code can no longer be used, so it was removed. Please check your total.']);
286
+
287
+        $this->assertSame(0, Order::count());
288
+    }
289
+
290
+    public function test_an_order_must_still_be_at_least_two_ringgit_after_the_discount()
291
+    {
292
+        $this->store->forceFill(['free_shipping_over' => 0])->save();
293
+        DiscountCode::factory()->for($this->store)->percent(100)->create(['code' => 'FREE']);
294
+        $this->addToCart(2000);
295
+        $this->apply('FREE');
296
+
297
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
298
+            'name' => 'Aminah', 'email' => 'a@example.com', 'phone' => '0123456789',
299
+            'line1' => '12 Jalan Mawar', 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor',
300
+        ])->assertSessionHasErrors(['cart' => 'After the discount, the order total must be at least RM 2.00.']);
301
+    }
302
+
303
+    public function test_a_use_is_counted_only_when_the_order_is_paid_and_only_once()
304
+    {
305
+        $code = DiscountCode::factory()->for($this->store)->create(['code' => 'RAYA10', 'usage_limit' => 2]);
306
+        $this->addToCart(2000);
307
+        $this->apply('RAYA10');
308
+        $order = $this->placeOrder();
309
+
310
+        $this->assertSame(0, $code->fresh()->times_used);
311
+
312
+        $this->gateway->pay($order);
313
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
314
+            ->assertInertia(fn (Assert $page) => $page
315
+                ->where('view.order.discount_code', 'RAYA10')
316
+                ->where('view.order.discount_total', 2));
317
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
318
+
319
+        $this->assertSame(1, $code->fresh()->times_used);
320
+
321
+        $mail = new OrderConfirmation($order->fresh());
322
+        $mail->assertSeeInHtml('RAYA10');
323
+        $mail->assertSeeInHtml('-RM 2.00');
324
+    }
325
+
326
+    public function test_messages_follow_the_store_language()
327
+    {
328
+        $this->store->update(['language' => 'ms']);
329
+        DiscountCode::factory()->for($this->store)->percent(15)->create(['code' => 'MERDEKA']);
330
+        $this->addToCart(2000);
331
+
332
+        $this->apply('TIADA')->assertSessionHasErrors(['code' => 'Kod ini tidak sah.']);
333
+        $this->apply('MERDEKA');
334
+
335
+        ($this->cart())(fn (Assert $page) => $page->where('cart.discount.label', 'Diskaun 15%'));
336
+    }
337
+
338
+    public function test_another_merchant_cannot_see_or_change_codes()
339
+    {
340
+        $code = DiscountCode::factory()->for($this->store)->create();
341
+
342
+        $this->actingAs(User::factory()->create());
343
+
344
+        $this->get(route('stores.discounts.index', $this->store->slug))->assertNotFound();
345
+        $this->post(route('stores.discounts.store', $this->store->slug), $this->form())->assertNotFound();
346
+        $this->get(route('stores.discounts.edit', [$this->store->slug, $code->id]))->assertNotFound();
347
+        $this->put(route('stores.discounts.update', [$this->store->slug, $code->id]), $this->form())->assertNotFound();
348
+        $this->delete(route('stores.discounts.destroy', [$this->store->slug, $code->id]))->assertNotFound();
349
+
350
+        $this->assertTrue($code->fresh()->exists);
351
+    }
352
+
353
+    public function test_codes_work_on_the_live_store_too()
354
+    {
355
+        DiscountCode::factory()->for($this->store)->percent(10)->create(['code' => 'RAYA10']);
356
+        $product = Product::factory()->for($this->store)->create(['price' => 2000, 'stock' => 5]);
357
+        $this->post(route('stores.publish', $this->store->slug));
358
+        auth()->logout();
359
+
360
+        $live = 'http://'.$this->store->slug.'.localhost';
361
+
362
+        $this->post($live.'/cart/items', ['product_id' => $product->id, 'quantity' => 1]);
363
+        $this->post($live.'/cart/discount', ['code' => 'raya10'])->assertSessionHasNoErrors();
364
+
365
+        $this->get($live.'/cart')->assertInertia(fn (Assert $page) => $page
366
+            ->where('cart.discount.amount', 2)
367
+            ->where('cart.total', 18));
368
+
369
+        $this->delete($live.'/cart/discount');
370
+
371
+        $this->get($live.'/cart')->assertInertia(fn (Assert $page) => $page->where('cart.discount', null));
372
+    }
373
+}

Загрузка…
Отмена
Сохранить