Sfoglia il codice sorgente

Add cart, Stripe checkout, orders and order confirmation email

Step 4 part 2:
- Session cart per store with stock limits and self-correction.
- Checkout: shopper details, order snapshot, Stripe hosted payment page
  behind a PaymentGateway interface, return-page and webhook confirmation.
- Orders tab for the merchant and a confirmation email in the store language.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
feature/commerce
fahmisaad 5 giorni fa
parent
commit
09c0259704
51 ha cambiato i file con 3200 aggiunte e 107 eliminazioni
  1. 6
    0
      .env
  2. 48
    33
      PROGRESS.md
  3. 31
    11
      README.md
  4. 183
    0
      app/Commerce/Cart.php
  5. 144
    0
      app/Commerce/Checkout.php
  6. 16
    0
      app/Commerce/MalaysianStates.php
  7. 16
    0
      app/Commerce/Payments/CheckoutLink.php
  8. 10
    0
      app/Commerce/Payments/PaymentException.php
  9. 37
    0
      app/Commerce/Payments/PaymentGateway.php
  10. 18
    0
      app/Commerce/Payments/PaymentStatus.php
  11. 112
    0
      app/Commerce/Payments/StripeGateway.php
  12. 19
    0
      app/Enums/OrderStatus.php
  13. 81
    0
      app/Http/Controllers/CartController.php
  14. 117
    0
      app/Http/Controllers/CheckoutController.php
  15. 56
    0
      app/Http/Controllers/Concerns/RendersStorefront.php
  16. 45
    0
      app/Http/Controllers/OrderController.php
  17. 12
    38
      app/Http/Controllers/StoreDesignController.php
  18. 38
    0
      app/Http/Controllers/StripeWebhookController.php
  19. 44
    0
      app/Mail/OrderConfirmation.php
  20. 111
    0
      app/Models/Order.php
  21. 31
    0
      app/Models/OrderItem.php
  22. 1
    0
      app/Models/Product.php
  23. 8
    0
      app/Models/Store.php
  24. 4
    1
      app/Providers/AppServiceProvider.php
  25. 3
    0
      bootstrap/app.php
  26. 2
    1
      composer.json
  27. 63
    1
      composer.lock
  28. 9
    0
      config/services.php
  29. 48
    0
      database/factories/OrderFactory.php
  30. 62
    0
      database/migrations/2026_11_14_000006_create_orders_table.php
  31. 7
    1
      resources/js/components/stores/store-nav.tsx
  32. 18
    0
      resources/js/lib/money.ts
  33. 138
    0
      resources/js/pages/stores/orders/index.tsx
  34. 132
    0
      resources/js/pages/stores/orders/show.tsx
  35. 4
    0
      resources/js/pages/stores/preview.tsx
  36. 3
    1
      resources/js/storefront/context.tsx
  37. 155
    0
      resources/js/storefront/pages/cart.tsx
  38. 231
    0
      resources/js/storefront/pages/checkout.tsx
  39. 70
    0
      resources/js/storefront/pages/order.tsx
  40. 86
    12
      resources/js/storefront/pages/product.tsx
  41. 21
    1
      resources/js/storefront/renderer.tsx
  42. 40
    5
      resources/js/storefront/sections/header.tsx
  43. 83
    2
      resources/js/storefront/text.ts
  44. 56
    0
      resources/js/storefront/types.ts
  45. 51
    0
      resources/js/storefront/ui.tsx
  46. 32
    0
      resources/js/types/store.ts
  47. 26
    0
      resources/views/mail/orders/confirmation.blade.php
  48. 19
    0
      routes/web.php
  49. 204
    0
      tests/Feature/Stores/CartTest.php
  50. 381
    0
      tests/Feature/Stores/CheckoutTest.php
  51. 68
    0
      tests/Support/FakeGateway.php

+ 6
- 0
.env Vedi File

@@ -71,6 +71,10 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
71 71
 
72 72
 VITE_APP_NAME="${APP_NAME}"
73 73
 
74
+
75
+STRIPE_KEY=
76
+STRIPE_SECRET=
77
+
74 78
 # AI. Each task picks its own provider and model. Change these lines to switch models; no code changes.
75 79
 # Providers: claude, deepseek, fake (no API key needed, returns a sample design).
76 80
 # Set these in .env.local, never here. This file is uploaded to the repository.
@@ -84,3 +88,5 @@ DEEPSEEK_API_KEY=
84 88
 
85 89
 # Must be longer than the longest background job (AI jobs can take several minutes).
86 90
 DB_QUEUE_RETRY_AFTER=600
91
+# Optional. Lets Stripe tell the app about payments directly. Starts with whsec_.
92
+STRIPE_WEBHOOK_SECRET=

+ 48
- 33
PROGRESS.md Vedi File

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-14
7
-**Current step:** Step 4 — Commerce (part 1 done: pages format, products, Shop page and product page)
8
-**Next action:** Step 4 part 2: cart, then checkout with Stripe Malaysia in test mode (needs Stripe test keys in `.env.local`), orders list, order confirmation email
7
+**Current step:** Step 5 — Publishing (Step 4 Commerce is done and tested with a real Stripe test payment)
8
+**Next action:** Merge the feature branches into `main`, then start Step 5: publish a store so real shoppers can open it (local: `storename.localhost`)
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -75,6 +75,12 @@ Changing from Claude to another AI model (or back) must be a settings change, no
75 75
 - `PlanUpgrader` converts an old version 1 plan to version 2.
76 76
 - `PlanSchema.php` is the one place that says what is allowed. `PlanValidator` checks every plan before saving and removes anything unknown. Links can only point inside the page, inside the site, or to `https`, `mailto` and `tel` addresses.
77 77
 - Products: prices are saved in sen (whole numbers) to avoid rounding errors. Photos are saved on the `public` storage disk, which needs `php artisan storage:link` once per machine.
78
+- Cart: only product ids and quantities are saved in the session. Prices and stock are always read fresh, so the cart never shows an old price, and it corrects itself when stock runs low or a product is hidden.
79
+- Checkout: the shopper fills in contact details and a Malaysian address, we save an order as "Awaiting payment", then send them to Stripe's own payment page. Card details never touch our server.
80
+- An order keeps its own copy of product names and prices, so it never changes when a product is edited or deleted later. Order numbers count up per store from 1001.
81
+- An order becomes "Paid" only after we ask Stripe directly and the amount matches. Then stock goes down, the cart is emptied and the email is sent. This happens once, even if both the return page and the webhook report the payment.
82
+- Payments go through one interface (`PaymentGateway`), like the AI layer. Stripe is the only provider for now.
83
+- Stripe shows whichever payment methods are switched on in the Stripe dashboard for MYR (cards now; FPX and e-wallets can be switched on there, Step 7).
78 84
 - Until a store has real products, its home page shows the example products the AI wrote.
79 85
 - To add a new section type: add it to `PlanSchema.php` and `types.ts`, write one React component, add one line in `renderer.tsx`.
80 86
 - The storefront uses its own colours through `--sf-*` CSS variables, so it never mixes with the dashboard theme.
@@ -150,10 +156,11 @@ Changing from Claude to another AI model (or back) must be a settings change, no
150 156
 - [x] Products: create, edit, delete, up to 5 photos, price, price before discount, stock, draft or active
151 157
 - [x] Shop page (all products) and product page, built by us, in the store's colours and fonts
152 158
 - [x] The home page product section shows real products once the merchant adds some, with a "View all" button
153
-- [ ] Cart
154
-- [ ] Checkout with Stripe Malaysia (test mode)
155
-- [ ] Orders list for the merchant
156
-- [ ] Order confirmation email
159
+- [x] Cart: add from the product page, change quantity, remove, subtotal, cart count in the header. Kept in the browser session, one cart per store, no account needed
160
+- [x] Checkout with Stripe Malaysia (test mode): shopper details and address, then Stripe's hosted payment page. Tested with a real Stripe test payment on 2026-11-15
161
+- [x] Orders list and order page for the merchant ("Orders" tab)
162
+- [x] Order confirmation email, in the store's language, sent once when the order is paid
163
+- [ ] Known gaps, to do later: shipping fee is RM 0 until EasyParcel (Step 7); the merchant cannot mark an order as shipped yet; unpaid orders stay in the list as "Awaiting payment"; the Stripe webhook needs a public address, so it only starts working after hosting (Step 8)
157 164
 - [ ] Later in this step or right after: let the merchant add content pages by chat ("add an About page"). The format already supports it
158 165
 
159 166
 ### Step 5 — Publishing
@@ -224,36 +231,42 @@ Then, from the project folder:
224 231
 
225 232
 ## 4b. Where things are in the code
226 233
 
227
-| Thing                                 | Location                                                                    |
228
-| ------------------------------------- | --------------------------------------------------------------------------- |
229
-| Store model                           | `app/Models/Store.php`                                                      |
230
-| Store screens logic                   | `app/Http/Controllers/StoreController.php`                                  |
231
-| Store categories, languages, statuses | `app/Enums/`                                                                |
232
-| Store form rules                      | `app/Http/Requests/Stores/CreateStoreRequest.php`                           |
233
-| Screens                               | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`            |
234
-| Store tests                           | `tests/Feature/Stores/`                                                     |
235
-| Store plan format (the rules)         | `app/StorePlan/PlanSchema.php`                                              |
236
-| Store plan checker                    | `app/StorePlan/PlanValidator.php`                                           |
237
-| Sample plan                           | `app/StorePlan/SamplePlan.php`                                              |
238
-| Preview logic                         | `app/Http/Controllers/StoreDesignController.php`                            |
239
-| AI settings                           | `config/ai.php` (providers, models per task)                                |
240
-| AI layer and providers                | `app/Ai/`, `app/Ai/Drivers/`                                                |
241
-| AI prompts, generation and chat edits | `app/StorePlan/Ai/`                                                         |
242
-| Start an AI job (buttons)             | `app/Http/Controllers/StoreGenerationController.php`                        |
243
-| Background AI job                     | `app/Jobs/RunStoreGeneration.php`                                           |
244
-| Plan limits and usage counting        | `config/plans.php`, `app/Billing/UsageLimits.php`                           |
245
-| Progress screen and chat box          | `resources/js/components/stores/`                                           |
246
-| Product model and photos              | `app/Models/Product.php`, `app/Models/ProductImage.php`                     |
247
-| Product screens logic                 | `app/Http/Controllers/ProductController.php`                                |
248
-| Product screens                       | `resources/js/pages/stores/products/`                                       |
249
-| Storefront Shop and product pages     | `resources/js/storefront/pages/`                                            |
250
-| Storefront words (English, Malay)     | `resources/js/storefront/text.ts`                                           |
251
-| Store plan format (frontend types)    | `resources/js/storefront/types.ts`                                          |
252
-| Storefront renderer and sections      | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/` |
234
+| Thing                                 | Location                                                                        |
235
+| ------------------------------------- | ------------------------------------------------------------------------------- |
236
+| Store model                           | `app/Models/Store.php`                                                          |
237
+| Store screens logic                   | `app/Http/Controllers/StoreController.php`                                      |
238
+| Store categories, languages, statuses | `app/Enums/`                                                                    |
239
+| Store form rules                      | `app/Http/Requests/Stores/CreateStoreRequest.php`                               |
240
+| Screens                               | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                |
241
+| Store tests                           | `tests/Feature/Stores/`                                                         |
242
+| Store plan format (the rules)         | `app/StorePlan/PlanSchema.php`                                                  |
243
+| Store plan checker                    | `app/StorePlan/PlanValidator.php`                                               |
244
+| Sample plan                           | `app/StorePlan/SamplePlan.php`                                                  |
245
+| Preview logic                         | `app/Http/Controllers/StoreDesignController.php`                                |
246
+| AI settings                           | `config/ai.php` (providers, models per task)                                    |
247
+| AI layer and providers                | `app/Ai/`, `app/Ai/Drivers/`                                                    |
248
+| AI prompts, generation and chat edits | `app/StorePlan/Ai/`                                                             |
249
+| Start an AI job (buttons)             | `app/Http/Controllers/StoreGenerationController.php`                            |
250
+| Background AI job                     | `app/Jobs/RunStoreGeneration.php`                                               |
251
+| Plan limits and usage counting        | `config/plans.php`, `app/Billing/UsageLimits.php`                               |
252
+| Progress screen and chat box          | `resources/js/components/stores/`                                               |
253
+| Product model and photos              | `app/Models/Product.php`, `app/Models/ProductImage.php`                         |
254
+| Product screens logic                 | `app/Http/Controllers/ProductController.php`                                    |
255
+| Product screens                       | `resources/js/pages/stores/products/`                                           |
256
+| Storefront Shop and product pages     | `resources/js/storefront/pages/`                                                |
257
+| Checkout and order logic              | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`      |
258
+| Payment providers                     | `app/Commerce/Payments/` (interface and Stripe)                                 |
259
+| Stripe webhook                        | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`) |
260
+| Orders for the merchant               | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |
261
+| Order email                           | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                |
262
+| Cart logic                            | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`              |
263
+| Storefront words (English, Malay)     | `resources/js/storefront/text.ts`                                               |
264
+| Store plan format (frontend types)    | `resources/js/storefront/types.ts`                                              |
265
+| Storefront renderer and sections      | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`     |
253 266
 
254 267
 ## 5. Open questions
255 268
 
256
-- Stripe test keys (publishable and secret) for Step 4 part 2
269
+- **Who receives the money?** Today every payment goes to our own Stripe account (the keys in `.env.local`). Before real merchants sell, each merchant must be paid into their own account. The usual way is Stripe Connect. Decide before launch; it changes the checkout a little and adds an onboarding step for merchants.
257 270
 - Hosting provider (decide at Step 8)
258 271
 
259 272
 ## 6. Later improvements
@@ -280,3 +293,5 @@ Add one line per work session: date, what was done, what is next.
280 293
 | 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                      | Real AI test, then Step 4                                       |
281 294
 | 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                       | Merge into `main`, then Step 4: products                        |
282 295
 | 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                             | Step 4 part 2: cart, Stripe checkout, orders, email             |
296
+| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                   | Stripe checkout (needs test keys), orders, email                |
297
+| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                   | Merge into `main`, then Step 5: publishing                      |

+ 31
- 11
README.md Vedi File

@@ -10,17 +10,17 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
10 10
 
11 11
 ## Current status
12 12
 
13
-| Step | What                                                    | Status                                                            |
14
-| ---- | ------------------------------------------------------- | ----------------------------------------------------------------- |
15
-| 0    | Prepare the local machine                               | Done                                                              |
16
-| 1    | Project foundation: login, create a store, dashboard    | Done                                                              |
17
-| 2    | Store sections, renderer and preview                    | Done                                                              |
18
-| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                              |
19
-| 4    | Commerce: products, cart, checkout with Stripe Malaysia | In progress: products and shop pages done, cart and checkout next |
20
-| 5    | Publishing: subdomains, then custom domains             | Not started                                                       |
21
-| 6    | Our own subscription billing                            | Not started                                                       |
22
-| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Not started                                                       |
23
-| 8    | Before launch: hosting, legal pages, backups            | Not started                                                       |
13
+| Step | What                                                    | Status      |
14
+| ---- | ------------------------------------------------------- | ----------- |
15
+| 0    | Prepare the local machine                               | Done        |
16
+| 1    | Project foundation: login, create a store, dashboard    | Done        |
17
+| 2    | Store sections, renderer and preview                    | Done        |
18
+| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done        |
19
+| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done        |
20
+| 5    | Publishing: subdomains, then custom domains             | Next        |
21
+| 6    | Our own subscription billing                            | Not started |
22
+| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Not started |
23
+| 8    | Before launch: hosting, legal pages, backups            | Not started |
24 24
 
25 25
 ## What works today
26 26
 
@@ -38,6 +38,9 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
38 38
 - Products: add, edit, delete, up to 5 photos, price, stock, draft or active
39 39
 - A Shop page with all products and a page for each product, in the store's design
40 40
 - The home page shows the merchant's real products, with a "View all" button
41
+- Cart: add products, change quantities, remove items, see the subtotal. No account needed
42
+- Checkout with Stripe (test mode): shopper details, Stripe's hosted payment page, thank-you page
43
+- Orders tab for the merchant, and an order confirmation email to the shopper
41 44
 
42 45
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.
43 46
 
@@ -186,6 +189,21 @@ Changing from Claude to another AI model is a settings change, not a code rewrit
186 189
 - AI work runs in the background, so the worker must be running. `composer run dev` starts it.
187 190
 - Settings are in `config/ai.php`. Plan limits are in `config/plans.php`.
188 191
 
192
+## Payments
193
+
194
+- Checkout uses Stripe's hosted payment page, so card details never touch this app.
195
+- Put your Stripe **test** keys in `.env.local`:
196
+
197
+    ```
198
+    STRIPE_KEY=pk_test_...
199
+    STRIPE_SECRET=sk_test_...
200
+    ```
201
+
202
+- To test a payment, use Stripe's test card `4242 4242 4242 4242`, any future date and any 3 digits.
203
+- `STRIPE_WEBHOOK_SECRET` is optional on a local machine. The app also confirms a payment when the shopper returns from Stripe. The webhook address is `/stripe/webhook`.
204
+- All payments go through one interface (`app/Commerce/Payments/PaymentGateway.php`), so another provider can be added without changing the checkout.
205
+- Money is always saved in sen (whole numbers).
206
+
189 207
 ## Plans and limits
190 208
 
191 209
 Starting numbers, to adjust after real usage.
@@ -232,3 +250,5 @@ Starting numbers, to adjust after real usage.
232 250
 ## License
233 251
 
234 252
 Private. All rights reserved.
253
+| Cart, checkout and payments | `app/Commerce/` |
254
+| Orders for the merchant | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |

+ 183
- 0
app/Commerce/Cart.php Vedi File

@@ -0,0 +1,183 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Models\Product;
6
+use App\Models\Store;
7
+use Illuminate\Contracts\Session\Session;
8
+use Illuminate\Support\Collection;
9
+
10
+/**
11
+ * A shopper's cart for one store.
12
+ *
13
+ * It is kept in the browser session, so shoppers do not need an account, and each store
14
+ * has its own cart. Only product ids and quantities are saved. Names, prices and stock are
15
+ * always read fresh from the database, so the cart can never show an old price.
16
+ */
17
+class Cart
18
+{
19
+    /** The most of one product a shopper may put in the cart. */
20
+    public const int MAX_QUANTITY = 99;
21
+
22
+    /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
23
+    private bool $adjusted = false;
24
+
25
+    public function __construct(
26
+        private readonly Session $session,
27
+        private readonly Store $store,
28
+    ) {}
29
+
30
+    /**
31
+     * Put more of a product in the cart. Returns how many are in the cart afterwards.
32
+     */
33
+    public function add(Product $product, int $quantity): int
34
+    {
35
+        return $this->store(($this->quantities()[$product->id] ?? 0) + $quantity, $product);
36
+    }
37
+
38
+    /**
39
+     * Set exactly how many of a product are in the cart. Zero removes it.
40
+     * The number is capped by the stock and by MAX_QUANTITY.
41
+     */
42
+    public function set(Product $product, int $quantity): int
43
+    {
44
+        return $this->store($quantity, $product);
45
+    }
46
+
47
+    private function store(int $wanted, Product $product): int
48
+    {
49
+        $quantities = $this->quantities();
50
+        $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY));
51
+
52
+        if ($allowed === 0) {
53
+            unset($quantities[$product->id]);
54
+        } else {
55
+            $quantities[$product->id] = $allowed;
56
+        }
57
+
58
+        $this->save($quantities);
59
+
60
+        return $allowed;
61
+    }
62
+
63
+    public function remove(int $productId): void
64
+    {
65
+        $quantities = $this->quantities();
66
+        unset($quantities[$productId]);
67
+
68
+        $this->save($quantities);
69
+    }
70
+
71
+    public function clear(): void
72
+    {
73
+        $this->session->forget($this->key());
74
+    }
75
+
76
+    /**
77
+     * The cart lines, with fresh product details.
78
+     * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
79
+     *
80
+     * @return Collection<int, array{product: Product, quantity: int, line_total: int}>
81
+     */
82
+    public function lines(): Collection
83
+    {
84
+        $quantities = $this->quantities();
85
+
86
+        if ($quantities === []) {
87
+            return collect();
88
+        }
89
+
90
+        $products = $this->store->products()
91
+            ->active()
92
+            ->with('images')
93
+            ->whereKey(array_keys($quantities))
94
+            ->get()
95
+            ->keyBy('id');
96
+
97
+        $kept = [];
98
+        $lines = collect();
99
+
100
+        foreach ($quantities as $productId => $quantity) {
101
+            $product = $products->get($productId);
102
+            $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0;
103
+
104
+            if ($allowed !== $quantity) {
105
+                $this->adjusted = true;
106
+            }
107
+
108
+            if ($product === null || $allowed < 1) {
109
+                continue;
110
+            }
111
+
112
+            $kept[$productId] = $allowed;
113
+            $lines->push([
114
+                'product' => $product,
115
+                'quantity' => $allowed,
116
+                'line_total' => $product->price * $allowed,
117
+            ]);
118
+        }
119
+
120
+        if ($kept !== $quantities) {
121
+            $this->save($kept);
122
+        }
123
+
124
+        return $lines;
125
+    }
126
+
127
+    /**
128
+     * What the storefront is allowed to see. Money is in ringgit here.
129
+     *
130
+     * @return array{count: int, subtotal: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
131
+     */
132
+    public function toStorefront(): array
133
+    {
134
+        $lines = $this->lines();
135
+
136
+        return [
137
+            'count' => (int) $lines->sum('quantity'),
138
+            'subtotal' => $lines->sum('line_total') / 100,
139
+            'adjusted' => $this->adjusted,
140
+            'lines' => $lines->map(fn (array $line) => [
141
+                'product' => $line['product']->toStorefront(),
142
+                'quantity' => $line['quantity'],
143
+                'max' => min($line['product']->stock, self::MAX_QUANTITY),
144
+                'line_total' => $line['line_total'] / 100,
145
+            ])->values()->all(),
146
+        ];
147
+    }
148
+
149
+    /**
150
+     * @return array<int, int> Product id to quantity.
151
+     */
152
+    private function quantities(): array
153
+    {
154
+        $saved = $this->session->get($this->key(), []);
155
+
156
+        if (! is_array($saved)) {
157
+            return [];
158
+        }
159
+
160
+        $clean = [];
161
+
162
+        foreach ($saved as $productId => $quantity) {
163
+            if (is_int($productId) && is_int($quantity) && $quantity > 0) {
164
+                $clean[$productId] = $quantity;
165
+            }
166
+        }
167
+
168
+        return $clean;
169
+    }
170
+
171
+    /**
172
+     * @param  array<int, int>  $quantities
173
+     */
174
+    private function save(array $quantities): void
175
+    {
176
+        $this->session->put($this->key(), $quantities);
177
+    }
178
+
179
+    private function key(): string
180
+    {
181
+        return 'cart.'.$this->store->id;
182
+    }
183
+}

+ 144
- 0
app/Commerce/Checkout.php Vedi File

@@ -0,0 +1,144 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Commerce\Payments\PaymentStatus;
6
+use App\Enums\OrderStatus;
7
+use App\Mail\OrderConfirmation;
8
+use App\Models\Order;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use Illuminate\Support\Facades\DB;
12
+use Illuminate\Support\Facades\Mail;
13
+use Illuminate\Support\Str;
14
+use Illuminate\Validation\ValidationException;
15
+
16
+/**
17
+ * Turns a cart into an order, and an order into a paid order.
18
+ */
19
+class Checkout
20
+{
21
+    /** Stripe does not accept payments below RM 2.00. */
22
+    public const int MINIMUM_TOTAL = 200;
23
+
24
+    /** The first order number of every store. */
25
+    private const int FIRST_NUMBER = 1001;
26
+
27
+    /**
28
+     * Save the cart as an order that is waiting for payment.
29
+     * The order keeps its own copy of each product's name and price.
30
+     *
31
+     * @param  array{name: string, email: string, phone: string, line1: string, line2?: string|null, city: string, postcode: string, state: string}  $details
32
+     *
33
+     * @throws ValidationException When the cart is empty or the total is too small.
34
+     */
35
+    public function placeOrder(Store $store, Cart $cart, array $details): Order
36
+    {
37
+        $lines = $cart->lines();
38
+        $subtotal = (int) $lines->sum('line_total');
39
+
40
+        if ($lines->isEmpty()) {
41
+            throw ValidationException::withMessages(['cart' => __('Your cart is empty.')]);
42
+        }
43
+
44
+        if ($subtotal < self::MINIMUM_TOTAL) {
45
+            throw ValidationException::withMessages(['cart' => __('The order total must be at least RM 2.00.')]);
46
+        }
47
+
48
+        return DB::transaction(function () use ($store, $lines, $subtotal, $details): Order {
49
+            // Lock the store row so two orders placed at the same moment cannot get the same number.
50
+            Store::query()->whereKey($store->id)->lockForUpdate()->first();
51
+
52
+            $order = new Order;
53
+            $order->store_id = $store->id;
54
+            $order->public_id = (string) Str::ulid();
55
+            $order->number = max(self::FIRST_NUMBER, (int) $store->orders()->max('number') + 1);
56
+            $order->status = OrderStatus::Pending;
57
+            $order->customer_name = $details['name'];
58
+            $order->customer_email = $details['email'];
59
+            $order->customer_phone = $details['phone'];
60
+            $order->shipping_address = [
61
+                'line1' => $details['line1'],
62
+                'line2' => $details['line2'] ?? null,
63
+                'city' => $details['city'],
64
+                'postcode' => $details['postcode'],
65
+                'state' => $details['state'],
66
+                'country' => 'MY',
67
+            ];
68
+            $order->subtotal = $subtotal;
69
+            $order->shipping_total = 0;
70
+            $order->total = $subtotal;
71
+            $order->currency = 'MYR';
72
+            $order->save();
73
+
74
+            foreach ($lines as $line) {
75
+                $order->items()->create([
76
+                    'store_id' => $store->id,
77
+                    'product_id' => $line['product']->id,
78
+                    'name' => $line['product']->name,
79
+                    'unit_price' => $line['product']->price,
80
+                    'quantity' => $line['quantity'],
81
+                    'line_total' => $line['line_total'],
82
+                ]);
83
+            }
84
+
85
+            return $order->load('items');
86
+        });
87
+    }
88
+
89
+    /**
90
+     * Record that an order was paid: mark it, lower the stock, and email the shopper.
91
+     *
92
+     * Safe to call more than once for the same order (the return page and the webhook may both call it).
93
+     * Only the first call does anything. Returns true when this call marked the order paid.
94
+     */
95
+    public function markPaid(Order $order, PaymentStatus $payment): bool
96
+    {
97
+        if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
98
+            return false;
99
+        }
100
+
101
+        // The provider must have collected the full order total.
102
+        if ($payment->amount !== null && $payment->amount !== $order->total) {
103
+            report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
104
+
105
+            return false;
106
+        }
107
+
108
+        $marked = DB::transaction(function () use ($order, $payment): bool {
109
+            $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
110
+
111
+            if ($locked->isPaid()) {
112
+                return false;
113
+            }
114
+
115
+            $locked->status = OrderStatus::Paid;
116
+            $locked->payment_reference = $payment->reference;
117
+            $locked->paid_at = now();
118
+            $locked->save();
119
+
120
+            foreach ($locked->items as $item) {
121
+                // The product may have been deleted since the order was placed.
122
+                $product = $item->product_id !== null
123
+                    ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
124
+                    : null;
125
+
126
+                if ($product !== null) {
127
+                    // Never below zero, even if stock was changed by hand in the meantime.
128
+                    $product->stock = max(0, $product->stock - $item->quantity);
129
+                    $product->save();
130
+                }
131
+            }
132
+
133
+            return true;
134
+        });
135
+
136
+        $order->refresh();
137
+
138
+        if ($marked) {
139
+            Mail::to($order->customer_email)->send(new OrderConfirmation($order));
140
+        }
141
+
142
+        return $marked;
143
+    }
144
+}

+ 16
- 0
app/Commerce/MalaysianStates.php Vedi File

@@ -0,0 +1,16 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+final class MalaysianStates
6
+{
7
+    /**
8
+     * The states and federal territories a Malaysian address can be in.
9
+     *
10
+     * @var list<string>
11
+     */
12
+    public const array ALL = [
13
+        'Johor', 'Kedah', 'Kelantan', 'Kuala Lumpur', 'Labuan', 'Melaka', 'Negeri Sembilan', 'Pahang',
14
+        'Perak', 'Perlis', 'Pulau Pinang', 'Putrajaya', 'Sabah', 'Sarawak', 'Selangor', 'Terengganu',
15
+    ];
16
+}

+ 16
- 0
app/Commerce/Payments/CheckoutLink.php Vedi File

@@ -0,0 +1,16 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+/**
6
+ * A payment page created at the provider.
7
+ */
8
+final readonly class CheckoutLink
9
+{
10
+    public function __construct(
11
+        /** The provider's id for the payment page. */
12
+        public string $id,
13
+        /** Where to send the shopper to pay. */
14
+        public string $url,
15
+    ) {}
16
+}

+ 10
- 0
app/Commerce/Payments/PaymentException.php Vedi File

@@ -0,0 +1,10 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use RuntimeException;
6
+
7
+/**
8
+ * Anything that goes wrong while talking to the payment provider.
9
+ */
10
+final class PaymentException extends RuntimeException {}

+ 37
- 0
app/Commerce/Payments/PaymentGateway.php Vedi File

@@ -0,0 +1,37 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Models\Order;
6
+
7
+/**
8
+ * The one interface the app uses to take payments.
9
+ * Stripe is the first provider. Another provider only needs a class that implements this.
10
+ */
11
+interface PaymentGateway
12
+{
13
+    /** The name saved on the order, such as "stripe". */
14
+    public function name(): string;
15
+
16
+    /**
17
+     * Create a payment page for the order and say where to send the shopper.
18
+     *
19
+     * @throws PaymentException
20
+     */
21
+    public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink;
22
+
23
+    /**
24
+     * Ask the provider about a payment page we created earlier.
25
+     *
26
+     * @throws PaymentException
27
+     */
28
+    public function checkPayment(string $checkoutId): PaymentStatus;
29
+
30
+    /**
31
+     * Read a message the provider sent to our webhook address.
32
+     * Returns null when the message is about something we do not handle.
33
+     *
34
+     * @throws PaymentException When the message is not genuine.
35
+     */
36
+    public function readWebhook(string $payload, string $signature): ?PaymentStatus;
37
+}

+ 18
- 0
app/Commerce/Payments/PaymentStatus.php Vedi File

@@ -0,0 +1,18 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+/**
6
+ * What the provider says about one payment page.
7
+ */
8
+final readonly class PaymentStatus
9
+{
10
+    public function __construct(
11
+        public string $checkoutId,
12
+        public bool $paid,
13
+        /** The provider's id for the payment itself. */
14
+        public ?string $reference = null,
15
+        /** The amount the provider collected, in sen. */
16
+        public ?int $amount = null,
17
+    ) {}
18
+}

+ 112
- 0
app/Commerce/Payments/StripeGateway.php Vedi File

@@ -0,0 +1,112 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Models\Order;
6
+use App\Models\OrderItem;
7
+use Stripe\Checkout\Session;
8
+use Stripe\Exception\ApiErrorException;
9
+use Stripe\Exception\SignatureVerificationException;
10
+use Stripe\StripeClient;
11
+use Stripe\Webhook;
12
+use UnexpectedValueException;
13
+
14
+/**
15
+ * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
16
+ *
17
+ * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
18
+ * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
19
+ */
20
+final class StripeGateway implements PaymentGateway
21
+{
22
+    public function name(): string
23
+    {
24
+        return 'stripe';
25
+    }
26
+
27
+    public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
28
+    {
29
+        try {
30
+            $session = $this->client()->checkout->sessions->create([
31
+                'mode' => 'payment',
32
+                'customer_email' => $order->customer_email,
33
+                'client_reference_id' => (string) $order->id,
34
+                'metadata' => ['order_id' => (string) $order->id, 'store_id' => (string) $order->store_id],
35
+                'line_items' => $order->items->map(fn (OrderItem $item) => [
36
+                    'quantity' => $item->quantity,
37
+                    'price_data' => [
38
+                        'currency' => strtolower($order->currency),
39
+                        'unit_amount' => $item->unit_price,
40
+                        'product_data' => ['name' => $item->name],
41
+                    ],
42
+                ])->values()->all(),
43
+                // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
44
+                'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
45
+                'cancel_url' => $cancelUrl,
46
+            ]);
47
+        } catch (ApiErrorException $e) {
48
+            throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
49
+        }
50
+
51
+        if (! is_string($session->url)) {
52
+            throw new PaymentException('Stripe did not return a payment page address.');
53
+        }
54
+
55
+        return new CheckoutLink($session->id, $session->url);
56
+    }
57
+
58
+    public function checkPayment(string $checkoutId): PaymentStatus
59
+    {
60
+        try {
61
+            return $this->status($this->client()->checkout->sessions->retrieve($checkoutId));
62
+        } catch (ApiErrorException $e) {
63
+            throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
64
+        }
65
+    }
66
+
67
+    public function readWebhook(string $payload, string $signature): ?PaymentStatus
68
+    {
69
+        $secret = (string) config('services.stripe.webhook_secret');
70
+
71
+        if ($secret === '') {
72
+            throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
73
+        }
74
+
75
+        try {
76
+            $event = Webhook::constructEvent($payload, $signature, $secret);
77
+        } catch (SignatureVerificationException|UnexpectedValueException $e) {
78
+            throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
79
+        }
80
+
81
+        $session = $event->data->object ?? null;
82
+
83
+        // "async_payment_succeeded" covers methods such as FPX that confirm a little later.
84
+        if (! in_array($event->type, ['checkout.session.completed', 'checkout.session.async_payment_succeeded'], true)
85
+            || ! $session instanceof Session) {
86
+            return null;
87
+        }
88
+
89
+        return $this->status($session);
90
+    }
91
+
92
+    private function status(Session $session): PaymentStatus
93
+    {
94
+        return new PaymentStatus(
95
+            checkoutId: $session->id,
96
+            paid: $session->payment_status === 'paid',
97
+            reference: is_string($session->payment_intent) ? $session->payment_intent : null,
98
+            amount: $session->amount_total,
99
+        );
100
+    }
101
+
102
+    private function client(): StripeClient
103
+    {
104
+        $secret = (string) config('services.stripe.secret');
105
+
106
+        if ($secret === '') {
107
+            throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
108
+        }
109
+
110
+        return new StripeClient($secret);
111
+    }
112
+}

+ 19
- 0
app/Enums/OrderStatus.php Vedi File

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+namespace App\Enums;
4
+
5
+enum OrderStatus: string
6
+{
7
+    /** The shopper started checkout but has not paid (yet). */
8
+    case Pending = 'pending';
9
+
10
+    case Paid = 'paid';
11
+
12
+    public function label(): string
13
+    {
14
+        return match ($this) {
15
+            self::Pending => 'Awaiting payment',
16
+            self::Paid => 'Paid',
17
+        };
18
+    }
19
+}

+ 81
- 0
app/Http/Controllers/CartController.php Vedi File

@@ -0,0 +1,81 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Cart;
6
+use App\Http\Controllers\Concerns\RendersStorefront;
7
+use App\Models\Product;
8
+use App\Models\Store;
9
+use Illuminate\Http\RedirectResponse;
10
+use Illuminate\Http\Request;
11
+use Illuminate\Validation\ValidationException;
12
+use Inertia\Response;
13
+
14
+/**
15
+ * The shopper's cart for one store.
16
+ */
17
+class CartController extends Controller
18
+{
19
+    use RendersStorefront;
20
+
21
+    public function show(Request $request, string $slug): Response
22
+    {
23
+        return $this->renderStorefront($request, $this->ownedStore($request, $slug), ['type' => 'cart']);
24
+    }
25
+
26
+    /**
27
+     * Add a product to the cart.
28
+     */
29
+    public function add(Request $request, string $slug): RedirectResponse
30
+    {
31
+        $store = $this->ownedStore($request, $slug);
32
+
33
+        $validated = $request->validate([
34
+            'product_id' => ['required', 'integer'],
35
+            'quantity' => ['required', 'integer', 'min:1', 'max:'.Cart::MAX_QUANTITY],
36
+        ]);
37
+
38
+        $product = $this->buyableProduct($store, $validated['product_id']);
39
+
40
+        if ($product->stock < 1) {
41
+            throw ValidationException::withMessages(['quantity' => __('This product is sold out.')]);
42
+        }
43
+
44
+        $this->cart($request, $store)->add($product, $validated['quantity']);
45
+
46
+        return back();
47
+    }
48
+
49
+    /**
50
+     * Change how many of a product are in the cart. Zero removes it.
51
+     */
52
+    public function update(Request $request, string $slug, int $product): RedirectResponse
53
+    {
54
+        $store = $this->ownedStore($request, $slug);
55
+
56
+        $validated = $request->validate([
57
+            'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
58
+        ]);
59
+
60
+        $this->cart($request, $store)->set($this->buyableProduct($store, $product), $validated['quantity']);
61
+
62
+        return back();
63
+    }
64
+
65
+    public function remove(Request $request, string $slug, int $product): RedirectResponse
66
+    {
67
+        $store = $this->ownedStore($request, $slug);
68
+
69
+        $this->cart($request, $store)->remove($product);
70
+
71
+        return back();
72
+    }
73
+
74
+    /**
75
+     * A product of this store that shoppers may buy. Anything else gives "not found".
76
+     */
77
+    private function buyableProduct(Store $store, int $id): Product
78
+    {
79
+        return $store->products()->active()->whereKey($id)->firstOrFail();
80
+    }
81
+}

+ 117
- 0
app/Http/Controllers/CheckoutController.php Vedi File

@@ -0,0 +1,117 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Checkout;
6
+use App\Commerce\MalaysianStates;
7
+use App\Commerce\Payments\PaymentException;
8
+use App\Commerce\Payments\PaymentGateway;
9
+use App\Http\Controllers\Concerns\RendersStorefront;
10
+use App\Models\Order;
11
+use Illuminate\Http\RedirectResponse;
12
+use Illuminate\Http\Request;
13
+use Illuminate\Validation\Rule;
14
+use Illuminate\Validation\ValidationException;
15
+use Inertia\Inertia;
16
+use Inertia\Response;
17
+use Symfony\Component\HttpFoundation\Response as HttpResponse;
18
+
19
+/**
20
+ * Checkout: the shopper's details, the trip to the payment page, and the page they come back to.
21
+ */
22
+class CheckoutController extends Controller
23
+{
24
+    use RendersStorefront;
25
+
26
+    /**
27
+     * The form for the shopper's contact details and delivery address.
28
+     */
29
+    public function show(Request $request, string $slug): Response|RedirectResponse
30
+    {
31
+        $store = $this->ownedStore($request, $slug);
32
+
33
+        if ($this->cart($request, $store)->lines()->isEmpty()) {
34
+            return to_route('stores.preview.cart', $store->slug);
35
+        }
36
+
37
+        return $this->renderStorefront($request, $store, [
38
+            'type' => 'checkout',
39
+            'states' => MalaysianStates::ALL,
40
+        ]);
41
+    }
42
+
43
+    /**
44
+     * Save the order, then send the shopper to the payment page.
45
+     */
46
+    public function store(Request $request, Checkout $checkout, PaymentGateway $gateway, string $slug): HttpResponse
47
+    {
48
+        $store = $this->ownedStore($request, $slug);
49
+
50
+        $details = $request->validate([
51
+            'name' => ['required', 'string', 'min:2', 'max:120'],
52
+            'email' => ['required', 'email', 'max:160'],
53
+            'phone' => ['required', 'string', 'regex:/^[0-9+\-\s]{7,20}$/'],
54
+            'line1' => ['required', 'string', 'min:3', 'max:200'],
55
+            'line2' => ['nullable', 'string', 'max:200'],
56
+            'city' => ['required', 'string', 'min:2', 'max:100'],
57
+            'postcode' => ['required', 'string', 'regex:/^[0-9]{5}$/'],
58
+            'state' => ['required', Rule::in(MalaysianStates::ALL)],
59
+        ], [
60
+            'phone.regex' => __('Please enter a valid phone number.'),
61
+            'postcode.regex' => __('The postcode must be 5 digits.'),
62
+        ]);
63
+
64
+        $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
65
+
66
+        try {
67
+            $link = $gateway->startCheckout(
68
+                $order,
69
+                successUrl: route('stores.preview.order', [$store->slug, $order->public_id]),
70
+                cancelUrl: route('stores.preview.cart', $store->slug),
71
+            );
72
+        } catch (PaymentException $e) {
73
+            report($e);
74
+            $order->delete();
75
+
76
+            throw ValidationException::withMessages([
77
+                'cart' => __('We could not start the payment. Please try again in a moment.'),
78
+            ]);
79
+        }
80
+
81
+        $order->payment_provider = $gateway->name();
82
+        $order->payment_checkout_id = $link->id;
83
+        $order->save();
84
+
85
+        // The payment page is on another website, so this is a full browser redirect.
86
+        return Inertia::location($link->url);
87
+    }
88
+
89
+    /**
90
+     * Where the shopper lands after paying. The long random id in the address is what protects the page.
91
+     */
92
+    public function order(Request $request, Checkout $checkout, PaymentGateway $gateway, string $slug, string $publicId): Response
93
+    {
94
+        $store = $this->ownedStore($request, $slug);
95
+
96
+        /** @var Order $order */
97
+        $order = $store->orders()->with('items')->where('public_id', $publicId)->firstOrFail();
98
+
99
+        // Ask the payment provider directly. Nothing in the web address is trusted.
100
+        if (! $order->isPaid() && $order->payment_checkout_id !== null) {
101
+            try {
102
+                $checkout->markPaid($order, $gateway->checkPayment($order->payment_checkout_id));
103
+            } catch (PaymentException $e) {
104
+                report($e);
105
+            }
106
+        }
107
+
108
+        if ($order->isPaid()) {
109
+            $this->cart($request, $store)->clear();
110
+        }
111
+
112
+        return $this->renderStorefront($request, $store, [
113
+            'type' => 'order',
114
+            'order' => $order->toDisplay(),
115
+        ]);
116
+    }
117
+}

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

@@ -0,0 +1,56 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Concerns;
4
+
5
+use App\Commerce\Cart;
6
+use App\Models\Product;
7
+use App\Models\Store;
8
+use App\StorePlan\PlanSchema;
9
+use Illuminate\Http\Request;
10
+use Inertia\Inertia;
11
+use Inertia\Response;
12
+
13
+/**
14
+ * Shared by the controllers that show storefront pages.
15
+ * For now the storefront is a preview that only the store's owner can open. Step 5 makes it public.
16
+ */
17
+trait RendersStorefront
18
+{
19
+    private function ownedStore(Request $request, string $slug): Store
20
+    {
21
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
22
+    }
23
+
24
+    private function cart(Request $request, Store $store): Cart
25
+    {
26
+        return new Cart($request->session(), $store);
27
+    }
28
+
29
+    /**
30
+     * Every storefront page gets the same basics: the plan, the fonts, the product list and the cart.
31
+     *
32
+     * @param  array<string, mixed>  $view  Which page to show.
33
+     */
34
+    private function renderStorefront(Request $request, Store $store, array $view): Response
35
+    {
36
+        abort_if($store->plan === null, 404);
37
+
38
+        return Inertia::render('stores/preview', [
39
+            'storeName' => $store->name,
40
+            'language' => $store->language->value,
41
+            'plan' => $store->plan,
42
+            'fonts' => PlanSchema::FONTS,
43
+            // Links inside the storefront are built on top of this address.
44
+            'baseUrl' => route('stores.preview', $store->slug, false),
45
+            'view' => $view,
46
+            'products' => $store->products()
47
+                ->active()
48
+                ->with('images')
49
+                ->latest('id')
50
+                ->limit(60)
51
+                ->get()
52
+                ->map(fn (Product $product) => $product->toStorefront()),
53
+            'cart' => $this->cart($request, $store)->toStorefront(),
54
+        ]);
55
+    }
56
+}

+ 45
- 0
app/Http/Controllers/OrderController.php Vedi File

@@ -0,0 +1,45 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Models\Order;
6
+use App\Models\Store;
7
+use Illuminate\Http\Request;
8
+use Inertia\Inertia;
9
+use Inertia\Response;
10
+
11
+/**
12
+ * The merchant's view of a store's orders.
13
+ */
14
+class OrderController extends Controller
15
+{
16
+    public function index(Request $request, string $slug): Response
17
+    {
18
+        $store = $this->ownedStore($request, $slug);
19
+
20
+        return Inertia::render('stores/orders/index', [
21
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
22
+            'orders' => $store->orders()
23
+                ->with('items')
24
+                ->latest('id')
25
+                ->limit(200)
26
+                ->get()
27
+                ->map(fn (Order $order) => $order->toDisplay()),
28
+        ]);
29
+    }
30
+
31
+    public function show(Request $request, string $slug, int $order): Response
32
+    {
33
+        $store = $this->ownedStore($request, $slug);
34
+
35
+        return Inertia::render('stores/orders/show', [
36
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
37
+            'order' => $store->orders()->with('items')->whereKey($order)->firstOrFail()->toDisplay(),
38
+        ]);
39
+    }
40
+
41
+    private function ownedStore(Request $request, string $slug): Store
42
+    {
43
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
44
+    }
45
+}

+ 12
- 38
app/Http/Controllers/StoreDesignController.php Vedi File

@@ -2,21 +2,27 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
-use App\Models\Product;
6
-use App\Models\Store;
5
+use App\Http\Controllers\Concerns\RendersStorefront;
7 6
 use App\StorePlan\PlanSchema;
8 7
 use Illuminate\Http\Request;
9
-use Inertia\Inertia;
10 8
 use Inertia\Response;
11 9
 
10
+/**
11
+ * The storefront pages: home, shop and product.
12
+ */
12 13
 class StoreDesignController extends Controller
13 14
 {
15
+    use RendersStorefront;
16
+
14 17
     /**
15 18
      * The home page of the storefront, drawn from the store's saved plan.
16 19
      */
17 20
     public function preview(Request $request, string $slug): Response
18 21
     {
19
-        return $this->render($this->ownedStore($request, $slug), ['type' => 'page', 'pageId' => PlanSchema::HOME_PAGE]);
22
+        return $this->renderStorefront($request, $this->ownedStore($request, $slug), [
23
+            'type' => 'page',
24
+            'pageId' => PlanSchema::HOME_PAGE,
25
+        ]);
20 26
     }
21 27
 
22 28
     /**
@@ -24,7 +30,7 @@ class StoreDesignController extends Controller
24 30
      */
25 31
     public function shop(Request $request, string $slug): Response
26 32
     {
27
-        return $this->render($this->ownedStore($request, $slug), ['type' => 'shop']);
33
+        return $this->renderStorefront($request, $this->ownedStore($request, $slug), ['type' => 'shop']);
28 34
     }
29 35
 
30 36
     /**
@@ -36,38 +42,6 @@ class StoreDesignController extends Controller
36 42
 
37 43
         $product = $store->products()->active()->with('images')->where('slug', $productSlug)->firstOrFail();
38 44
 
39
-        return $this->render($store, ['type' => 'product', 'product' => $product->toStorefront()]);
40
-    }
41
-
42
-    /**
43
-     * Every storefront page gets the same basics: the plan, the fonts and the product list.
44
-     *
45
-     * @param  array<string, mixed>  $view  Which page to show.
46
-     */
47
-    private function render(Store $store, array $view): Response
48
-    {
49
-        abort_if($store->plan === null, 404);
50
-
51
-        return Inertia::render('stores/preview', [
52
-            'storeName' => $store->name,
53
-            'language' => $store->language->value,
54
-            'plan' => $store->plan,
55
-            'fonts' => PlanSchema::FONTS,
56
-            // Links inside the storefront are built on top of this address.
57
-            'baseUrl' => route('stores.preview', $store->slug, false),
58
-            'view' => $view,
59
-            'products' => $store->products()
60
-                ->active()
61
-                ->with('images')
62
-                ->latest('id')
63
-                ->limit(60)
64
-                ->get()
65
-                ->map(fn (Product $product) => $product->toStorefront()),
66
-        ]);
67
-    }
68
-
69
-    private function ownedStore(Request $request, string $slug): Store
70
-    {
71
-        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
45
+        return $this->renderStorefront($request, $store, ['type' => 'product', 'product' => $product->toStorefront()]);
72 46
     }
73 47
 }

+ 38
- 0
app/Http/Controllers/StripeWebhookController.php Vedi File

@@ -0,0 +1,38 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Checkout;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Commerce\Payments\PaymentGateway;
8
+use App\Models\Order;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Http\Response;
11
+
12
+/**
13
+ * Stripe calls this address to tell us about payments.
14
+ *
15
+ * It is the safety net for shoppers who pay but close the browser before coming back to the store.
16
+ * Every message is checked with the webhook signing secret before anything is done.
17
+ */
18
+class StripeWebhookController extends Controller
19
+{
20
+    public function __invoke(Request $request, PaymentGateway $gateway, Checkout $checkout): Response
21
+    {
22
+        try {
23
+            $payment = $gateway->readWebhook($request->getContent(), (string) $request->header('Stripe-Signature'));
24
+        } catch (PaymentException) {
25
+            return response('Invalid webhook.', 400);
26
+        }
27
+
28
+        if ($payment !== null) {
29
+            $order = Order::query()->where('payment_checkout_id', $payment->checkoutId)->first();
30
+
31
+            if ($order !== null) {
32
+                $checkout->markPaid($order, $payment);
33
+            }
34
+        }
35
+
36
+        return response('OK');
37
+    }
38
+}

+ 44
- 0
app/Mail/OrderConfirmation.php Vedi File

@@ -0,0 +1,44 @@
1
+<?php
2
+
3
+namespace App\Mail;
4
+
5
+use App\Models\Order;
6
+use Illuminate\Bus\Queueable;
7
+use Illuminate\Mail\Mailable;
8
+use Illuminate\Mail\Mailables\Content;
9
+use Illuminate\Mail\Mailables\Envelope;
10
+use Illuminate\Queue\SerializesModels;
11
+
12
+/**
13
+ * Sent to the shopper once their order is paid. Written in the store's language.
14
+ */
15
+class OrderConfirmation extends Mailable
16
+{
17
+    use Queueable, SerializesModels;
18
+
19
+    public function __construct(public Order $order) {}
20
+
21
+    public function envelope(): Envelope
22
+    {
23
+        $store = $this->order->store;
24
+
25
+        return new Envelope(
26
+            subject: $store->language->value === 'ms'
27
+                ? "Pesanan #{$this->order->number} disahkan - {$store->name}"
28
+                : "Order #{$this->order->number} confirmed - {$store->name}",
29
+        );
30
+    }
31
+
32
+    public function content(): Content
33
+    {
34
+        return new Content(
35
+            markdown: 'mail.orders.confirmation',
36
+            with: [
37
+                'order' => $this->order->loadMissing('items'),
38
+                'store' => $this->order->store,
39
+                'malay' => $this->order->store->language->value === 'ms',
40
+                'money' => fn (int $sen): string => 'RM '.number_format($sen / 100, 2),
41
+            ],
42
+        );
43
+    }
44
+}

+ 111
- 0
app/Models/Order.php Vedi File

@@ -0,0 +1,111 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use App\Enums\OrderStatus;
6
+use Carbon\CarbonInterface;
7
+use Database\Factories\OrderFactory;
8
+use Illuminate\Database\Eloquent\Collection;
9
+use Illuminate\Database\Eloquent\Factories\HasFactory;
10
+use Illuminate\Database\Eloquent\Model;
11
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
12
+use Illuminate\Database\Eloquent\Relations\HasMany;
13
+
14
+/**
15
+ * One purchase from a store. Money is saved in sen (1 ringgit = 100 sen).
16
+ *
17
+ * The items keep their own copy of each product's name and price, so an order
18
+ * never changes when the merchant later edits or deletes a product.
19
+ *
20
+ * @property int $id
21
+ * @property int $store_id
22
+ * @property string $public_id
23
+ * @property int $number
24
+ * @property OrderStatus $status
25
+ * @property string $customer_name
26
+ * @property string $customer_email
27
+ * @property string $customer_phone
28
+ * @property array{line1: string, line2: string|null, city: string, postcode: string, state: string, country: string} $shipping_address
29
+ * @property int $subtotal
30
+ * @property int $shipping_total
31
+ * @property int $total
32
+ * @property string $currency
33
+ * @property string|null $payment_provider
34
+ * @property string|null $payment_checkout_id
35
+ * @property string|null $payment_reference
36
+ * @property CarbonInterface|null $paid_at
37
+ * @property CarbonInterface|null $created_at
38
+ * @property CarbonInterface|null $updated_at
39
+ * @property-read Store $store
40
+ * @property-read Collection<int, OrderItem> $items
41
+ */
42
+class Order extends Model
43
+{
44
+    /** @use HasFactory<OrderFactory> */
45
+    use HasFactory;
46
+
47
+    /**
48
+     * @return BelongsTo<Store, $this>
49
+     */
50
+    public function store(): BelongsTo
51
+    {
52
+        return $this->belongsTo(Store::class);
53
+    }
54
+
55
+    /**
56
+     * @return HasMany<OrderItem, $this>
57
+     */
58
+    public function items(): HasMany
59
+    {
60
+        return $this->hasMany(OrderItem::class);
61
+    }
62
+
63
+    public function isPaid(): bool
64
+    {
65
+        return $this->status === OrderStatus::Paid;
66
+    }
67
+
68
+    /**
69
+     * The order as shown to people. Money is in ringgit here.
70
+     *
71
+     * @return array<string, mixed>
72
+     */
73
+    public function toDisplay(): array
74
+    {
75
+        return [
76
+            'id' => $this->id,
77
+            'public_id' => $this->public_id,
78
+            'number' => $this->number,
79
+            'status' => $this->status->value,
80
+            'status_label' => $this->status->label(),
81
+            'customer_name' => $this->customer_name,
82
+            'customer_email' => $this->customer_email,
83
+            'customer_phone' => $this->customer_phone,
84
+            'shipping_address' => $this->shipping_address,
85
+            'subtotal' => $this->subtotal / 100,
86
+            'shipping_total' => $this->shipping_total / 100,
87
+            'total' => $this->total / 100,
88
+            'paid_at' => $this->paid_at?->toIso8601String(),
89
+            'created_at' => $this->created_at?->toIso8601String(),
90
+            'items' => $this->items->map(fn (OrderItem $item) => [
91
+                'id' => $item->id,
92
+                'name' => $item->name,
93
+                'unit_price' => $item->unit_price / 100,
94
+                'quantity' => $item->quantity,
95
+                'line_total' => $item->line_total / 100,
96
+            ])->all(),
97
+        ];
98
+    }
99
+
100
+    /**
101
+     * @return array<string, string>
102
+     */
103
+    protected function casts(): array
104
+    {
105
+        return [
106
+            'status' => OrderStatus::class,
107
+            'shipping_address' => 'array',
108
+            'paid_at' => 'datetime',
109
+        ];
110
+    }
111
+}

+ 31
- 0
app/Models/OrderItem.php Vedi File

@@ -0,0 +1,31 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Attributes\Fillable;
6
+use Illuminate\Database\Eloquent\Model;
7
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
+
9
+/**
10
+ * One line of an order: a product, its price at the time, and how many.
11
+ *
12
+ * @property int $id
13
+ * @property int $store_id
14
+ * @property int $order_id
15
+ * @property int|null $product_id
16
+ * @property string $name
17
+ * @property int $unit_price
18
+ * @property int $quantity
19
+ * @property int $line_total
20
+ */
21
+#[Fillable(['store_id', 'product_id', 'name', 'unit_price', 'quantity', 'line_total'])]
22
+class OrderItem extends Model
23
+{
24
+    /**
25
+     * @return BelongsTo<Order, $this>
26
+     */
27
+    public function order(): BelongsTo
28
+    {
29
+        return $this->belongsTo(Order::class);
30
+    }
31
+}

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

@@ -108,6 +108,7 @@ class Product extends Model
108 108
             'price' => $this->price / 100,
109 109
             'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
110 110
             'in_stock' => $this->stock > 0,
111
+            'stock_left' => $this->stock,
111 112
             'image' => $images[0] ?? null,
112 113
             'images' => $images,
113 114
         ];

+ 8
- 0
app/Models/Store.php Vedi File

@@ -98,6 +98,14 @@ class Store extends Model
98 98
         return $this->hasMany(Product::class);
99 99
     }
100 100
 
101
+    /**
102
+     * @return HasMany<Order, $this>
103
+     */
104
+    public function orders(): HasMany
105
+    {
106
+        return $this->hasMany(Order::class);
107
+    }
108
+
101 109
     /**
102 110
      * The AI jobs run for this store, newest first.
103 111
      *

+ 4
- 1
app/Providers/AppServiceProvider.php Vedi File

@@ -2,6 +2,8 @@
2 2
 
3 3
 namespace App\Providers;
4 4
 
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Commerce\Payments\StripeGateway;
5 7
 use Carbon\CarbonImmutable;
6 8
 use Illuminate\Support\Facades\Date;
7 9
 use Illuminate\Support\Facades\DB;
@@ -15,7 +17,8 @@ class AppServiceProvider extends ServiceProvider
15 17
      */
16 18
     public function register(): void
17 19
     {
18
-        //
20
+        // Payments go through one interface, so the provider can be changed in one place.
21
+        $this->app->bind(PaymentGateway::class, StripeGateway::class);
19 22
     }
20 23
 
21 24
     /**

+ 3
- 0
bootstrap/app.php Vedi File

@@ -17,6 +17,9 @@ $app = Application::configure(basePath: dirname(__DIR__))
17 17
     ->withMiddleware(function (Middleware $middleware): void {
18 18
         $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
19 19
 
20
+        // Stripe cannot send our form-protection token. Its messages are checked by signature instead.
21
+        $middleware->validateCsrfTokens(except: ['stripe/webhook']);
22
+
20 23
         $middleware->web(append: [
21 24
             HandleAppearance::class,
22 25
             HandleInertiaRequests::class,

+ 2
- 1
composer.json Vedi File

@@ -16,7 +16,8 @@
16 16
         "laravel/fortify": "^1.37.2",
17 17
         "laravel/framework": "^13.17",
18 18
         "laravel/tinker": "^3.0",
19
-        "laravel/wayfinder": "^0.1.14"
19
+        "laravel/wayfinder": "^0.1.14",
20
+        "stripe/stripe-php": "^23.0"
20 21
     },
21 22
     "require-dev": {
22 23
         "fakerphp/faker": "^1.24",

+ 63
- 1
composer.lock Vedi File

@@ -4,7 +4,7 @@
4 4
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 5
         "This file is @generated automatically"
6 6
     ],
7
-    "content-hash": "7293711322836bd2596ffe6f015a4c9f",
7
+    "content-hash": "3a251c29daf7286529823a011af026e1",
8 8
     "packages": [
9 9
         {
10 10
             "name": "anthropic-ai/sdk",
@@ -4616,6 +4616,68 @@
4616 4616
             },
4617 4617
             "time": "2026-02-18T19:02:27+00:00"
4618 4618
         },
4619
+        {
4620
+            "name": "stripe/stripe-php",
4621
+            "version": "v23.0.0",
4622
+            "source": {
4623
+                "type": "git",
4624
+                "url": "https://github.com/stripe/stripe-php.git",
4625
+                "reference": "f29b7a44597531c304360c3d42959aaf52e33618"
4626
+            },
4627
+            "dist": {
4628
+                "type": "zip",
4629
+                "url": "https://api.github.com/repos/stripe/stripe-php/zipball/f29b7a44597531c304360c3d42959aaf52e33618",
4630
+                "reference": "f29b7a44597531c304360c3d42959aaf52e33618",
4631
+                "shasum": ""
4632
+            },
4633
+            "require": {
4634
+                "ext-curl": "*",
4635
+                "ext-json": "*",
4636
+                "ext-mbstring": "*",
4637
+                "php": ">=7.4.0"
4638
+            },
4639
+            "require-dev": {
4640
+                "friendsofphp/php-cs-fixer": "3.94.0",
4641
+                "phpstan/phpstan": "^1.2",
4642
+                "phpunit/phpunit": "^8.0 || ^9.0"
4643
+            },
4644
+            "type": "library",
4645
+            "extra": {
4646
+                "branch-alias": {
4647
+                    "dev-master": "2.0-dev"
4648
+                }
4649
+            },
4650
+            "autoload": {
4651
+                "files": [
4652
+                    "lib/version_check.php"
4653
+                ],
4654
+                "psr-4": {
4655
+                    "Stripe\\": "lib/"
4656
+                }
4657
+            },
4658
+            "notification-url": "https://packagist.org/downloads/",
4659
+            "license": [
4660
+                "MIT"
4661
+            ],
4662
+            "authors": [
4663
+                {
4664
+                    "name": "Stripe and contributors",
4665
+                    "homepage": "https://github.com/stripe/stripe-php/contributors"
4666
+                }
4667
+            ],
4668
+            "description": "Stripe PHP Library",
4669
+            "homepage": "https://stripe.com/",
4670
+            "keywords": [
4671
+                "api",
4672
+                "payment processing",
4673
+                "stripe"
4674
+            ],
4675
+            "support": {
4676
+                "issues": "https://github.com/stripe/stripe-php/issues",
4677
+                "source": "https://github.com/stripe/stripe-php/tree/v23.0.0"
4678
+            },
4679
+            "time": "2026-11-11T19:52:56+00:00"
4680
+        },
4619 4681
         {
4620 4682
             "name": "symfony/clock",
4621 4683
             "version": "v8.1.9",

+ 9
- 0
config/services.php Vedi File

@@ -35,4 +35,13 @@ return [
35 35
         ],
36 36
     ],
37 37
 
38
+    'stripe' => [
39
+        // Publishable key (pk_...). Not needed by the server today; kept for later use in the browser.
40
+        'key' => env('STRIPE_KEY'),
41
+        // Secret key (sk_...). Use a test key (sk_test_...) for development.
42
+        'secret' => env('STRIPE_SECRET'),
43
+        // Signing secret for the webhook (whsec_...). Optional on a local machine.
44
+        'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
45
+    ],
46
+
38 47
 ];

+ 48
- 0
database/factories/OrderFactory.php Vedi File

@@ -0,0 +1,48 @@
1
+<?php
2
+
3
+namespace Database\Factories;
4
+
5
+use App\Enums\OrderStatus;
6
+use App\Models\Order;
7
+use App\Models\Store;
8
+use Illuminate\Database\Eloquent\Factories\Factory;
9
+use Illuminate\Support\Str;
10
+
11
+/**
12
+ * @extends Factory<Order>
13
+ */
14
+class OrderFactory extends Factory
15
+{
16
+    /**
17
+     * @return array<string, mixed>
18
+     */
19
+    public function definition(): array
20
+    {
21
+        return [
22
+            'store_id' => Store::factory(),
23
+            'public_id' => fn () => (string) Str::ulid(),
24
+            'number' => fake()->unique()->numberBetween(1001, 999999),
25
+            'status' => OrderStatus::Pending,
26
+            'customer_name' => 'Aminah binti Ali',
27
+            'customer_email' => 'aminah@example.com',
28
+            'customer_phone' => '0123456789',
29
+            'shipping_address' => [
30
+                'line1' => '12 Jalan Mawar',
31
+                'line2' => null,
32
+                'city' => 'Shah Alam',
33
+                'postcode' => '40000',
34
+                'state' => 'Selangor',
35
+                'country' => 'MY',
36
+            ],
37
+            'subtotal' => 2580,
38
+            'shipping_total' => 0,
39
+            'total' => 2580,
40
+            'currency' => 'MYR',
41
+        ];
42
+    }
43
+
44
+    public function paid(): static
45
+    {
46
+        return $this->state(['status' => OrderStatus::Paid, 'paid_at' => now(), 'payment_reference' => 'pi_test']);
47
+    }
48
+}

+ 62
- 0
database/migrations/2026_11_14_000006_create_orders_table.php Vedi File

@@ -0,0 +1,62 @@
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('orders', function (Blueprint $table) {
12
+            $table->id();
13
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
14
+            // A long random id used in web addresses, so order pages cannot be guessed.
15
+            $table->ulid('public_id')->unique();
16
+            // The short number the merchant and shopper see, counting up per store from 1001.
17
+            $table->unsignedInteger('number');
18
+            $table->string('status')->default('pending');
19
+
20
+            $table->string('customer_name');
21
+            $table->string('customer_email');
22
+            $table->string('customer_phone', 30);
23
+            $table->json('shipping_address');
24
+
25
+            // Money in sen (1 ringgit = 100 sen).
26
+            $table->unsignedInteger('subtotal');
27
+            $table->unsignedInteger('shipping_total')->default(0);
28
+            $table->unsignedInteger('total');
29
+            $table->string('currency', 3)->default('MYR');
30
+
31
+            $table->string('payment_provider')->nullable();
32
+            // The provider's id for the checkout page we sent the shopper to.
33
+            $table->string('payment_checkout_id')->nullable()->index();
34
+            // The provider's id for the payment itself, once paid.
35
+            $table->string('payment_reference')->nullable();
36
+            $table->timestamp('paid_at')->nullable();
37
+            $table->timestamps();
38
+
39
+            $table->unique(['store_id', 'number']);
40
+            $table->index(['store_id', 'status', 'created_at']);
41
+        });
42
+
43
+        Schema::create('order_items', function (Blueprint $table) {
44
+            $table->id();
45
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
46
+            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
47
+            // Kept even if the product is deleted later; the name and price below are the record.
48
+            $table->foreignId('product_id')->nullable()->constrained()->nullOnDelete();
49
+            $table->string('name');
50
+            $table->unsignedInteger('unit_price');
51
+            $table->unsignedInteger('quantity');
52
+            $table->unsignedInteger('line_total');
53
+            $table->timestamps();
54
+        });
55
+    }
56
+
57
+    public function down(): void
58
+    {
59
+        Schema::dropIfExists('order_items');
60
+        Schema::dropIfExists('orders');
61
+    }
62
+};

+ 7
- 1
resources/js/components/stores/store-nav.tsx Vedi File

@@ -1,9 +1,10 @@
1 1
 import { Link } from '@inertiajs/react';
2
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
2 3
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
3 4
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
4 5
 import { cn } from '@/lib/utils';
5 6
 
6
-type Tab = 'design' | 'products';
7
+type Tab = 'design' | 'products' | 'orders';
7 8
 
8 9
 /** The tabs at the top of every page of one store. */
9 10
 export default function StoreNav({
@@ -24,6 +25,11 @@ export default function StoreNav({
24 25
             label: 'Products',
25 26
             href: ProductController.index.url(slug),
26 27
         },
28
+        {
29
+            key: 'orders',
30
+            label: 'Orders',
31
+            href: OrderController.index.url(slug),
32
+        },
27 33
     ];
28 34
 
29 35
     return (

+ 18
- 0
resources/js/lib/money.ts Vedi File

@@ -0,0 +1,18 @@
1
+const ringgit = new Intl.NumberFormat('en-MY', {
2
+    style: 'currency',
3
+    currency: 'MYR',
4
+});
5
+
6
+const dateTime = new Intl.DateTimeFormat('en-MY', {
7
+    dateStyle: 'medium',
8
+    timeStyle: 'short',
9
+});
10
+
11
+/** 12.9 becomes "RM 12.90". */
12
+export function formatRinggit(amount: number): string {
13
+    return ringgit.format(amount);
14
+}
15
+
16
+export function formatDateTime(iso: string | null): string {
17
+    return iso ? dateTime.format(new Date(iso)) : '';
18
+}

+ 138
- 0
resources/js/pages/stores/orders/index.tsx Vedi File

@@ -0,0 +1,138 @@
1
+import { Head, Link } from '@inertiajs/react';
2
+import { ReceiptText } from 'lucide-react';
3
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
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 { formatDateTime, formatRinggit } from '@/lib/money';
8
+import { dashboard } from '@/routes';
9
+import type { Order, StoreSummary } from '@/types';
10
+
11
+export default function OrdersIndex({
12
+    store,
13
+    orders,
14
+}: {
15
+    store: StoreSummary;
16
+    orders: Order[];
17
+}) {
18
+    const paid = orders.filter((order) => order.status === 'paid');
19
+    const revenue = paid.reduce((sum, order) => sum + order.total, 0);
20
+
21
+    return (
22
+        <>
23
+            <Head title={`Orders - ${store.name}`} />
24
+
25
+            <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
26
+                <div>
27
+                    <h1 className="text-xl font-semibold">{store.name}</h1>
28
+                    <p className="text-sm text-muted-foreground">
29
+                        <Link
30
+                            href={StoreController.show.url(store.slug)}
31
+                            className="hover:underline"
32
+                        >
33
+                            Back to store
34
+                        </Link>
35
+                    </p>
36
+                </div>
37
+
38
+                <StoreNav slug={store.slug} current="orders" />
39
+
40
+                <div className="flex flex-wrap items-baseline justify-between gap-3">
41
+                    <h2 className="font-medium">
42
+                        Orders{' '}
43
+                        <span className="text-muted-foreground">
44
+                            ({orders.length})
45
+                        </span>
46
+                    </h2>
47
+                    {paid.length > 0 && (
48
+                        <p className="text-sm text-muted-foreground tabular-nums">
49
+                            {paid.length} paid · {formatRinggit(revenue)} in
50
+                            total
51
+                        </p>
52
+                    )}
53
+                </div>
54
+
55
+                {orders.length === 0 ? (
56
+                    <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed p-10 text-center">
57
+                        <ReceiptText className="size-6 text-muted-foreground" />
58
+                        <div>
59
+                            <p className="font-medium">No orders yet</p>
60
+                            <p className="mt-1 max-w-sm text-sm text-muted-foreground">
61
+                                When a shopper checks out, their order shows up
62
+                                here.
63
+                            </p>
64
+                        </div>
65
+                    </div>
66
+                ) : (
67
+                    <div className="overflow-x-auto rounded-xl border">
68
+                        <table className="w-full text-sm">
69
+                            <thead className="border-b bg-muted/40 text-left text-muted-foreground">
70
+                                <tr>
71
+                                    <th className="px-4 py-2.5 font-medium">
72
+                                        Order
73
+                                    </th>
74
+                                    <th className="px-4 py-2.5 font-medium">
75
+                                        Date
76
+                                    </th>
77
+                                    <th className="px-4 py-2.5 font-medium">
78
+                                        Customer
79
+                                    </th>
80
+                                    <th className="px-4 py-2.5 font-medium">
81
+                                        Status
82
+                                    </th>
83
+                                    <th className="px-4 py-2.5 text-right font-medium">
84
+                                        Total
85
+                                    </th>
86
+                                </tr>
87
+                            </thead>
88
+                            <tbody className="divide-y">
89
+                                {orders.map((order) => (
90
+                                    <tr key={order.id}>
91
+                                        <td className="px-4 py-3">
92
+                                            <Link
93
+                                                href={OrderController.show.url({
94
+                                                    slug: store.slug,
95
+                                                    order: order.id,
96
+                                                })}
97
+                                                className="font-medium underline-offset-2 hover:underline"
98
+                                            >
99
+                                                #{order.number}
100
+                                            </Link>
101
+                                        </td>
102
+                                        <td className="px-4 py-3 whitespace-nowrap text-muted-foreground">
103
+                                            {formatDateTime(order.created_at)}
104
+                                        </td>
105
+                                        <td className="px-4 py-3">
106
+                                            {order.customer_name}
107
+                                        </td>
108
+                                        <td className="px-4 py-3">
109
+                                            <Badge
110
+                                                variant={
111
+                                                    order.status === 'paid'
112
+                                                        ? 'default'
113
+                                                        : 'secondary'
114
+                                                }
115
+                                            >
116
+                                                {order.status_label}
117
+                                            </Badge>
118
+                                        </td>
119
+                                        <td className="px-4 py-3 text-right tabular-nums">
120
+                                            {formatRinggit(order.total)}
121
+                                        </td>
122
+                                    </tr>
123
+                                ))}
124
+                            </tbody>
125
+                        </table>
126
+                    </div>
127
+                )}
128
+            </div>
129
+        </>
130
+    );
131
+}
132
+
133
+OrdersIndex.layout = {
134
+    breadcrumbs: [
135
+        { title: 'Dashboard', href: dashboard() },
136
+        { title: 'Orders', href: '#' },
137
+    ],
138
+};

+ 132
- 0
resources/js/pages/stores/orders/show.tsx Vedi File

@@ -0,0 +1,132 @@
1
+import { Head, Link } from '@inertiajs/react';
2
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
3
+import { Badge } from '@/components/ui/badge';
4
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
5
+import { formatDateTime, formatRinggit } from '@/lib/money';
6
+import { dashboard } from '@/routes';
7
+import type { Order, StoreSummary } from '@/types';
8
+
9
+export default function ShowOrder({
10
+    store,
11
+    order,
12
+}: {
13
+    store: StoreSummary;
14
+    order: Order;
15
+}) {
16
+    const address = order.shipping_address;
17
+
18
+    return (
19
+        <>
20
+            <Head title={`Order #${order.number} - ${store.name}`} />
21
+
22
+            <div className="mx-auto w-full max-w-3xl space-y-6 p-4">
23
+                <div>
24
+                    <p className="text-sm text-muted-foreground">
25
+                        <Link
26
+                            href={OrderController.index.url(store.slug)}
27
+                            className="hover:underline"
28
+                        >
29
+                            Back to orders
30
+                        </Link>
31
+                    </p>
32
+                    <div className="mt-1 flex flex-wrap items-center gap-3">
33
+                        <h1 className="text-xl font-semibold">
34
+                            Order #{order.number}
35
+                        </h1>
36
+                        <Badge
37
+                            variant={
38
+                                order.status === 'paid'
39
+                                    ? 'default'
40
+                                    : 'secondary'
41
+                            }
42
+                        >
43
+                            {order.status_label}
44
+                        </Badge>
45
+                    </div>
46
+                    <p className="text-sm text-muted-foreground">
47
+                        Placed {formatDateTime(order.created_at)}
48
+                        {order.paid_at
49
+                            ? ` · Paid ${formatDateTime(order.paid_at)}`
50
+                            : ''}
51
+                    </p>
52
+                </div>
53
+
54
+                <Card>
55
+                    <CardHeader>
56
+                        <CardTitle>Items</CardTitle>
57
+                    </CardHeader>
58
+                    <CardContent>
59
+                        <ul className="divide-y text-sm">
60
+                            {order.items.map((item) => (
61
+                                <li
62
+                                    key={item.id}
63
+                                    className="flex justify-between gap-4 py-2.5"
64
+                                >
65
+                                    <span>
66
+                                        {item.name}{' '}
67
+                                        <span className="text-muted-foreground">
68
+                                            × {item.quantity} at{' '}
69
+                                            {formatRinggit(item.unit_price)}
70
+                                        </span>
71
+                                    </span>
72
+                                    <span className="tabular-nums">
73
+                                        {formatRinggit(item.line_total)}
74
+                                    </span>
75
+                                </li>
76
+                            ))}
77
+                        </ul>
78
+                        <div className="mt-3 flex justify-between gap-4 border-t pt-3 font-medium">
79
+                            <span>Total</span>
80
+                            <span className="tabular-nums">
81
+                                {formatRinggit(order.total)}
82
+                            </span>
83
+                        </div>
84
+                    </CardContent>
85
+                </Card>
86
+
87
+                <div className="grid gap-6 sm:grid-cols-2">
88
+                    <Card>
89
+                        <CardHeader>
90
+                            <CardTitle>Customer</CardTitle>
91
+                        </CardHeader>
92
+                        <CardContent className="space-y-1 text-sm">
93
+                            <p>{order.customer_name}</p>
94
+                            <p>
95
+                                <a
96
+                                    href={`mailto:${order.customer_email}`}
97
+                                    className="underline underline-offset-2"
98
+                                >
99
+                                    {order.customer_email}
100
+                                </a>
101
+                            </p>
102
+                            <p>{order.customer_phone}</p>
103
+                        </CardContent>
104
+                    </Card>
105
+
106
+                    <Card>
107
+                        <CardHeader>
108
+                            <CardTitle>Deliver to</CardTitle>
109
+                        </CardHeader>
110
+                        <CardContent>
111
+                            <address className="text-sm leading-relaxed not-italic">
112
+                                {address.line1}
113
+                                {address.line2 ? `, ${address.line2}` : ''}
114
+                                <br />
115
+                                {address.postcode} {address.city}
116
+                                <br />
117
+                                {address.state}
118
+                            </address>
119
+                        </CardContent>
120
+                    </Card>
121
+                </div>
122
+            </div>
123
+        </>
124
+    );
125
+}
126
+
127
+ShowOrder.layout = {
128
+    breadcrumbs: [
129
+        { title: 'Dashboard', href: dashboard() },
130
+        { title: 'Order', href: '#' },
131
+    ],
132
+};

+ 4
- 0
resources/js/pages/stores/preview.tsx Vedi File

@@ -3,6 +3,7 @@ import { StorefrontRenderer } from '@/storefront/renderer';
3 3
 import { fontStylesheetUrl } from '@/storefront/theme';
4 4
 import type {
5 5
     FontMap,
6
+    StoreCart,
6 7
     StorePlan,
7 8
     StoreProduct,
8 9
     StorefrontView,
@@ -16,6 +17,7 @@ export default function PreviewStore({
16 17
     baseUrl,
17 18
     view,
18 19
     products,
20
+    cart,
19 21
 }: {
20 22
     storeName: string;
21 23
     language: string;
@@ -24,6 +26,7 @@ export default function PreviewStore({
24 26
     baseUrl: string;
25 27
     view: StorefrontView;
26 28
     products: StoreProduct[];
29
+    cart: StoreCart;
27 30
 }) {
28 31
     const fontUrl = fontStylesheetUrl(plan.theme, fonts);
29 32
     const title = view.type === 'product' ? view.product.name : storeName;
@@ -41,6 +44,7 @@ export default function PreviewStore({
41 44
                 baseUrl={baseUrl}
42 45
                 language={language}
43 46
                 products={products}
47
+                cart={cart}
44 48
             />
45 49
         </>
46 50
     );

+ 3
- 1
resources/js/storefront/context.tsx Vedi File

@@ -1,5 +1,5 @@
1 1
 import { createContext, useContext } from 'react';
2
-import type { StoreProduct } from './types';
2
+import type { StoreCart, StoreProduct } from './types';
3 3
 
4 4
 export type Storefront = {
5 5
     /** Address of the store's home page. Every other storefront address is built on it. */
@@ -9,6 +9,7 @@ export type Storefront = {
9 9
     language: string;
10 10
     /** The merchant's real products that shoppers may see. */
11 11
     products: StoreProduct[];
12
+    cart: StoreCart;
12 13
 };
13 14
 
14 15
 const StorefrontContext = createContext<Storefront>({
@@ -16,6 +17,7 @@ const StorefrontContext = createContext<Storefront>({
16 17
     isHome: true,
17 18
     language: 'en',
18 19
     products: [],
20
+    cart: { count: 0, subtotal: 0, adjusted: false, lines: [] },
19 21
 });
20 22
 
21 23
 export const StorefrontProvider = StorefrontContext.Provider;

+ 155
- 0
resources/js/storefront/pages/cart.tsx Vedi File

@@ -0,0 +1,155 @@
1
+import { router } from '@inertiajs/react';
2
+import { useState } from 'react';
3
+import { useStorefront } from '../context';
4
+import { ProductImage } from '../product-card';
5
+import { storefrontText } from '../text';
6
+import { formatPrice } from '../theme';
7
+import type { CartLine } from '../types';
8
+import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
9
+
10
+/** The shopper's cart. Built by us, in the store's colours and fonts. */
11
+export function CartPage() {
12
+    const { cart, language, baseUrl } = useStorefront();
13
+    const t = storefrontText(language);
14
+    const [busy, setBusy] = useState(false);
15
+
16
+    function change(line: CartLine, quantity: number) {
17
+        const url = `${baseUrl}/cart/items/${line.product.id}`;
18
+        const options = {
19
+            preserveScroll: true,
20
+            onStart: () => setBusy(true),
21
+            onFinish: () => setBusy(false),
22
+        };
23
+
24
+        if (quantity < 1) {
25
+            router.delete(url, options);
26
+        } else {
27
+            router.patch(url, { quantity }, options);
28
+        }
29
+    }
30
+
31
+    return (
32
+        <main className="py-12 md:py-16">
33
+            <Container>
34
+                <h1 className="sf-heading text-4xl font-semibold sm:text-5xl">
35
+                    {t.yourCart}
36
+                </h1>
37
+
38
+                {cart.adjusted && (
39
+                    <p
40
+                        role="status"
41
+                        className="mt-6 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-4 text-sm"
42
+                    >
43
+                        {t.cartAdjusted}
44
+                    </p>
45
+                )}
46
+
47
+                {cart.lines.length === 0 ? (
48
+                    <div className="mt-8">
49
+                        <p className="text-(--sf-muted)">{t.cartEmpty}</p>
50
+                        <SfButton href="/shop" className="mt-6">
51
+                            {t.continueShopping}
52
+                        </SfButton>
53
+                    </div>
54
+                ) : (
55
+                    <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_340px] lg:gap-14">
56
+                        <ul className="divide-y divide-(--sf-border) border-y border-(--sf-border)">
57
+                            {cart.lines.map((line, index) => (
58
+                                <li
59
+                                    key={line.product.id}
60
+                                    className="flex gap-4 py-5"
61
+                                >
62
+                                    <SfLink
63
+                                        href={`/products/${line.product.slug}`}
64
+                                        className="shrink-0"
65
+                                    >
66
+                                        <ProductImage
67
+                                            src={line.product.image}
68
+                                            alt={line.product.name}
69
+                                            seed={index}
70
+                                            className="size-20 sm:size-24"
71
+                                        />
72
+                                    </SfLink>
73
+
74
+                                    <div className="flex min-w-0 flex-1 flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
75
+                                        <div className="min-w-0">
76
+                                            <SfLink
77
+                                                href={`/products/${line.product.slug}`}
78
+                                                className="font-medium hover:underline"
79
+                                            >
80
+                                                {line.product.name}
81
+                                            </SfLink>
82
+                                            <p className="mt-1 text-sm text-(--sf-muted) tabular-nums">
83
+                                                {formatPrice(
84
+                                                    line.product.price,
85
+                                                )}
86
+                                            </p>
87
+                                            {line.quantity >= line.max && (
88
+                                                <p className="mt-1 text-xs text-(--sf-muted)">
89
+                                                    {t.onlyLeft(line.max)}
90
+                                                </p>
91
+                                            )}
92
+                                        </div>
93
+
94
+                                        <div className="flex items-center gap-4 sm:flex-col sm:items-end sm:gap-2">
95
+                                            <QuantityStepper
96
+                                                value={line.quantity}
97
+                                                max={line.max}
98
+                                                disabled={busy}
99
+                                                onChange={(quantity) =>
100
+                                                    change(line, quantity)
101
+                                                }
102
+                                                decreaseLabel={`${t.decrease}: ${line.product.name}`}
103
+                                                increaseLabel={`${t.increase}: ${line.product.name}`}
104
+                                            />
105
+                                            <p className="font-medium tabular-nums">
106
+                                                {formatPrice(line.line_total)}
107
+                                            </p>
108
+                                            <button
109
+                                                type="button"
110
+                                                disabled={busy}
111
+                                                onClick={() => change(line, 0)}
112
+                                                aria-label={`${t.remove}: ${line.product.name}`}
113
+                                                className="text-sm text-(--sf-muted) underline underline-offset-2 hover:text-(--sf-fg) disabled:opacity-50"
114
+                                            >
115
+                                                {t.remove}
116
+                                            </button>
117
+                                        </div>
118
+                                    </div>
119
+                                </li>
120
+                            ))}
121
+                        </ul>
122
+
123
+                        <aside className="h-fit rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
124
+                            <div className="flex items-baseline justify-between gap-4">
125
+                                <span className="font-medium">
126
+                                    {t.subtotal}
127
+                                </span>
128
+                                <span className="text-xl font-semibold tabular-nums">
129
+                                    {formatPrice(cart.subtotal)}
130
+                                </span>
131
+                            </div>
132
+                            <p className="mt-2 text-sm text-(--sf-muted)">
133
+                                {t.shippingNote}
134
+                            </p>
135
+
136
+                            <SfButton
137
+                                href="/checkout"
138
+                                className="mt-6 w-full py-3"
139
+                            >
140
+                                {t.checkout}
141
+                            </SfButton>
142
+
143
+                            <SfLink
144
+                                href="/shop"
145
+                                className="mt-5 inline-block text-sm underline underline-offset-2 hover:text-(--sf-primary)"
146
+                            >
147
+                                {t.continueShopping}
148
+                            </SfLink>
149
+                        </aside>
150
+                    </div>
151
+                )}
152
+            </Container>
153
+        </main>
154
+    );
155
+}

+ 231
- 0
resources/js/storefront/pages/checkout.tsx Vedi File

@@ -0,0 +1,231 @@
1
+import { useForm } from '@inertiajs/react';
2
+import type { FormEvent, ReactNode } from 'react';
3
+import { useStorefront } from '../context';
4
+import { storefrontText } from '../text';
5
+import { formatPrice } from '../theme';
6
+import { Container, SfLink } from '../ui';
7
+
8
+const inputClass =
9
+    'w-full rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) px-3 py-2.5 text-base text-(--sf-fg) outline-none focus-visible:border-(--sf-primary) focus-visible:ring-2 focus-visible:ring-(--sf-primary)/30';
10
+
11
+function Field({
12
+    id,
13
+    label,
14
+    error,
15
+    children,
16
+}: {
17
+    id: string;
18
+    label: string;
19
+    error?: string;
20
+    children: ReactNode;
21
+}) {
22
+    return (
23
+        <div className="grid gap-1.5">
24
+            <label htmlFor={id} className="text-sm font-medium">
25
+                {label}
26
+            </label>
27
+            {children}
28
+            {error && (
29
+                <p id={`${id}-error`} className="text-sm text-red-700">
30
+                    {error}
31
+                </p>
32
+            )}
33
+        </div>
34
+    );
35
+}
36
+
37
+/** The shopper's details and address, before going to the payment page. */
38
+export function CheckoutPage({ states }: { states: string[] }) {
39
+    const { cart, language, baseUrl } = useStorefront();
40
+    const t = storefrontText(language);
41
+    const form = useForm({
42
+        name: '',
43
+        email: '',
44
+        phone: '',
45
+        line1: '',
46
+        line2: '',
47
+        city: '',
48
+        postcode: '',
49
+        state: '',
50
+    });
51
+    // "cart" errors come from the server: an empty cart, or the payment page could not be opened.
52
+    const errors = form.errors as typeof form.errors & { cart?: string };
53
+
54
+    function submit(event: FormEvent) {
55
+        event.preventDefault();
56
+        form.post(`${baseUrl}/checkout`, { preserveScroll: true });
57
+    }
58
+
59
+    function text(
60
+        name: keyof typeof form.data,
61
+        label: string,
62
+        props: React.InputHTMLAttributes<HTMLInputElement> = {},
63
+    ) {
64
+        return (
65
+            <Field id={name} label={label} error={form.errors[name]}>
66
+                <input
67
+                    id={name}
68
+                    name={name}
69
+                    value={form.data[name]}
70
+                    onChange={(event) => form.setData(name, event.target.value)}
71
+                    aria-invalid={form.errors[name] ? true : undefined}
72
+                    aria-describedby={
73
+                        form.errors[name] ? `${name}-error` : undefined
74
+                    }
75
+                    className={inputClass}
76
+                    {...props}
77
+                />
78
+            </Field>
79
+        );
80
+    }
81
+
82
+    return (
83
+        <main className="py-10 md:py-14">
84
+            <Container>
85
+                <SfLink
86
+                    href="/cart"
87
+                    className="text-sm text-(--sf-muted) transition-colors hover:text-(--sf-fg)"
88
+                >
89
+                    ← {t.backToCart}
90
+                </SfLink>
91
+
92
+                <h1 className="sf-heading mt-4 text-4xl font-semibold sm:text-5xl">
93
+                    {t.checkout}
94
+                </h1>
95
+
96
+                <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_360px] lg:gap-14">
97
+                    <form onSubmit={submit} className="space-y-10" noValidate>
98
+                        {errors.cart && (
99
+                            <p
100
+                                role="alert"
101
+                                className="rounded-(--sf-radius-card) border border-red-300 bg-red-50 p-4 text-sm text-red-800"
102
+                            >
103
+                                {errors.cart}
104
+                            </p>
105
+                        )}
106
+
107
+                        <fieldset className="space-y-5">
108
+                            <legend className="sf-heading text-xl font-semibold">
109
+                                {t.contactDetails}
110
+                            </legend>
111
+                            {text('name', t.fullName, {
112
+                                autoComplete: 'name',
113
+                                required: true,
114
+                            })}
115
+                            <div className="grid gap-5 sm:grid-cols-2">
116
+                                {text('email', t.email, {
117
+                                    type: 'email',
118
+                                    autoComplete: 'email',
119
+                                    required: true,
120
+                                })}
121
+                                {text('phone', t.phone, {
122
+                                    type: 'tel',
123
+                                    autoComplete: 'tel',
124
+                                    required: true,
125
+                                })}
126
+                            </div>
127
+                        </fieldset>
128
+
129
+                        <fieldset className="space-y-5">
130
+                            <legend className="sf-heading text-xl font-semibold">
131
+                                {t.deliveryAddress}
132
+                            </legend>
133
+                            {text('line1', t.addressLine1, {
134
+                                autoComplete: 'address-line1',
135
+                                required: true,
136
+                            })}
137
+                            {text('line2', t.addressLine2, {
138
+                                autoComplete: 'address-line2',
139
+                            })}
140
+                            <div className="grid gap-5 sm:grid-cols-3">
141
+                                {text('postcode', t.postcode, {
142
+                                    inputMode: 'numeric',
143
+                                    autoComplete: 'postal-code',
144
+                                    maxLength: 5,
145
+                                    required: true,
146
+                                })}
147
+                                {text('city', t.city, {
148
+                                    autoComplete: 'address-level2',
149
+                                    required: true,
150
+                                })}
151
+                                <Field
152
+                                    id="state"
153
+                                    label={t.state}
154
+                                    error={form.errors.state}
155
+                                >
156
+                                    <select
157
+                                        id="state"
158
+                                        name="state"
159
+                                        value={form.data.state}
160
+                                        onChange={(event) =>
161
+                                            form.setData(
162
+                                                'state',
163
+                                                event.target.value,
164
+                                            )
165
+                                        }
166
+                                        autoComplete="address-level1"
167
+                                        required
168
+                                        aria-invalid={
169
+                                            form.errors.state ? true : undefined
170
+                                        }
171
+                                        className={inputClass}
172
+                                    >
173
+                                        <option value="" disabled>
174
+                                            {t.chooseState}
175
+                                        </option>
176
+                                        {states.map((state) => (
177
+                                            <option key={state} value={state}>
178
+                                                {state}
179
+                                            </option>
180
+                                        ))}
181
+                                    </select>
182
+                                </Field>
183
+                            </div>
184
+                        </fieldset>
185
+
186
+                        <div>
187
+                            <button
188
+                                type="submit"
189
+                                disabled={form.processing}
190
+                                className="inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
191
+                            >
192
+                                {t.payNow}
193
+                            </button>
194
+                            <p className="mt-2 text-xs text-(--sf-muted)">
195
+                                {t.paySecure}
196
+                            </p>
197
+                        </div>
198
+                    </form>
199
+
200
+                    <aside className="h-fit rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
201
+                        <h2 className="font-medium">{t.orderSummary}</h2>
202
+                        <ul className="mt-4 space-y-3 text-sm">
203
+                            {cart.lines.map((line) => (
204
+                                <li
205
+                                    key={line.product.id}
206
+                                    className="flex justify-between gap-4"
207
+                                >
208
+                                    <span>
209
+                                        {line.product.name}{' '}
210
+                                        <span className="text-(--sf-muted)">
211
+                                            × {line.quantity}
212
+                                        </span>
213
+                                    </span>
214
+                                    <span className="tabular-nums">
215
+                                        {formatPrice(line.line_total)}
216
+                                    </span>
217
+                                </li>
218
+                            ))}
219
+                        </ul>
220
+                        <div className="mt-5 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
221
+                            <span className="font-medium">{t.total}</span>
222
+                            <span className="text-xl font-semibold tabular-nums">
223
+                                {formatPrice(cart.subtotal)}
224
+                            </span>
225
+                        </div>
226
+                    </aside>
227
+                </div>
228
+            </Container>
229
+        </main>
230
+    );
231
+}

+ 70
- 0
resources/js/storefront/pages/order.tsx Vedi File

@@ -0,0 +1,70 @@
1
+import { useStorefront } from '../context';
2
+import { storefrontText } from '../text';
3
+import { formatPrice } from '../theme';
4
+import type { StoreOrder } from '../types';
5
+import { Container, SfButton } from '../ui';
6
+
7
+/** Where the shopper lands after the payment page: a thank-you, or a "not paid yet" notice. */
8
+export function OrderPage({ order }: { order: StoreOrder }) {
9
+    const { language } = useStorefront();
10
+    const t = storefrontText(language);
11
+    const paid = order.status === 'paid';
12
+    const address = order.shipping_address;
13
+
14
+    return (
15
+        <main className="py-12 md:py-16">
16
+            <Container className="max-w-3xl">
17
+                <h1 className="sf-heading text-4xl font-semibold sm:text-5xl">
18
+                    {paid ? t.thankYou : t.orderPendingTitle}
19
+                </h1>
20
+                <p className="mt-4 text-(--sf-muted)" role="status">
21
+                    {paid
22
+                        ? t.orderPaid(order.number, order.customer_email)
23
+                        : t.orderPending(order.number)}
24
+                </p>
25
+
26
+                <div className="mt-10 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
27
+                    <h2 className="font-medium">{t.orderSummary}</h2>
28
+                    <ul className="mt-4 space-y-3 text-sm">
29
+                        {order.items.map((item) => (
30
+                            <li
31
+                                key={item.id}
32
+                                className="flex justify-between gap-4"
33
+                            >
34
+                                <span>
35
+                                    {item.name}{' '}
36
+                                    <span className="text-(--sf-muted)">
37
+                                        × {item.quantity}
38
+                                    </span>
39
+                                </span>
40
+                                <span className="tabular-nums">
41
+                                    {formatPrice(item.line_total)}
42
+                                </span>
43
+                            </li>
44
+                        ))}
45
+                    </ul>
46
+                    <div className="mt-5 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
47
+                        <span className="font-medium">{t.total}</span>
48
+                        <span className="text-xl font-semibold tabular-nums">
49
+                            {formatPrice(order.total)}
50
+                        </span>
51
+                    </div>
52
+
53
+                    <h2 className="mt-8 font-medium">{t.deliverTo}</h2>
54
+                    <address className="mt-2 text-sm leading-relaxed text-(--sf-muted) not-italic">
55
+                        {order.customer_name}
56
+                        <br />
57
+                        {address.line1}
58
+                        {address.line2 ? `, ${address.line2}` : ''}
59
+                        <br />
60
+                        {address.postcode} {address.city}, {address.state}
61
+                    </address>
62
+                </div>
63
+
64
+                <SfButton href={paid ? '/shop' : '/cart'} className="mt-8">
65
+                    {paid ? t.continueShopping : t.backToCart}
66
+                </SfButton>
67
+            </Container>
68
+        </main>
69
+    );
70
+}

+ 86
- 12
resources/js/storefront/pages/product.tsx Vedi File

@@ -1,10 +1,11 @@
1
+import { router } from '@inertiajs/react';
1 2
 import { useState } from 'react';
2 3
 import { useStorefront } from '../context';
3 4
 import { ProductImage } from '../product-card';
4 5
 import { storefrontText } from '../text';
5 6
 import { formatPrice } from '../theme';
6 7
 import type { StoreProduct } from '../types';
7
-import { Container, SfLink } from '../ui';
8
+import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
8 9
 
9 10
 /** One product's own page. Built by us, in the store's colours and fonts. */
10 11
 export function ProductPage({ product }: { product: StoreProduct }) {
@@ -78,20 +79,93 @@ export function ProductPage({ product }: { product: StoreProduct }) {
78 79
                             </p>
79 80
                         )}
80 81
 
81
-                        {/* The cart arrives in the next part of Step 4. Until then the button is switched off. */}
82
-                        <button
83
-                            type="button"
84
-                            disabled
85
-                            className="mt-8 inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) opacity-50 sm:w-auto"
86
-                        >
87
-                            {product.in_stock ? t.addToCart : t.soldOut}
88
-                        </button>
89
-                        <p className="mt-2 text-xs text-(--sf-muted)">
90
-                            {t.cartSoon}
91
-                        </p>
82
+                        <AddToCart product={product} />
92 83
                     </div>
93 84
                 </div>
94 85
             </Container>
95 86
         </main>
96 87
     );
97 88
 }
89
+
90
+function AddToCart({ product }: { product: StoreProduct }) {
91
+    const { baseUrl, language, cart } = useStorefront();
92
+    const t = storefrontText(language);
93
+    const [quantity, setQuantity] = useState(1);
94
+    const [busy, setBusy] = useState(false);
95
+    const [added, setAdded] = useState(false);
96
+    const [error, setError] = useState<string | null>(null);
97
+
98
+    const inCart =
99
+        cart.lines.find((line) => line.product.id === product.id)?.quantity ??
100
+        0;
101
+    const max = Math.max(0, Math.min(product.stock_left, 99) - inCart);
102
+    const canAdd = product.in_stock && max > 0;
103
+
104
+    function add() {
105
+        setError(null);
106
+        router.post(
107
+            `${baseUrl}/cart/items`,
108
+            { product_id: product.id, quantity: Math.min(quantity, max) },
109
+            {
110
+                preserveScroll: true,
111
+                onStart: () => setBusy(true),
112
+                onFinish: () => setBusy(false),
113
+                onSuccess: () => {
114
+                    setAdded(true);
115
+                    setQuantity(1);
116
+                },
117
+                onError: (errors) =>
118
+                    setError(errors.quantity ?? errors.product_id ?? null),
119
+            },
120
+        );
121
+    }
122
+
123
+    return (
124
+        <div className="mt-8">
125
+            {canAdd && (
126
+                <div className="mb-4 flex items-center gap-3">
127
+                    <span className="text-sm text-(--sf-muted)">
128
+                        {t.quantity}
129
+                    </span>
130
+                    <QuantityStepper
131
+                        value={Math.min(quantity, max)}
132
+                        max={max}
133
+                        onChange={setQuantity}
134
+                        decreaseLabel={t.decrease}
135
+                        increaseLabel={t.increase}
136
+                    />
137
+                    {product.stock_left <= 5 && (
138
+                        <span className="text-sm text-(--sf-muted)">
139
+                            {t.onlyLeft(product.stock_left)}
140
+                        </span>
141
+                    )}
142
+                </div>
143
+            )}
144
+
145
+            <button
146
+                type="button"
147
+                onClick={add}
148
+                disabled={!canAdd || busy}
149
+                className="inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
150
+            >
151
+                {product.in_stock ? t.addToCart : t.soldOut}
152
+            </button>
153
+
154
+            <div aria-live="polite" className="mt-3 min-h-6 text-sm">
155
+                {error && <p className="text-red-700">{error}</p>}
156
+                {added && !error && (
157
+                    <p className="flex flex-wrap items-center gap-3">
158
+                        <span>{t.added}</span>
159
+                        <SfButton
160
+                            href="/cart"
161
+                            variant="outline"
162
+                            className="px-3 py-1.5"
163
+                        >
164
+                            {t.viewCart}
165
+                        </SfButton>
166
+                    </p>
167
+                )}
168
+            </div>
169
+        </div>
170
+    );
171
+}

+ 21
- 1
resources/js/storefront/renderer.tsx Vedi File

@@ -1,5 +1,8 @@
1 1
 import type { ReactNode } from 'react';
2 2
 import { StorefrontProvider } from './context';
3
+import { CartPage } from './pages/cart';
4
+import { CheckoutPage } from './pages/checkout';
5
+import { OrderPage } from './pages/order';
3 6
 import { ProductPage } from './pages/product';
4 7
 import { ShopPage } from './pages/shop';
5 8
 import { About } from './sections/about';
@@ -16,6 +19,7 @@ import { themeStyle } from './theme';
16 19
 import type {
17 20
     FontMap,
18 21
     PlanSection,
22
+    StoreCart,
19 23
     StorePlan,
20 24
     StoreProduct,
21 25
     StorefrontView,
@@ -54,6 +58,18 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
54 58
         return <ShopPage />;
55 59
     }
56 60
 
61
+    if (view.type === 'cart') {
62
+        return <CartPage />;
63
+    }
64
+
65
+    if (view.type === 'checkout') {
66
+        return <CheckoutPage states={view.states} />;
67
+    }
68
+
69
+    if (view.type === 'order') {
70
+        return <OrderPage order={view.order} />;
71
+    }
72
+
57 73
     if (view.type === 'product') {
58 74
         return <ProductPage product={view.product} />;
59 75
     }
@@ -81,6 +97,7 @@ export function StorefrontRenderer({
81 97
     baseUrl,
82 98
     language,
83 99
     products,
100
+    cart,
84 101
 }: {
85 102
     plan: StorePlan;
86 103
     fonts: FontMap;
@@ -88,11 +105,14 @@ export function StorefrontRenderer({
88 105
     baseUrl: string;
89 106
     language: string;
90 107
     products: StoreProduct[];
108
+    cart: StoreCart;
91 109
 }): ReactNode {
92 110
     const isHome = view.type === 'page' && view.pageId === 'home';
93 111
 
94 112
     return (
95
-        <StorefrontProvider value={{ baseUrl, isHome, language, products }}>
113
+        <StorefrontProvider
114
+            value={{ baseUrl, isHome, language, products, cart }}
115
+        >
96 116
             <div
97 117
                 className="sf-root flex min-h-screen flex-col"
98 118
                 style={themeStyle(plan.theme, fonts)}

+ 40
- 5
resources/js/storefront/sections/header.tsx Vedi File

@@ -1,4 +1,7 @@
1
+import { ShoppingBag } from 'lucide-react';
1 2
 import { cn } from '@/lib/utils';
3
+import { useStorefront } from '../context';
4
+import { storefrontText } from '../text';
2 5
 import type { HeaderSection } from '../types';
3 6
 import { Container, SfButton, SfLink } from '../ui';
4 7
 
@@ -9,12 +12,32 @@ export function Header({
9 12
 }) {
10 13
     const { logoText, links, cta } = section.content;
11 14
     const centered = section.variant === 'centered';
15
+    const { cart, language } = useStorefront();
16
+    const t = storefrontText(language);
17
+
18
+    const cartLink = (
19
+        <SfLink
20
+            href="/cart"
21
+            className="relative inline-flex size-10 items-center justify-center rounded-(--sf-radius) text-(--sf-fg) transition-colors hover:bg-(--sf-surface)"
22
+        >
23
+            <ShoppingBag className="size-5" aria-hidden="true" />
24
+            <span className="sr-only">{t.cartCount(cart.count)}</span>
25
+            {cart.count > 0 && (
26
+                <span
27
+                    aria-hidden="true"
28
+                    className="absolute -top-0.5 -right-0.5 flex min-w-5 items-center justify-center rounded-full bg-(--sf-primary) px-1 text-[11px] leading-5 font-semibold text-(--sf-primary-fg)"
29
+                >
30
+                    {cart.count}
31
+                </span>
32
+            )}
33
+        </SfLink>
34
+    );
12 35
 
13 36
     return (
14 37
         <header className="sticky top-0 z-20 border-b border-(--sf-border) bg-(--sf-bg)/90 backdrop-blur">
15 38
             <Container
16 39
                 className={cn(
17
-                    'flex items-center gap-6 py-4',
40
+                    'relative flex items-center gap-6 py-4',
18 41
                     centered ? 'flex-col sm:gap-3' : 'justify-between',
19 42
                 )}
20 43
             >
@@ -42,10 +65,22 @@ export function Header({
42 65
                     ))}
43 66
                 </nav>
44 67
 
45
-                {cta && !centered && (
46
-                    <SfButton href={cta.href} className="px-4 py-2">
47
-                        {cta.label}
48
-                    </SfButton>
68
+                {centered ? (
69
+                    <div className="absolute top-3 right-5 sm:right-8">
70
+                        {cartLink}
71
+                    </div>
72
+                ) : (
73
+                    <div className="flex items-center gap-2">
74
+                        {cartLink}
75
+                        {cta && (
76
+                            <SfButton
77
+                                href={cta.href}
78
+                                className="hidden px-4 py-2 sm:inline-flex"
79
+                            >
80
+                                {cta.label}
81
+                            </SfButton>
82
+                        )}
83
+                    </div>
49 84
                 )}
50 85
             </Container>
51 86
         </header>

+ 83
- 2
resources/js/storefront/text.ts Vedi File

@@ -10,7 +10,48 @@ const words = {
10 10
         soldOut: 'Sold out',
11 11
         inStock: 'In stock',
12 12
         addToCart: 'Add to cart',
13
-        cartSoon: 'Buying is not switched on yet.',
13
+        quantity: 'Quantity',
14
+        added: 'Added to your cart.',
15
+        viewCart: 'View cart',
16
+        cart: 'Cart',
17
+        yourCart: 'Your cart',
18
+        cartEmpty: 'Your cart is empty.',
19
+        continueShopping: 'Continue shopping',
20
+        remove: 'Remove',
21
+        decrease: 'Decrease quantity',
22
+        increase: 'Increase quantity',
23
+        subtotal: 'Subtotal',
24
+        shippingNote: 'Shipping is worked out at checkout.',
25
+        checkout: 'Checkout',
26
+        contactDetails: 'Your details',
27
+        deliveryAddress: 'Delivery address',
28
+        fullName: 'Full name',
29
+        email: 'Email',
30
+        phone: 'Phone number',
31
+        addressLine1: 'Address',
32
+        addressLine2: 'Unit, floor, building (optional)',
33
+        city: 'City',
34
+        postcode: 'Postcode',
35
+        state: 'State',
36
+        chooseState: 'Choose a state',
37
+        orderSummary: 'Order summary',
38
+        total: 'Total',
39
+        payNow: 'Continue to payment',
40
+        paySecure: 'You will pay on a secure Stripe page.',
41
+        backToCart: 'Back to cart',
42
+        thankYou: 'Thank you for your order',
43
+        orderPaid: (number: number, email: string) =>
44
+            `Order #${number} is paid. We sent a confirmation to ${email}.`,
45
+        orderPendingTitle: 'Payment not completed',
46
+        orderPending: (number: number) =>
47
+            `Order #${number} has not been paid yet. Your cart is still saved, so you can try again.`,
48
+        deliverTo: 'Deliver to',
49
+        quantityShort: 'Qty',
50
+        cartAdjusted:
51
+            'Some items changed because stock ran low. Please check your cart.',
52
+        onlyLeft: (count: number) => `Only ${count} left`,
53
+        cartCount: (count: number) =>
54
+            count === 1 ? 'Cart, 1 item' : `Cart, ${count} items`,
14 55
         backToShop: 'Back to shop',
15 56
         noProducts: 'No products yet. Please check back soon.',
16 57
         productCount: (count: number) =>
@@ -23,7 +64,47 @@ const words = {
23 64
         soldOut: 'Habis dijual',
24 65
         inStock: 'Ada stok',
25 66
         addToCart: 'Tambah ke troli',
26
-        cartSoon: 'Pembelian belum dibuka lagi.',
67
+        quantity: 'Kuantiti',
68
+        added: 'Ditambah ke troli anda.',
69
+        viewCart: 'Lihat troli',
70
+        cart: 'Troli',
71
+        yourCart: 'Troli anda',
72
+        cartEmpty: 'Troli anda kosong.',
73
+        continueShopping: 'Teruskan membeli-belah',
74
+        remove: 'Buang',
75
+        decrease: 'Kurangkan kuantiti',
76
+        increase: 'Tambah kuantiti',
77
+        subtotal: 'Jumlah kecil',
78
+        shippingNote: 'Kos penghantaran dikira semasa pembayaran.',
79
+        checkout: 'Bayar',
80
+        contactDetails: 'Butiran anda',
81
+        deliveryAddress: 'Alamat penghantaran',
82
+        fullName: 'Nama penuh',
83
+        email: 'E-mel',
84
+        phone: 'Nombor telefon',
85
+        addressLine1: 'Alamat',
86
+        addressLine2: 'Unit, tingkat, bangunan (pilihan)',
87
+        city: 'Bandar',
88
+        postcode: 'Poskod',
89
+        state: 'Negeri',
90
+        chooseState: 'Pilih negeri',
91
+        orderSummary: 'Ringkasan pesanan',
92
+        total: 'Jumlah',
93
+        payNow: 'Teruskan ke pembayaran',
94
+        paySecure: 'Anda akan membayar di halaman Stripe yang selamat.',
95
+        backToCart: 'Kembali ke troli',
96
+        thankYou: 'Terima kasih atas pesanan anda',
97
+        orderPaid: (number: number, email: string) =>
98
+            `Pesanan #${number} telah dibayar. Pengesahan dihantar ke ${email}.`,
99
+        orderPendingTitle: 'Pembayaran belum selesai',
100
+        orderPending: (number: number) =>
101
+            `Pesanan #${number} belum dibayar. Troli anda masih disimpan, jadi anda boleh cuba lagi.`,
102
+        deliverTo: 'Hantar ke',
103
+        quantityShort: 'Kuantiti',
104
+        cartAdjusted:
105
+            'Beberapa item berubah kerana stok berkurangan. Sila semak troli anda.',
106
+        onlyLeft: (count: number) => `Tinggal ${count} sahaja`,
107
+        cartCount: (count: number) => `Troli, ${count} item`,
27 108
         backToShop: 'Kembali ke kedai',
28 109
         noProducts: 'Belum ada produk. Sila datang semula nanti.',
29 110
         productCount: (count: number) => `${count} produk`,

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

@@ -165,12 +165,68 @@ export type StoreProduct = {
165 165
     price: number;
166 166
     compare_at_price: number | null;
167 167
     in_stock: boolean;
168
+    /** How many can still be bought. */
169
+    stock_left: number;
168 170
     image: string | null;
169 171
     images: string[];
170 172
 };
171 173
 
174
+export type CartLine = {
175
+    product: StoreProduct;
176
+    quantity: number;
177
+    /** The most the shopper may choose, from the stock. */
178
+    max: number;
179
+    line_total: number;
180
+};
181
+
182
+/** The shopper's cart. Money is in ringgit. */
183
+export type StoreCart = {
184
+    count: number;
185
+    subtotal: number;
186
+    /** True when stock changed and the cart was corrected. */
187
+    adjusted: boolean;
188
+    lines: CartLine[];
189
+};
190
+
191
+export type OrderAddress = {
192
+    line1: string;
193
+    line2: string | null;
194
+    city: string;
195
+    postcode: string;
196
+    state: string;
197
+    country: string;
198
+};
199
+
200
+/** An order as shown to people. Money is in ringgit. */
201
+export type StoreOrder = {
202
+    id: number;
203
+    public_id: string;
204
+    number: number;
205
+    status: 'pending' | 'paid';
206
+    status_label: string;
207
+    customer_name: string;
208
+    customer_email: string;
209
+    customer_phone: string;
210
+    shipping_address: OrderAddress;
211
+    subtotal: number;
212
+    shipping_total: number;
213
+    total: number;
214
+    paid_at: string | null;
215
+    created_at: string | null;
216
+    items: {
217
+        id: number;
218
+        name: string;
219
+        unit_price: number;
220
+        quantity: number;
221
+        line_total: number;
222
+    }[];
223
+};
224
+
172 225
 /** Which storefront page to show. */
173 226
 export type StorefrontView =
174 227
     | { type: 'page'; pageId: string }
175 228
     | { type: 'shop' }
229
+    | { type: 'cart' }
230
+    | { type: 'checkout'; states: string[] }
231
+    | { type: 'order'; order: StoreOrder }
176 232
     | { type: 'product'; product: StoreProduct };

+ 51
- 0
resources/js/storefront/ui.tsx Vedi File

@@ -63,6 +63,57 @@ export function SfLink({
63 63
     );
64 64
 }
65 65
 
66
+/** A minus button, the number, and a plus button. */
67
+export function QuantityStepper({
68
+    value,
69
+    max,
70
+    min = 1,
71
+    disabled = false,
72
+    onChange,
73
+    decreaseLabel,
74
+    increaseLabel,
75
+}: {
76
+    value: number;
77
+    max: number;
78
+    min?: number;
79
+    disabled?: boolean;
80
+    onChange: (value: number) => void;
81
+    decreaseLabel: string;
82
+    increaseLabel: string;
83
+}) {
84
+    const button =
85
+        'flex size-9 items-center justify-center text-lg leading-none transition-colors hover:bg-(--sf-surface) disabled:cursor-not-allowed disabled:opacity-40';
86
+
87
+    return (
88
+        <div className="inline-flex items-center overflow-hidden rounded-(--sf-radius) border border-(--sf-border)">
89
+            <button
90
+                type="button"
91
+                className={button}
92
+                aria-label={decreaseLabel}
93
+                disabled={disabled || value <= min}
94
+                onClick={() => onChange(value - 1)}
95
+            >
96
+                −
97
+            </button>
98
+            <span
99
+                className="min-w-9 px-1 text-center text-sm tabular-nums"
100
+                aria-live="polite"
101
+            >
102
+                {value}
103
+            </span>
104
+            <button
105
+                type="button"
106
+                className={button}
107
+                aria-label={increaseLabel}
108
+                disabled={disabled || value >= max}
109
+                onClick={() => onChange(value + 1)}
110
+            >
111
+                +
112
+            </button>
113
+        </div>
114
+    );
115
+}
116
+
66 117
 export function Eyebrow({ children }: { children: ReactNode }) {
67 118
     return (
68 119
         <p className="text-xs font-semibold tracking-[0.18em] text-(--sf-primary) uppercase">

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

@@ -60,3 +60,35 @@ export type StoreSummary = {
60 60
     name: string;
61 61
     slug: string;
62 62
 };
63
+
64
+/** An order as the dashboard sees it. Money is in ringgit. */
65
+export type Order = {
66
+    id: number;
67
+    public_id: string;
68
+    number: number;
69
+    status: 'pending' | 'paid';
70
+    status_label: string;
71
+    customer_name: string;
72
+    customer_email: string;
73
+    customer_phone: string;
74
+    shipping_address: {
75
+        line1: string;
76
+        line2: string | null;
77
+        city: string;
78
+        postcode: string;
79
+        state: string;
80
+        country: string;
81
+    };
82
+    subtotal: number;
83
+    shipping_total: number;
84
+    total: number;
85
+    paid_at: string | null;
86
+    created_at: string | null;
87
+    items: {
88
+        id: number;
89
+        name: string;
90
+        unit_price: number;
91
+        quantity: number;
92
+        line_total: number;
93
+    }[];
94
+};

+ 26
- 0
resources/views/mail/orders/confirmation.blade.php Vedi File

@@ -0,0 +1,26 @@
1
+<x-mail::message>
2
+# {{ $malay ? 'Terima kasih atas pesanan anda' : 'Thank you for your order' }}
3
+
4
+{{ $malay ? 'Hai' : 'Hi' }} {{ $order->customer_name }},
5
+
6
+{{ $malay
7
+    ? "Kami telah menerima bayaran anda. Ini ringkasan pesanan #{$order->number} daripada {$store->name}."
8
+    : "We have received your payment. Here is a summary of order #{$order->number} from {$store->name}." }}
9
+
10
+<x-mail::table>
11
+| {{ $malay ? 'Produk' : 'Item' }} | {{ $malay ? 'Kuantiti' : 'Qty' }} | {{ $malay ? 'Jumlah' : 'Total' }} |
12
+| :--- | :---: | ---: |
13
+@foreach ($order->items as $item)
14
+| {{ $item->name }} | {{ $item->quantity }} | {{ $money($item->line_total) }} |
15
+@endforeach
16
+| **{{ $malay ? 'Jumlah dibayar' : 'Total paid' }}** | | **{{ $money($order->total) }}** |
17
+</x-mail::table>
18
+
19
+**{{ $malay ? 'Alamat penghantaran' : 'Delivery address' }}**
20
+
21
+{{ $order->shipping_address['line1'] }}@if ($order->shipping_address['line2']), {{ $order->shipping_address['line2'] }}@endif<br>
22
+{{ $order->shipping_address['postcode'] }} {{ $order->shipping_address['city'] }}, {{ $order->shipping_address['state'] }}
23
+
24
+{{ $malay ? 'Terima kasih,' : 'Thanks,' }}<br>
25
+{{ $store->name }}
26
+</x-mail::message>

+ 19
- 0
routes/web.php Vedi File

@@ -1,13 +1,20 @@
1 1
 <?php
2 2
 
3
+use App\Http\Controllers\CartController;
4
+use App\Http\Controllers\CheckoutController;
5
+use App\Http\Controllers\OrderController;
3 6
 use App\Http\Controllers\ProductController;
4 7
 use App\Http\Controllers\StoreController;
5 8
 use App\Http\Controllers\StoreDesignController;
6 9
 use App\Http\Controllers\StoreGenerationController;
10
+use App\Http\Controllers\StripeWebhookController;
7 11
 use Illuminate\Support\Facades\Route;
8 12
 
9 13
 Route::inertia('/', 'welcome')->name('home');
10 14
 
15
+// Called by Stripe, not by a browser, so it has no login. Each message is checked with a signing secret.
16
+Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
17
+
11 18
 Route::middleware(['auth', 'verified'])->group(function () {
12 19
     Route::get('dashboard', [StoreController::class, 'index'])->name('dashboard');
13 20
 
@@ -18,6 +25,18 @@ Route::middleware(['auth', 'verified'])->group(function () {
18 25
     Route::get('stores/{slug}/preview/shop', [StoreDesignController::class, 'shop'])->name('stores.preview.shop');
19 26
     Route::get('stores/{slug}/preview/products/{productSlug}', [StoreDesignController::class, 'product'])->name('stores.preview.product');
20 27
 
28
+    Route::get('stores/{slug}/preview/cart', [CartController::class, 'show'])->name('stores.preview.cart');
29
+    Route::post('stores/{slug}/preview/cart/items', [CartController::class, 'add'])->name('stores.preview.cart.add');
30
+    Route::patch('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'update'])->name('stores.preview.cart.update')->whereNumber('product');
31
+    Route::delete('stores/{slug}/preview/cart/items/{product}', [CartController::class, 'remove'])->name('stores.preview.cart.remove')->whereNumber('product');
32
+
33
+    Route::get('stores/{slug}/preview/checkout', [CheckoutController::class, 'show'])->name('stores.preview.checkout');
34
+    Route::post('stores/{slug}/preview/checkout', [CheckoutController::class, 'store'])->name('stores.preview.checkout.store');
35
+    Route::get('stores/{slug}/preview/orders/{publicId}', [CheckoutController::class, 'order'])->name('stores.preview.order');
36
+
37
+    Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
38
+    Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');
39
+
21 40
     Route::get('stores/{slug}/products', [ProductController::class, 'index'])->name('stores.products.index');
22 41
     Route::get('stores/{slug}/products/create', [ProductController::class, 'create'])->name('stores.products.create');
23 42
     Route::post('stores/{slug}/products', [ProductController::class, 'store'])->name('stores.products.store');

+ 204
- 0
tests/Feature/Stores/CartTest.php Vedi File

@@ -0,0 +1,204 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Models\Product;
6
+use App\Models\Store;
7
+use App\Models\User;
8
+use App\StorePlan\SamplePlan;
9
+use Illuminate\Foundation\Testing\RefreshDatabase;
10
+use Inertia\Testing\AssertableInertia as Assert;
11
+use Tests\TestCase;
12
+
13
+class CartTest extends TestCase
14
+{
15
+    use RefreshDatabase;
16
+
17
+    private User $user;
18
+
19
+    private Store $store;
20
+
21
+    protected function setUp(): void
22
+    {
23
+        parent::setUp();
24
+
25
+        $this->user = User::factory()->create();
26
+        $this->store = $this->storeWithDesign($this->user);
27
+        $this->actingAs($this->user);
28
+    }
29
+
30
+    private function storeWithDesign(User $user): Store
31
+    {
32
+        $store = Store::factory()->for($user)->create();
33
+        $store->plan = SamplePlan::for($store);
34
+        $store->save();
35
+
36
+        return $store;
37
+    }
38
+
39
+    private function add(Product $product, int $quantity = 1, ?Store $store = null)
40
+    {
41
+        return $this->post(route('stores.preview.cart.add', ($store ?? $this->store)->slug), [
42
+            'product_id' => $product->id,
43
+            'quantity' => $quantity,
44
+        ]);
45
+    }
46
+
47
+    private function assertCart(callable $assert, ?Store $store = null): void
48
+    {
49
+        $this->get(route('stores.preview.cart', ($store ?? $this->store)->slug))
50
+            ->assertOk()
51
+            ->assertInertia(fn (Assert $page) => $assert($page->where('view.type', 'cart')));
52
+    }
53
+
54
+    public function test_a_new_cart_is_empty()
55
+    {
56
+        $this->assertCart(fn (Assert $page) => $page
57
+            ->where('cart.count', 0)
58
+            ->where('cart.subtotal', 0)
59
+            ->where('cart.adjusted', false)
60
+            ->has('cart.lines', 0));
61
+    }
62
+
63
+    public function test_a_shopper_can_add_products_and_the_totals_are_exact()
64
+    {
65
+        $sambal = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
66
+        $kerepek = Product::factory()->for($this->store)->create(['name' => 'Kerepek', 'price' => 799, 'stock' => 10]);
67
+
68
+        $this->add($sambal, 2)->assertRedirect();
69
+        $this->add($kerepek, 3)->assertRedirect();
70
+        // Adding the same product again increases its quantity.
71
+        $this->add($sambal, 1)->assertRedirect();
72
+
73
+        $this->assertCart(fn (Assert $page) => $page
74
+            ->where('cart.count', 6)
75
+            // 3 x 12.90 + 3 x 7.99 = 62.67
76
+            ->where('cart.subtotal', 62.67)
77
+            ->has('cart.lines', 2)
78
+            ->where('cart.lines.0.product.name', 'Sambal')
79
+            ->where('cart.lines.0.quantity', 3)
80
+            ->where('cart.lines.0.max', 10)
81
+            ->where('cart.lines.0.line_total', 38.7)
82
+            ->where('cart.lines.1.quantity', 3)
83
+            ->where('cart.lines.1.line_total', 23.97));
84
+
85
+        // Every storefront page knows the cart, so the header can show the count.
86
+        $this->get(route('stores.preview', $this->store->slug))
87
+            ->assertInertia(fn (Assert $page) => $page->where('cart.count', 6));
88
+    }
89
+
90
+    public function test_a_shopper_cannot_add_more_than_the_stock()
91
+    {
92
+        $product = Product::factory()->for($this->store)->create(['stock' => 3]);
93
+
94
+        $this->add($product, 2);
95
+        $this->add($product, 5);
96
+
97
+        $this->assertCart(fn (Assert $page) => $page
98
+            ->where('cart.lines.0.quantity', 3)
99
+            ->where('cart.lines.0.max', 3));
100
+    }
101
+
102
+    public function test_quantity_can_be_changed_and_zero_removes_the_item()
103
+    {
104
+        $product = Product::factory()->for($this->store)->create(['stock' => 10]);
105
+        $this->add($product, 2);
106
+
107
+        $this->patch(route('stores.preview.cart.update', [$this->store->slug, $product->id]), ['quantity' => 7])->assertRedirect();
108
+        $this->assertCart(fn (Assert $page) => $page->where('cart.lines.0.quantity', 7));
109
+
110
+        $this->patch(route('stores.preview.cart.update', [$this->store->slug, $product->id]), ['quantity' => 50]);
111
+        $this->assertCart(fn (Assert $page) => $page->where('cart.lines.0.quantity', 10));
112
+
113
+        $this->patch(route('stores.preview.cart.update', [$this->store->slug, $product->id]), ['quantity' => 0]);
114
+        $this->assertCart(fn (Assert $page) => $page->has('cart.lines', 0));
115
+    }
116
+
117
+    public function test_an_item_can_be_removed()
118
+    {
119
+        $keep = Product::factory()->for($this->store)->create();
120
+        $drop = Product::factory()->for($this->store)->create();
121
+        $this->add($keep);
122
+        $this->add($drop);
123
+
124
+        $this->delete(route('stores.preview.cart.remove', [$this->store->slug, $drop->id]))->assertRedirect();
125
+
126
+        $this->assertCart(fn (Assert $page) => $page
127
+            ->has('cart.lines', 1)
128
+            ->where('cart.lines.0.product.id', $keep->id));
129
+    }
130
+
131
+    public function test_bad_quantities_are_refused()
132
+    {
133
+        $product = Product::factory()->for($this->store)->create(['stock' => 10]);
134
+
135
+        $this->add($product, 0)->assertSessionHasErrors('quantity');
136
+        $this->add($product, -3)->assertSessionHasErrors('quantity');
137
+        $this->add($product, 100)->assertSessionHasErrors('quantity');
138
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => '1; drop'])
139
+            ->assertSessionHasErrors('quantity');
140
+
141
+        $this->assertCart(fn (Assert $page) => $page->has('cart.lines', 0));
142
+    }
143
+
144
+    public function test_only_products_shoppers_can_buy_may_be_added()
145
+    {
146
+        $draft = Product::factory()->for($this->store)->draft()->create();
147
+        $soldOut = Product::factory()->for($this->store)->soldOut()->create();
148
+        $elsewhere = Product::factory()->create();
149
+
150
+        $this->add($draft)->assertNotFound();
151
+        $this->add($elsewhere)->assertNotFound();
152
+        $this->add($soldOut)->assertSessionHasErrors('quantity');
153
+
154
+        $this->assertCart(fn (Assert $page) => $page->has('cart.lines', 0));
155
+    }
156
+
157
+    public function test_the_cart_corrects_itself_when_stock_or_status_changes()
158
+    {
159
+        $shrinks = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 10]);
160
+        $hidden = Product::factory()->for($this->store)->create(['stock' => 10]);
161
+        $deleted = Product::factory()->for($this->store)->create(['stock' => 10]);
162
+        $this->add($shrinks, 8);
163
+        $this->add($hidden, 1);
164
+        $this->add($deleted, 1);
165
+
166
+        $shrinks->update(['stock' => 2, 'price' => 1500]);
167
+        $hidden->update(['status' => 'draft']);
168
+        $deleted->delete();
169
+
170
+        $this->assertCart(fn (Assert $page) => $page
171
+            ->where('cart.adjusted', true)
172
+            ->has('cart.lines', 1)
173
+            ->where('cart.lines.0.quantity', 2)
174
+            // The price is always the current one, never the one from when it was added.
175
+            ->where('cart.subtotal', 30));
176
+
177
+        // The correction is saved, so the notice shows only once.
178
+        $this->assertCart(fn (Assert $page) => $page->where('cart.adjusted', false)->has('cart.lines', 1));
179
+    }
180
+
181
+    public function test_each_store_has_its_own_cart()
182
+    {
183
+        $other = $this->storeWithDesign($this->user);
184
+        $here = Product::factory()->for($this->store)->create();
185
+        $there = Product::factory()->for($other)->create();
186
+
187
+        $this->add($here, 2);
188
+        $this->add($there, 1, $other);
189
+
190
+        $this->assertCart(fn (Assert $page) => $page->where('cart.count', 2)->where('cart.lines.0.product.id', $here->id));
191
+        $this->assertCart(fn (Assert $page) => $page->where('cart.count', 1)->where('cart.lines.0.product.id', $there->id), $other);
192
+    }
193
+
194
+    public function test_the_cart_of_someone_elses_store_cannot_be_opened_or_changed()
195
+    {
196
+        $theirs = $this->storeWithDesign(User::factory()->create());
197
+        $product = Product::factory()->for($theirs)->create();
198
+
199
+        $this->get(route('stores.preview.cart', $theirs->slug))->assertNotFound();
200
+        $this->add($product, 1, $theirs)->assertNotFound();
201
+        $this->patch(route('stores.preview.cart.update', [$theirs->slug, $product->id]), ['quantity' => 1])->assertNotFound();
202
+        $this->delete(route('stores.preview.cart.remove', [$theirs->slug, $product->id]))->assertNotFound();
203
+    }
204
+}

+ 381
- 0
tests/Feature/Stores/CheckoutTest.php Vedi File

@@ -0,0 +1,381 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentException;
6
+use App\Commerce\Payments\PaymentGateway;
7
+use App\Commerce\Payments\StripeGateway;
8
+use App\Enums\OrderStatus;
9
+use App\Mail\OrderConfirmation;
10
+use App\Models\Order;
11
+use App\Models\Product;
12
+use App\Models\Store;
13
+use App\Models\User;
14
+use App\StorePlan\SamplePlan;
15
+use Illuminate\Foundation\Testing\RefreshDatabase;
16
+use Illuminate\Support\Facades\Mail;
17
+use Inertia\Testing\AssertableInertia as Assert;
18
+use Tests\Support\FakeGateway;
19
+use Tests\TestCase;
20
+
21
+class CheckoutTest extends TestCase
22
+{
23
+    use RefreshDatabase;
24
+
25
+    private User $user;
26
+
27
+    private Store $store;
28
+
29
+    private FakeGateway $gateway;
30
+
31
+    protected function setUp(): void
32
+    {
33
+        parent::setUp();
34
+
35
+        Mail::fake();
36
+
37
+        $this->gateway = new FakeGateway;
38
+        $this->app->instance(PaymentGateway::class, $this->gateway);
39
+
40
+        $this->user = User::factory()->create();
41
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
42
+        $this->store->plan = SamplePlan::for($this->store);
43
+        $this->store->save();
44
+        $this->actingAs($this->user);
45
+    }
46
+
47
+    /**
48
+     * @return array<string, string>
49
+     */
50
+    private function details(array $overrides = []): array
51
+    {
52
+        return [
53
+            'name' => 'Aminah binti Ali',
54
+            'email' => 'aminah@example.com',
55
+            'phone' => '012-345 6789',
56
+            'line1' => '12 Jalan Mawar',
57
+            'line2' => '',
58
+            'city' => 'Shah Alam',
59
+            'postcode' => '40000',
60
+            'state' => 'Selangor',
61
+            ...$overrides,
62
+        ];
63
+    }
64
+
65
+    private function addToCart(Product $product, int $quantity = 1): void
66
+    {
67
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity]);
68
+    }
69
+
70
+    private function placeOrder(array $overrides = [])
71
+    {
72
+        return $this->post(route('stores.preview.checkout.store', $this->store->slug), $this->details($overrides));
73
+    }
74
+
75
+    private function orderPage(Order $order)
76
+    {
77
+        return $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
78
+    }
79
+
80
+    public function test_checkout_needs_something_in_the_cart()
81
+    {
82
+        $this->get(route('stores.preview.checkout', $this->store->slug))
83
+            ->assertRedirect(route('stores.preview.cart', $this->store->slug));
84
+
85
+        $this->placeOrder()->assertSessionHasErrors('cart');
86
+
87
+        $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
88
+
89
+        $this->get(route('stores.preview.checkout', $this->store->slug))
90
+            ->assertOk()
91
+            ->assertInertia(fn (Assert $page) => $page
92
+                ->where('view.type', 'checkout')
93
+                ->has('view.states', 16)
94
+                ->where('cart.count', 1));
95
+    }
96
+
97
+    public function test_placing_an_order_saves_it_and_sends_the_shopper_to_the_payment_page()
98
+    {
99
+        $sambal = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
100
+        $kerepek = Product::factory()->for($this->store)->create(['name' => 'Kerepek', 'price' => 799, 'stock' => 10]);
101
+        $this->addToCart($sambal, 2);
102
+        $this->addToCart($kerepek, 1);
103
+
104
+        $this->placeOrder()->assertRedirect('https://pay.test/cs_fake_1');
105
+
106
+        $order = Order::with('items')->firstOrFail();
107
+
108
+        $this->assertSame($this->store->id, $order->store_id);
109
+        $this->assertSame(1001, $order->number);
110
+        $this->assertSame(OrderStatus::Pending, $order->status);
111
+        $this->assertSame(3379, $order->subtotal);
112
+        $this->assertSame(3379, $order->total);
113
+        $this->assertSame('MYR', $order->currency);
114
+        $this->assertSame('fake', $order->payment_provider);
115
+        $this->assertSame('cs_fake_1', $order->payment_checkout_id);
116
+        $this->assertSame('Aminah binti Ali', $order->customer_name);
117
+        $this->assertSame(['line1' => '12 Jalan Mawar', 'line2' => null, 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor', 'country' => 'MY'], $order->shipping_address);
118
+        $this->assertSame(26, strlen($order->public_id));
119
+        $this->assertCount(2, $order->items);
120
+        $this->assertSame(['Sambal', 1290, 2, 2580], [$order->items[0]->name, $order->items[0]->unit_price, $order->items[0]->quantity, $order->items[0]->line_total]);
121
+
122
+        // Nothing is taken from stock, and no email goes out, until the order is paid.
123
+        $this->assertSame(10, $sambal->fresh()->stock);
124
+        Mail::assertNothingSent();
125
+
126
+        // The next order of the same store gets the next number.
127
+        $this->placeOrder();
128
+        $this->assertSame(1002, Order::latest('id')->firstOrFail()->number);
129
+    }
130
+
131
+    public function test_shopper_details_are_checked()
132
+    {
133
+        $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
134
+
135
+        $this->placeOrder([
136
+            'name' => '',
137
+            'email' => 'not-an-email',
138
+            'phone' => 'call me',
139
+            'line1' => '',
140
+            'city' => '',
141
+            'postcode' => '4000',
142
+            'state' => 'Atlantis',
143
+        ])->assertSessionHasErrors(['name', 'email', 'phone', 'line1', 'city', 'postcode', 'state']);
144
+
145
+        $this->assertSame(0, Order::count());
146
+    }
147
+
148
+    public function test_an_order_must_be_at_least_two_ringgit()
149
+    {
150
+        $this->addToCart(Product::factory()->for($this->store)->create(['price' => 199]));
151
+
152
+        $this->placeOrder()->assertSessionHasErrors('cart');
153
+
154
+        $this->assertSame(0, Order::count());
155
+    }
156
+
157
+    public function test_if_the_payment_page_cannot_be_opened_no_order_is_left_behind()
158
+    {
159
+        $this->gateway->failToStart = true;
160
+        $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
161
+
162
+        $this->placeOrder()->assertSessionHasErrors('cart');
163
+
164
+        $this->assertSame(0, Order::count());
165
+        $this->get(route('stores.preview.cart', $this->store->slug))
166
+            ->assertInertia(fn (Assert $page) => $page->where('cart.count', 1));
167
+    }
168
+
169
+    public function test_a_paid_order_is_marked_lowers_stock_empties_the_cart_and_emails_the_shopper_once()
170
+    {
171
+        $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
172
+        $this->addToCart($product, 3);
173
+        $this->placeOrder();
174
+        $order = Order::firstOrFail();
175
+
176
+        $this->gateway->pay($order);
177
+
178
+        $this->orderPage($order)
179
+            ->assertOk()
180
+            ->assertInertia(fn (Assert $page) => $page
181
+                ->where('view.type', 'order')
182
+                ->where('view.order.status', 'paid')
183
+                ->where('view.order.number', 1001)
184
+                ->where('view.order.total', 38.7)
185
+                ->has('view.order.items', 1)
186
+                ->where('cart.count', 0));
187
+
188
+        $order->refresh();
189
+
190
+        $this->assertTrue($order->isPaid());
191
+        $this->assertNotNull($order->paid_at);
192
+        $this->assertSame('pi_fake_1', $order->payment_reference);
193
+        $this->assertSame(7, $product->fresh()->stock);
194
+
195
+        Mail::assertSent(OrderConfirmation::class, fn (OrderConfirmation $mail) => $mail->hasTo('aminah@example.com')
196
+            && $mail->order->is($order));
197
+
198
+        // Opening the page again must not take stock or send the email a second time.
199
+        $this->orderPage($order)->assertOk();
200
+
201
+        $this->assertSame(7, $product->fresh()->stock);
202
+        Mail::assertSent(OrderConfirmation::class, 1);
203
+    }
204
+
205
+    public function test_an_unpaid_order_stays_pending_and_the_cart_is_kept()
206
+    {
207
+        $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
208
+        $this->addToCart($product, 2);
209
+        $this->placeOrder();
210
+        $order = Order::firstOrFail();
211
+
212
+        $this->orderPage($order)
213
+            ->assertInertia(fn (Assert $page) => $page
214
+                ->where('view.order.status', 'pending')
215
+                ->where('cart.count', 2));
216
+
217
+        $this->assertFalse($order->fresh()->isPaid());
218
+        $this->assertSame(10, $product->fresh()->stock);
219
+        Mail::assertNothingSent();
220
+    }
221
+
222
+    public function test_a_payment_of_the_wrong_amount_does_not_mark_the_order_paid()
223
+    {
224
+        $this->addToCart(Product::factory()->for($this->store)->create(['price' => 5000, 'stock' => 5]));
225
+        $this->placeOrder();
226
+        $order = Order::firstOrFail();
227
+
228
+        $this->gateway->pay($order, amount: 500);
229
+
230
+        $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
231
+
232
+        Mail::assertNothingSent();
233
+    }
234
+
235
+    public function test_an_order_keeps_its_own_record_when_products_change_later()
236
+    {
237
+        $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
238
+        $this->addToCart($product, 2);
239
+        $this->placeOrder();
240
+        $order = Order::firstOrFail();
241
+
242
+        $product->update(['name' => 'Renamed', 'price' => 9900]);
243
+        $product->delete();
244
+
245
+        $item = $order->items()->firstOrFail();
246
+
247
+        $this->assertNull($item->product_id);
248
+        $this->assertSame(['Sambal', 1290, 2580], [$item->name, $item->unit_price, $item->line_total]);
249
+        $this->assertSame(2580, $order->fresh()->total);
250
+
251
+        // Paying for it still works, even though the product is gone.
252
+        $this->gateway->pay($order);
253
+        $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid'));
254
+    }
255
+
256
+    public function test_stock_never_goes_below_zero()
257
+    {
258
+        $product = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 5]);
259
+        $this->addToCart($product, 4);
260
+        $this->placeOrder();
261
+        $order = Order::firstOrFail();
262
+
263
+        // The merchant sold some elsewhere while the shopper was paying.
264
+        $product->update(['stock' => 1]);
265
+        $this->gateway->pay($order);
266
+        $this->orderPage($order);
267
+
268
+        $this->assertSame(0, $product->fresh()->stock);
269
+    }
270
+
271
+    public function test_the_webhook_marks_an_order_paid_without_the_shopper_coming_back()
272
+    {
273
+        $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
274
+        $this->addToCart($product, 1);
275
+        $this->placeOrder();
276
+        $order = Order::firstOrFail();
277
+        $this->gateway->pay($order);
278
+
279
+        auth()->logout();
280
+
281
+        $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'forged'])->assertStatus(400);
282
+        $this->assertFalse($order->fresh()->isPaid());
283
+
284
+        $this->postJson(route('stripe.webhook'), ['other' => 'event'], ['Stripe-Signature' => 'valid'])->assertOk();
285
+        $this->assertFalse($order->fresh()->isPaid());
286
+
287
+        $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
288
+        $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
289
+
290
+        $this->assertTrue($order->fresh()->isPaid());
291
+        $this->assertSame(9, $product->fresh()->stock);
292
+        Mail::assertSent(OrderConfirmation::class, 1);
293
+    }
294
+
295
+    public function test_the_real_stripe_gateway_only_accepts_messages_signed_with_our_secret()
296
+    {
297
+        config(['services.stripe.webhook_secret' => 'whsec_test_secret']);
298
+
299
+        $payload = (string) json_encode([
300
+            'id' => 'evt_1',
301
+            'object' => 'event',
302
+            'type' => 'checkout.session.completed',
303
+            'data' => ['object' => [
304
+                'id' => 'cs_test_123',
305
+                'object' => 'checkout.session',
306
+                'payment_status' => 'paid',
307
+                'payment_intent' => 'pi_123',
308
+                'amount_total' => 2580,
309
+            ]],
310
+        ]);
311
+        $time = time();
312
+        $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
313
+
314
+        $status = (new StripeGateway)->readWebhook($payload, $sign('whsec_test_secret'));
315
+
316
+        $this->assertSame('cs_test_123', $status->checkoutId);
317
+        $this->assertTrue($status->paid);
318
+        $this->assertSame('pi_123', $status->reference);
319
+        $this->assertSame(2580, $status->amount);
320
+
321
+        $this->expectException(PaymentException::class);
322
+        (new StripeGateway)->readWebhook($payload, $sign('whsec_someone_else'));
323
+    }
324
+
325
+    public function test_the_confirmation_email_lists_the_order_in_the_store_language()
326
+    {
327
+        $order = Order::factory()->for($this->store)->paid()->create(['number' => 1007, 'total' => 2580]);
328
+        $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
329
+
330
+        $mail = new OrderConfirmation($order);
331
+
332
+        $mail->assertHasSubject('Order #1007 confirmed - Kedai Ali');
333
+        $mail->assertSeeInHtml('Sambal Hijau');
334
+        $mail->assertSeeInHtml('RM 25.80');
335
+        $mail->assertSeeInHtml('12 Jalan Mawar');
336
+
337
+        $this->store->update(['language' => 'ms']);
338
+
339
+        (new OrderConfirmation($order->fresh()))->assertHasSubject('Pesanan #1007 disahkan - Kedai Ali');
340
+    }
341
+
342
+    public function test_the_merchant_sees_the_stores_orders()
343
+    {
344
+        $paid = Order::factory()->for($this->store)->paid()->create(['number' => 1001, 'total' => 5000]);
345
+        Order::factory()->for($this->store)->create(['number' => 1002]);
346
+        Order::factory()->create();
347
+
348
+        $this->get(route('stores.orders.index', $this->store->slug))
349
+            ->assertOk()
350
+            ->assertInertia(fn (Assert $page) => $page
351
+                ->component('stores/orders/index')
352
+                ->has('orders', 2)
353
+                ->where('orders.0.number', 1002)
354
+                ->where('orders.0.status', 'pending')
355
+                ->where('orders.1.status', 'paid')
356
+                ->where('orders.1.total', 50));
357
+
358
+        $this->get(route('stores.orders.show', [$this->store->slug, $paid->id]))
359
+            ->assertOk()
360
+            ->assertInertia(fn (Assert $page) => $page
361
+                ->component('stores/orders/show')
362
+                ->where('order.number', 1001)
363
+                ->where('order.customer_email', 'aminah@example.com'));
364
+    }
365
+
366
+    public function test_orders_of_another_store_cannot_be_seen()
367
+    {
368
+        $theirs = Store::factory()->create();
369
+        $theirs->plan = SamplePlan::for($theirs);
370
+        $theirs->save();
371
+        $order = Order::factory()->for($theirs)->paid()->create();
372
+
373
+        $this->get(route('stores.orders.index', $theirs->slug))->assertNotFound();
374
+        $this->get(route('stores.orders.show', [$theirs->slug, $order->id]))->assertNotFound();
375
+        // Their order id inside my own store's address must not work either.
376
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))->assertNotFound();
377
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))->assertNotFound();
378
+        $this->get(route('stores.preview.checkout', $theirs->slug))->assertNotFound();
379
+        $this->post(route('stores.preview.checkout.store', $theirs->slug), $this->details())->assertNotFound();
380
+    }
381
+}

+ 68
- 0
tests/Support/FakeGateway.php Vedi File

@@ -0,0 +1,68 @@
1
+<?php
2
+
3
+namespace Tests\Support;
4
+
5
+use App\Commerce\Payments\CheckoutLink;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Commerce\Payments\PaymentGateway;
8
+use App\Commerce\Payments\PaymentStatus;
9
+use App\Models\Order;
10
+
11
+/**
12
+ * A payment provider for tests. Nothing leaves the machine.
13
+ * Tests decide whether a payment page was paid by calling pay().
14
+ */
15
+final class FakeGateway implements PaymentGateway
16
+{
17
+    /** @var array<string, PaymentStatus> */
18
+    public array $payments = [];
19
+
20
+    /** @var list<Order> */
21
+    public array $started = [];
22
+
23
+    public bool $failToStart = false;
24
+
25
+    public function name(): string
26
+    {
27
+        return 'fake';
28
+    }
29
+
30
+    public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
31
+    {
32
+        if ($this->failToStart) {
33
+            throw new PaymentException('The provider is down.');
34
+        }
35
+
36
+        $id = 'cs_fake_'.$order->id;
37
+        $this->started[] = $order;
38
+        $this->payments[$id] = new PaymentStatus($id, paid: false);
39
+
40
+        return new CheckoutLink($id, 'https://pay.test/'.$id);
41
+    }
42
+
43
+    public function checkPayment(string $checkoutId): PaymentStatus
44
+    {
45
+        return $this->payments[$checkoutId] ?? throw new PaymentException('Unknown payment.');
46
+    }
47
+
48
+    public function readWebhook(string $payload, string $signature): ?PaymentStatus
49
+    {
50
+        if ($signature !== 'valid') {
51
+            throw new PaymentException('Bad signature.');
52
+        }
53
+
54
+        $data = json_decode($payload, true);
55
+
56
+        return isset($data['checkout_id']) ? $this->checkPayment($data['checkout_id']) : null;
57
+    }
58
+
59
+    /**
60
+     * Pretend the shopper paid on the payment page.
61
+     */
62
+    public function pay(Order $order, ?int $amount = null): void
63
+    {
64
+        $id = (string) $order->fresh()?->payment_checkout_id;
65
+
66
+        $this->payments[$id] = new PaymentStatus($id, paid: true, reference: 'pi_fake_'.$order->id, amount: $amount ?? $order->total);
67
+    }
68
+}

Loading…
Annulla
Salva