Переглянути джерело

Add shipping fees, mark as shipped and WhatsApp links

Step 7 part 1:
- Store Settings tab with WhatsApp number and flat shipping fees for
  Peninsular and East Malaysia, plus optional free shipping.
- Shipping fee behind a ShippingProvider interface; added at checkout,
  sent to Stripe as its own line, shown on the thank-you page and email.
- Mark as shipped with courier and tracking number; the shopper is
  emailed once, in the store language.
- WhatsApp chat button on the store and wa.me links on order pages.
- Checkout and cart messages in Bahasa Malaysia; Malaysian-only phone
  numbers for WhatsApp.
- Fix live-store menu links on pages other than home.
feature/malaysia-shipping
fahmisaad 4 дні тому
джерело
коміт
c26451e8ff
38 змінених файлів з 1509 додано та 109 видалено
  1. 91
    62
      PROGRESS.md
  2. 22
    12
      README.md
  3. 11
    5
      app/Commerce/Checkout.php
  4. 16
    0
      app/Commerce/Couriers.php
  5. 19
    0
      app/Commerce/Payments/StripeGateway.php
  6. 28
    0
      app/Commerce/Shipping/FlatRateShipping.php
  7. 17
    0
      app/Commerce/Shipping/ShippingProvider.php
  8. 2
    1
      app/Http/Controllers/CartController.php
  9. 13
    7
      app/Http/Controllers/CheckoutController.php
  10. 6
    0
      app/Http/Controllers/Concerns/RendersStorefront.php
  11. 52
    1
      app/Http/Controllers/OrderController.php
  12. 81
    0
      app/Http/Controllers/StoreSettingsController.php
  13. 43
    0
      app/Mail/OrderShipped.php
  14. 7
    0
      app/Models/Order.php
  15. 11
    1
      app/Models/Store.php
  16. 3
    0
      app/Providers/AppServiceProvider.php
  17. 69
    0
      app/Storefront/StorefrontText.php
  18. 35
    0
      app/Support/MalaysianPhone.php
  19. 38
    0
      database/migrations/2026_11_16_000000_add_shipping_and_whatsapp.php
  20. 7
    1
      resources/js/components/stores/store-nav.tsx
  21. 8
    0
      resources/js/pages/stores/orders/index.tsx
  22. 148
    1
      resources/js/pages/stores/orders/show.tsx
  23. 5
    0
      resources/js/pages/stores/preview.tsx
  24. 185
    0
      resources/js/pages/stores/settings.tsx
  25. 10
    3
      resources/js/storefront/context.tsx
  26. 17
    1
      resources/js/storefront/pages/cart.tsx
  27. 39
    3
      resources/js/storefront/pages/checkout.tsx
  28. 56
    5
      resources/js/storefront/pages/order.tsx
  29. 24
    2
      resources/js/storefront/renderer.tsx
  30. 31
    0
      resources/js/storefront/text.ts
  31. 17
    1
      resources/js/storefront/types.ts
  32. 34
    0
      resources/js/storefront/whatsapp.tsx
  33. 3
    0
      resources/js/types/store.ts
  34. 1
    0
      resources/views/mail/orders/confirmation.blade.php
  35. 31
    0
      resources/views/mail/orders/shipped.blade.php
  36. 4
    0
      routes/web.php
  37. 317
    0
      tests/Feature/Malaysia/ShippingTest.php
  38. 8
    3
      tests/Feature/Stores/CheckoutTest.php

+ 91
- 62
PROGRESS.md Переглянути файл

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-14
7
-**Current step:** Step 7 — Malaysia features (Step 6 billing is done and tested with a real Stripe test subscription)
8
-**Next action:** Merge `feature/billing` into `main`, then start Step 7: FPX, DuitNow and e-wallets at checkout, EasyParcel shipping, Bahasa Malaysia, WhatsApp
7
+**Current step:** Step 7 — Malaysia features (part 1 done: shipping fees, mark as shipped, WhatsApp buttons, Malay checkout messages; part 2 needs EasyParcel and WhatsApp Business accounts)
8
+**Next action:** Merge `feature/malaysia-shipping` into `main`. Then either Step 7 part 2 (needs an EasyParcel demo account and API key) or go on to Step 8 (discounts) and come back to part 2 later
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -121,6 +121,15 @@ Changing from Claude to another AI model (or back) must be a settings change, no
121 121
 - Switching plans changes the existing subscription; Stripe charges or credits the difference on the next bill.
122 122
 - Subscriptions go through one interface (`SubscriptionGateway`), like payments and AI.
123 123
 
124
+### How shipping and WhatsApp work (added in Step 7)
125
+
126
+- Shipping fees are stored on the store in sen (`shipping_west`, `shipping_east`, `free_shipping_over`). Sabah, Sarawak and Labuan use the east fee; every other state uses the west fee.
127
+- The fee goes through one interface (`ShippingProvider`). `FlatRateShipping` is the first provider; EasyParcel live rates can replace it in one place.
128
+- The order saves `shipping_total`, and Stripe must collect subtotal plus shipping before the order counts as paid.
129
+- `shipped_at`, `shipping_courier` and `tracking_number` on the order record the delivery. Only paid orders can be shipped.
130
+- WhatsApp numbers are saved as digits with country code (`60123456789`). Only Malaysian numbers are accepted. `MalaysianPhone` does the cleaning.
131
+- Messages the server shows to shoppers live in `App\Storefront\StorefrontText`; words drawn in the browser live in `resources/js/storefront/text.ts`.
132
+
124 133
 ### Plan prices and limits (starting numbers, adjust after real usage)
125 134
 
126 135
 | Plan                 | Price / month | Stores | Full regenerations / month | AI edits / month |
@@ -183,7 +192,7 @@ Changing from Claude to another AI model (or back) must be a settings change, no
183 192
 - [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
184 193
 - [x] Orders list and order page for the merchant ("Orders" tab)
185 194
 - [x] Order confirmation email, in the store's language, sent once when the order is paid
186
-- [ ] 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 9)
195
+- [ ] Known gaps, to do later: (shipping fee and "mark as shipped" were done in Step 7 part 1); unpaid orders stay in the list as "Awaiting payment"; the Stripe webhook needs a public address, so it only starts working after hosting (Step 9)
187 196
 - [x] Content pages by chat ("add an About page", "remove the About page"): the AI creates the page, and the app itself makes sure the menu links to it. Tested with real DeepSeek on 2026-11-15
188 197
 
189 198
 ### Step 5 — Publishing
@@ -207,10 +216,23 @@ Changing from Claude to another AI model (or back) must be a settings change, no
207 216
 
208 217
 ### Step 7 — Malaysia features
209 218
 
210
-- [ ] FPX, DuitNow QR and e-wallets at checkout
211
-- [ ] EasyParcel shipping rates and labels
212
-- [ ] Bahasa Malaysia and English store generation
213
-- [ ] WhatsApp order notifications and chat button
219
+Part 1 (done 2026-11-16, no new accounts needed):
220
+
221
+- [x] Store "Settings" tab: WhatsApp number and shipping fees
222
+- [x] Flat shipping fees: one for Peninsular Malaysia (default RM 8), one for Sabah, Sarawak and Labuan (default RM 15), optional free shipping above an amount. Shown at checkout as soon as a state is chosen, on Stripe's page as its own line, on the thank-you page and in the email
223
+- [x] "Mark as shipped" on the merchant's order page, with courier and tracking number. The shopper gets a "your order is on its way" email once; later corrections do not email again
224
+- [x] WhatsApp chat button on every page of the store, "Ask about this order on WhatsApp" on the thank-you page, and "WhatsApp customer" on the merchant's order page (all `wa.me` links, no account needed)
225
+- [x] Bahasa Malaysia and English store generation (already working since Step 3; checked again)
226
+- [x] Checkout and cart error messages in the store's language
227
+- [x] Checked which payment methods the Stripe account has: cards on; FPX and GrabPay supported by Stripe in Malaysia but not switched on yet (switch on in the Stripe dashboard, no code change). DuitNow QR, Touch 'n Go and Boost are not offered by Stripe
228
+- [x] Tested with a real Stripe test payment on 2026-11-16: Sabah order, RM 15 shipping, total RM 70; then marked as shipped
229
+
230
+Part 2 (needs outside accounts):
231
+
232
+- [ ] Switch on FPX and GrabPay in the Stripe dashboard (your action), then test an FPX payment
233
+- [ ] EasyParcel live shipping rates and labels (needs an EasyParcel demo account and API key; plugs in behind `ShippingProvider`)
234
+- [ ] Automatic WhatsApp order notifications (needs a WhatsApp Business Platform account from Meta, with approved message templates)
235
+- [ ] DuitNow QR and Malaysian e-wallets: only through a second payment provider (for example Billplz, ToyyibPay, HitPay or Fiuu). Decide whether it is worth it
214 236
 
215 237
 ### Step 8 — Discounts and product options
216 238
 
@@ -277,48 +299,54 @@ Then, from the project folder:
277 299
 
278 300
 ## 4b. Where things are in the code
279 301
 
280
-| Thing                                  | Location                                                                                    |
281
-| -------------------------------------- | ------------------------------------------------------------------------------------------- |
282
-| Store model                            | `app/Models/Store.php`                                                                      |
283
-| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                  |
284
-| Store categories, languages, statuses  | `app/Enums/`                                                                                |
285
-| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                           |
286
-| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                            |
287
-| Store tests                            | `tests/Feature/Stores/`                                                                     |
288
-| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                              |
289
-| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                           |
290
-| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                              |
291
-| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                            |
292
-| AI settings                            | `config/ai.php` (providers, models per task)                                                |
293
-| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                |
294
-| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                         |
295
-| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                        |
296
-| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                           |
297
-| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                           |
298
-| Progress screen and chat box           | `resources/js/components/stores/`                                                           |
299
-| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                     |
300
-| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                |
301
-| Product screens                        | `resources/js/pages/stores/products/`                                                       |
302
-| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                            |
303
-| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                  |
304
-| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                             |
305
-| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)             |
306
-| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`             |
307
-| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                            |
308
-| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                             |
309
-| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                            |
310
-| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                           |
311
-| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php` |
312
-| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)              |
313
-| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                 |
314
-| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                          |
315
-| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                           |
316
-| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                          |
317
-| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                 |
302
+| Thing                                  | Location                                                                                       |
303
+| -------------------------------------- | ---------------------------------------------------------------------------------------------- |
304
+| Store model                            | `app/Models/Store.php`                                                                         |
305
+| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                     |
306
+| Store categories, languages, statuses  | `app/Enums/`                                                                                   |
307
+| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                              |
308
+| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                               |
309
+| Store tests                            | `tests/Feature/Stores/`                                                                        |
310
+| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                 |
311
+| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                              |
312
+| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                 |
313
+| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                               |
314
+| AI settings                            | `config/ai.php` (providers, models per task)                                                   |
315
+| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                   |
316
+| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                            |
317
+| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                           |
318
+| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                              |
319
+| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                              |
320
+| Progress screen and chat box           | `resources/js/components/stores/`                                                              |
321
+| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                        |
322
+| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                   |
323
+| Product screens                        | `resources/js/pages/stores/products/`                                                          |
324
+| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                               |
325
+| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                     |
326
+| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                |
327
+| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                |
328
+| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                |
329
+| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                               |
330
+| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                |
331
+| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                               |
332
+| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                              |
333
+| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`    |
334
+| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                 |
335
+| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                    |
336
+| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php` |
337
+| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                       |
338
+| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                           |
339
+| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                       |
340
+| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                         |
341
+| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                             |
342
+| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                              |
343
+| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                             |
344
+| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                    |
318 345
 
319 346
 ## 5. Open questions
320 347
 
321 348
 - **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.
349
+- **DuitNow QR and e-wallets:** Stripe does not offer them. Adding them means a second payment provider. Decide later, based on what merchants ask for.
322 350
 - Hosting provider (decide at Step 9)
323 351
 
324 352
 ## 6. Later improvements
@@ -335,20 +363,21 @@ Then, from the project folder:
335 363
 
336 364
 Add one line per work session: date, what was done, what is next.
337 365
 
338
-| Date       | Done                                                                                                                                                                                                                                                                                                                                         | Next                                                            |
339
-| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
340
-| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                          | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
341
-| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                     | Step 2: store plan format, sections, renderer                   |
342
-| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                              | Step 3: swappable AI layer and store generation                 |
343
-| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
344
-| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                      | Add API keys, run the real test, then Step 4                    |
345
-| 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                                       |
346
-| 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                        |
347
-| 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             |
348
-| 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                |
349
-| 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                      |
350
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                 | Step 5: publishing                                              |
351
-| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                           | Step 5: publishing                                              |
352
-| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                 | Step 5: publishing                                              |
353
-| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                         | Step 6: subscription billing                                    |
354
-| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5. | Merge into `main`, then Step 7                                  |
366
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                        | Next                                                            |
367
+| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
368
+| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                         | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
369
+| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                    | Step 2: store plan format, sections, renderer                   |
370
+| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                             | Step 3: swappable AI layer and store generation                 |
371
+| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                       | Step 3: swappable AI layer and store generation                 |
372
+| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                     | Add API keys, run the real test, then Step 4                    |
373
+| 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                                       |
374
+| 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                        |
375
+| 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             |
376
+| 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                |
377
+| 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                      |
378
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                | Step 5: publishing                                              |
379
+| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                                                          | Step 5: publishing                                              |
380
+| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                                                | Step 5: publishing                                              |
381
+| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                                                        | Step 6: subscription billing                                    |
382
+| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                | Merge into `main`, then Step 7                                  |
383
+| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked. | Merge, then Step 7 part 2 or Step 8                             |

+ 22
- 12
README.md Переглянути файл

@@ -10,18 +10,18 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
10 10
 
11 11
 ## Current status
12 12
 
13
-| Step | What                                                    | Status                                              |
14
-| ---- | ------------------------------------------------------- | --------------------------------------------------- |
15
-| 0    | Prepare the local machine                               | Done                                                |
16
-| 1    | Project foundation: login, create a store, dashboard    | Done                                                |
17
-| 2    | Store sections, renderer and preview                    | Done                                                |
18
-| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                |
19
-| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                |
20
-| 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting |
21
-| 6    | Our own subscription billing                            | Done                                                |
22
-| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Next                                                |
23
-| 8    | Discounts and product options: codes, variants, bundles | Not started                                         |
24
-| 9    | Before launch: hosting, legal pages, backups            | Not started                                         |
13
+| Step | What                                                    | Status                                                         |
14
+| ---- | ------------------------------------------------------- | -------------------------------------------------------------- |
15
+| 0    | Prepare the local machine                               | Done                                                           |
16
+| 1    | Project foundation: login, create a store, dashboard    | Done                                                           |
17
+| 2    | Store sections, renderer and preview                    | Done                                                           |
18
+| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                           |
19
+| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                           |
20
+| 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting            |
21
+| 6    | Our own subscription billing                            | Done                                                           |
22
+| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Part 1 done (shipping fees, WhatsApp); EasyParcel and FPX next |
23
+| 8    | Discounts and product options: codes, variants, bundles | Not started                                                    |
24
+| 9    | Before launch: hosting, legal pages, backups            | Not started                                                    |
25 25
 
26 26
 ## What works today
27 27
 
@@ -45,6 +45,8 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
45 45
 - Orders tab for the merchant, and an order confirmation email to the shopper
46 46
 - Publishing: a store goes live at its own address (`storename.localhost:8000` on a local machine), with no login for shoppers
47 47
 - Design changes stay private until the merchant clicks "Publish changes"
48
+- Shipping fees for Peninsular and East Malaysia, with optional free shipping, and "mark as shipped" with a tracking number
49
+- WhatsApp chat button on the store, and WhatsApp links on order pages
48 50
 - Billing: 14-day free trial, then Starter, Growth or Pro through Stripe. Merchants can switch or cancel on the Billing page, and plan limits are enforced
49 51
 
50 52
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.
@@ -194,6 +196,14 @@ Changing from Claude to another AI model is a settings change, not a code rewrit
194 196
 - AI work runs in the background, so the worker must be running. `composer run dev` starts it.
195 197
 - Settings are in `config/ai.php`. Plan limits are in `config/plans.php`.
196 198
 
199
+## Shipping and WhatsApp
200
+
201
+- Each store's **Settings** tab holds its WhatsApp number and shipping fees: one fee for Peninsular Malaysia, one for Sabah, Sarawak and Labuan, and an optional free-shipping amount.
202
+- The fee is added at checkout and sent to Stripe as its own line.
203
+- On an order's page the merchant chooses the courier and tracking number and clicks "Mark as shipped". The shopper gets an email.
204
+- WhatsApp buttons are plain `wa.me` links and need no WhatsApp account. Automatic WhatsApp messages need a WhatsApp Business account (Step 7 part 2).
205
+- FPX and GrabPay are switched on in the Stripe dashboard, not in this app. Stripe does not offer DuitNow QR.
206
+
197 207
 ## Billing
198 208
 
199 209
 - Every new account starts a 14-day free trial.

+ 11
- 5
app/Commerce/Checkout.php Переглянути файл

@@ -3,11 +3,13 @@
3 3
 namespace App\Commerce;
4 4
 
5 5
 use App\Commerce\Payments\PaymentStatus;
6
+use App\Commerce\Shipping\ShippingProvider;
6 7
 use App\Enums\OrderStatus;
7 8
 use App\Mail\OrderConfirmation;
8 9
 use App\Models\Order;
9 10
 use App\Models\Product;
10 11
 use App\Models\Store;
12
+use App\Storefront\StorefrontText;
11 13
 use Illuminate\Support\Facades\DB;
12 14
 use Illuminate\Support\Facades\Mail;
13 15
 use Illuminate\Support\Str;
@@ -18,6 +20,8 @@ use Illuminate\Validation\ValidationException;
18 20
  */
19 21
 class Checkout
20 22
 {
23
+    public function __construct(private readonly ShippingProvider $shipping) {}
24
+
21 25
     /** Stripe does not accept payments below RM 2.00. */
22 26
     public const int MINIMUM_TOTAL = 200;
23 27
 
@@ -38,14 +42,16 @@ class Checkout
38 42
         $subtotal = (int) $lines->sum('line_total');
39 43
 
40 44
         if ($lines->isEmpty()) {
41
-            throw ValidationException::withMessages(['cart' => __('Your cart is empty.')]);
45
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'cart_empty')]);
42 46
         }
43 47
 
44 48
         if ($subtotal < self::MINIMUM_TOTAL) {
45
-            throw ValidationException::withMessages(['cart' => __('The order total must be at least RM 2.00.')]);
49
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]);
46 50
         }
47 51
 
48
-        return DB::transaction(function () use ($store, $lines, $subtotal, $details): Order {
52
+        $shipping = $this->shipping->quote($store, $subtotal, $details['state']);
53
+
54
+        return DB::transaction(function () use ($store, $lines, $subtotal, $shipping, $details): Order {
49 55
             // Lock the store row so two orders placed at the same moment cannot get the same number.
50 56
             Store::query()->whereKey($store->id)->lockForUpdate()->first();
51 57
 
@@ -66,8 +72,8 @@ class Checkout
66 72
                 'country' => 'MY',
67 73
             ];
68 74
             $order->subtotal = $subtotal;
69
-            $order->shipping_total = 0;
70
-            $order->total = $subtotal;
75
+            $order->shipping_total = $shipping;
76
+            $order->total = $subtotal + $shipping;
71 77
             $order->currency = 'MYR';
72 78
             $order->save();
73 79
 

+ 16
- 0
app/Commerce/Couriers.php Переглянути файл

@@ -0,0 +1,16 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+final class Couriers
6
+{
7
+    /**
8
+     * Couriers merchants in Malaysia commonly use. "Other" covers anything else, such as delivering by hand.
9
+     *
10
+     * @var list<string>
11
+     */
12
+    public const array ALL = [
13
+        'Pos Laju', 'J&T Express', 'Ninja Van', 'DHL eCommerce', 'City-Link Express',
14
+        'GDEX', 'SPX Express', 'Flash Express', 'Lalamove', 'Other',
15
+    ];
16
+}

+ 19
- 0
app/Commerce/Payments/StripeGateway.php Переглянути файл

@@ -40,6 +40,14 @@ final class StripeGateway implements PaymentGateway
40 40
                         'product_data' => ['name' => $item->name],
41 41
                     ],
42 42
                 ])->values()->all(),
43
+                // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
44
+                'shipping_options' => [[
45
+                    'shipping_rate_data' => [
46
+                        'type' => 'fixed_amount',
47
+                        'fixed_amount' => ['amount' => $order->shipping_total, 'currency' => strtolower($order->currency)],
48
+                        'display_name' => $this->shippingLabel($order),
49
+                    ],
50
+                ]],
43 51
                 // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
44 52
                 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
45 53
                 'cancel_url' => $cancelUrl,
@@ -55,6 +63,17 @@ final class StripeGateway implements PaymentGateway
55 63
         return new CheckoutLink($session->id, $session->url);
56 64
     }
57 65
 
66
+    private function shippingLabel(Order $order): string
67
+    {
68
+        $malay = $order->store->language->value === 'ms';
69
+
70
+        if ($order->shipping_total === 0) {
71
+            return $malay ? 'Penghantaran percuma' : 'Free shipping';
72
+        }
73
+
74
+        return $malay ? 'Penghantaran' : 'Shipping';
75
+    }
76
+
58 77
     public function checkPayment(string $checkoutId): PaymentStatus
59 78
     {
60 79
         try {

+ 28
- 0
app/Commerce/Shipping/FlatRateShipping.php Переглянути файл

@@ -0,0 +1,28 @@
1
+<?php
2
+
3
+namespace App\Commerce\Shipping;
4
+
5
+use App\Models\Store;
6
+
7
+/**
8
+ * One fee for Peninsular Malaysia, another for Sabah, Sarawak and Labuan,
9
+ * and free shipping above an amount the merchant chooses.
10
+ */
11
+final class FlatRateShipping implements ShippingProvider
12
+{
13
+    /**
14
+     * States across the sea from the peninsula, where couriers charge more.
15
+     *
16
+     * @var list<string>
17
+     */
18
+    public const array EAST_MALAYSIA = ['Sabah', 'Sarawak', 'Labuan'];
19
+
20
+    public function quote(Store $store, int $subtotal, string $state): int
21
+    {
22
+        if ($store->free_shipping_over !== null && $subtotal >= $store->free_shipping_over) {
23
+            return 0;
24
+        }
25
+
26
+        return in_array($state, self::EAST_MALAYSIA, true) ? $store->shipping_east : $store->shipping_west;
27
+    }
28
+}

+ 17
- 0
app/Commerce/Shipping/ShippingProvider.php Переглянути файл

@@ -0,0 +1,17 @@
1
+<?php
2
+
3
+namespace App\Commerce\Shipping;
4
+
5
+use App\Models\Store;
6
+
7
+/**
8
+ * Works out the shipping fee for an order.
9
+ * Flat rates are the first provider; EasyParcel live rates can be added behind the same interface later.
10
+ */
11
+interface ShippingProvider
12
+{
13
+    /**
14
+     * The shipping fee in sen for an order of this subtotal (in sen) to this Malaysian state.
15
+     */
16
+    public function quote(Store $store, int $subtotal, string $state): int;
17
+}

+ 2
- 1
app/Http/Controllers/CartController.php Переглянути файл

@@ -6,6 +6,7 @@ use App\Commerce\Cart;
6 6
 use App\Http\Controllers\Concerns\RendersStorefront;
7 7
 use App\Models\Product;
8 8
 use App\Models\Store;
9
+use App\Storefront\StorefrontText;
9 10
 use Illuminate\Http\RedirectResponse;
10 11
 use Illuminate\Http\Request;
11 12
 use Illuminate\Validation\ValidationException;
@@ -38,7 +39,7 @@ class CartController extends Controller
38 39
         $product = $this->buyableProduct($store, $validated['product_id']);
39 40
 
40 41
         if ($product->stock < 1) {
41
-            throw ValidationException::withMessages(['quantity' => __('This product is sold out.')]);
42
+            throw ValidationException::withMessages(['quantity' => StorefrontText::line($store->language->value, 'sold_out')]);
42 43
         }
43 44
 
44 45
         $this->cart($request, $store)->add($product, $validated['quantity']);

+ 13
- 7
app/Http/Controllers/CheckoutController.php Переглянути файл

@@ -6,8 +6,10 @@ use App\Commerce\Checkout;
6 6
 use App\Commerce\MalaysianStates;
7 7
 use App\Commerce\Payments\PaymentException;
8 8
 use App\Commerce\Payments\PaymentGateway;
9
+use App\Commerce\Shipping\ShippingProvider;
9 10
 use App\Http\Controllers\Concerns\RendersStorefront;
10 11
 use App\Models\Order;
12
+use App\Storefront\StorefrontText;
11 13
 use Illuminate\Http\RedirectResponse;
12 14
 use Illuminate\Http\Request;
13 15
 use Illuminate\Validation\Rule;
@@ -26,17 +28,24 @@ class CheckoutController extends Controller
26 28
     /**
27 29
      * The form for the shopper's contact details and delivery address.
28 30
      */
29
-    public function show(Request $request): Response|RedirectResponse
31
+    public function show(Request $request, ShippingProvider $shipping): Response|RedirectResponse
30 32
     {
31 33
         $storefront = $this->storefront($request);
34
+        $lines = $this->cart($request, $storefront->store)->lines();
32 35
 
33
-        if ($this->cart($request, $storefront->store)->lines()->isEmpty()) {
36
+        if ($lines->isEmpty()) {
34 37
             return redirect($storefront->path('/cart'));
35 38
         }
36 39
 
40
+        $subtotal = (int) $lines->sum('line_total');
41
+
37 42
         return $this->renderStorefront($request, $storefront, [
38 43
             'type' => 'checkout',
39 44
             'states' => MalaysianStates::ALL,
45
+            // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
46
+            'shippingByState' => collect(MalaysianStates::ALL)
47
+                ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $subtotal, $state) / 100])
48
+                ->all(),
40 49
         ]);
41 50
     }
42 51
 
@@ -57,10 +66,7 @@ class CheckoutController extends Controller
57 66
             'city' => ['required', 'string', 'min:2', 'max:100'],
58 67
             'postcode' => ['required', 'string', 'regex:/^[0-9]{5}$/'],
59 68
             'state' => ['required', Rule::in(MalaysianStates::ALL)],
60
-        ], [
61
-            'phone.regex' => __('Please enter a valid phone number.'),
62
-            'postcode.regex' => __('The postcode must be 5 digits.'),
63
-        ]);
69
+        ], StorefrontText::checkoutMessages($store->language->value), StorefrontText::checkoutFields($store->language->value));
64 70
 
65 71
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
66 72
 
@@ -75,7 +81,7 @@ class CheckoutController extends Controller
75 81
             $order->delete();
76 82
 
77 83
             throw ValidationException::withMessages([
78
-                'cart' => __('We could not start the payment. Please try again in a moment.'),
84
+                'cart' => StorefrontText::line($store->language->value, 'payment_unavailable'),
79 85
             ]);
80 86
         }
81 87
 

+ 6
- 0
app/Http/Controllers/Concerns/RendersStorefront.php Переглянути файл

@@ -52,6 +52,12 @@ trait RendersStorefront
52 52
                 ->get()
53 53
                 ->map(fn (Product $product) => $product->toStorefront()),
54 54
             'cart' => $this->cart($request, $store)->toStorefront(),
55
+            'shop' => [
56
+                // Digits only, such as 60123456789, or null when the merchant has not set one.
57
+                'whatsapp' => $store->whatsapp_number,
58
+                // In ringgit, or null when shipping is never free.
59
+                'free_shipping_over' => $store->free_shipping_over !== null ? $store->free_shipping_over / 100 : null,
60
+            ],
55 61
         ]);
56 62
     }
57 63
 }

+ 52
- 1
app/Http/Controllers/OrderController.php Переглянути файл

@@ -2,9 +2,15 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
+use App\Commerce\Couriers;
6
+use App\Mail\OrderShipped;
5 7
 use App\Models\Order;
6 8
 use App\Models\Store;
9
+use App\Support\MalaysianPhone;
10
+use Illuminate\Http\RedirectResponse;
7 11
 use Illuminate\Http\Request;
12
+use Illuminate\Support\Facades\Mail;
13
+use Illuminate\Validation\Rule;
8 14
 use Inertia\Inertia;
9 15
 use Inertia\Response;
10 16
 
@@ -31,13 +37,58 @@ class OrderController extends Controller
31 37
     public function show(Request $request, string $slug, int $order): Response
32 38
     {
33 39
         $store = $this->ownedStore($request, $slug);
40
+        $order = $store->orders()->with('items')->whereKey($order)->firstOrFail();
41
+        $customerWhatsapp = MalaysianPhone::normalize($order->customer_phone);
34 42
 
35 43
         return Inertia::render('stores/orders/show', [
36 44
             'store' => ['name' => $store->name, 'slug' => $store->slug],
37
-            'order' => $store->orders()->with('items')->whereKey($order)->firstOrFail()->toDisplay(),
45
+            'order' => $order->toDisplay(),
46
+            'couriers' => Couriers::ALL,
47
+            // A chat with the shopper, with a first message already typed in the store's language.
48
+            'customer_whatsapp_url' => $customerWhatsapp !== null
49
+                ? MalaysianPhone::whatsappLink($customerWhatsapp, $store->language->value === 'ms'
50
+                    ? "Hai {$order->customer_name}, terima kasih atas pesanan #{$order->number} daripada {$store->name}."
51
+                    : "Hi {$order->customer_name}, thank you for your order #{$order->number} from {$store->name}.")
52
+                : null,
38 53
         ]);
39 54
     }
40 55
 
56
+    /**
57
+     * Record that a paid order was sent. The shopper is emailed the first time only;
58
+     * later saves just correct the courier or tracking number.
59
+     */
60
+    public function ship(Request $request, string $slug, int $order): RedirectResponse
61
+    {
62
+        $store = $this->ownedStore($request, $slug);
63
+        $order = $store->orders()->whereKey($order)->firstOrFail();
64
+
65
+        abort_unless($order->isPaid(), 404);
66
+
67
+        $validated = $request->validate([
68
+            'shipping_courier' => ['required', Rule::in(Couriers::ALL)],
69
+            'tracking_number' => ['nullable', 'string', 'max:80', 'regex:/^[A-Za-z0-9\-\s]+$/'],
70
+        ], [
71
+            'tracking_number.regex' => __('Use only letters, numbers, spaces and dashes.'),
72
+        ]);
73
+
74
+        $firstTime = $order->shipped_at === null;
75
+
76
+        $order->shipping_courier = $validated['shipping_courier'];
77
+        $order->tracking_number = filled($validated['tracking_number'] ?? null) ? trim($validated['tracking_number']) : null;
78
+        $order->shipped_at ??= now();
79
+        $order->save();
80
+
81
+        if ($firstTime) {
82
+            Mail::to($order->customer_email)->send(new OrderShipped($order));
83
+        }
84
+
85
+        Inertia::flash('toast', ['type' => 'success', 'message' => $firstTime
86
+            ? __('Marked as shipped. We emailed the customer.')
87
+            : __('Shipping details saved.')]);
88
+
89
+        return to_route('stores.orders.show', [$store->slug, $order->id]);
90
+    }
91
+
41 92
     private function ownedStore(Request $request, string $slug): Store
42 93
     {
43 94
         return $request->user()->stores()->where('slug', $slug)->firstOrFail();

+ 81
- 0
app/Http/Controllers/StoreSettingsController.php Переглянути файл

@@ -0,0 +1,81 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Models\Store;
6
+use App\Support\MalaysianPhone;
7
+use Illuminate\Http\RedirectResponse;
8
+use Illuminate\Http\Request;
9
+use Illuminate\Validation\ValidationException;
10
+use Inertia\Inertia;
11
+use Inertia\Response;
12
+
13
+/**
14
+ * Store-wide settings that are not part of the design: WhatsApp number and shipping fees.
15
+ */
16
+class StoreSettingsController extends Controller
17
+{
18
+    public function edit(Request $request, string $slug): Response
19
+    {
20
+        $store = $this->ownedStore($request, $slug);
21
+
22
+        return Inertia::render('stores/settings', [
23
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
24
+            'settings' => [
25
+                'whatsapp_number' => $store->whatsapp_number,
26
+                'shipping_west' => self::ringgit($store->shipping_west),
27
+                'shipping_east' => self::ringgit($store->shipping_east),
28
+                'free_shipping_over' => $store->free_shipping_over !== null ? self::ringgit($store->free_shipping_over) : null,
29
+            ],
30
+        ]);
31
+    }
32
+
33
+    public function update(Request $request, string $slug): RedirectResponse
34
+    {
35
+        $store = $this->ownedStore($request, $slug);
36
+
37
+        $validated = $request->validate([
38
+            'whatsapp_number' => ['nullable', 'string', 'max:30'],
39
+            'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
40
+            'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
41
+            'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
42
+        ]);
43
+
44
+        $whatsapp = null;
45
+
46
+        if (filled($validated['whatsapp_number'] ?? null)) {
47
+            $whatsapp = MalaysianPhone::normalize($validated['whatsapp_number']);
48
+
49
+            if ($whatsapp === null) {
50
+                throw ValidationException::withMessages([
51
+                    'whatsapp_number' => __('Enter a Malaysian mobile number, such as 012-345 6789.'),
52
+                ]);
53
+            }
54
+        }
55
+
56
+        $store->whatsapp_number = $whatsapp;
57
+        $store->shipping_west = self::sen($validated['shipping_west']);
58
+        $store->shipping_east = self::sen($validated['shipping_east']);
59
+        $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
60
+        $store->save();
61
+
62
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
63
+
64
+        return to_route('stores.settings', $store->slug);
65
+    }
66
+
67
+    private static function sen(mixed $ringgit): int
68
+    {
69
+        return (int) round(((float) $ringgit) * 100);
70
+    }
71
+
72
+    private static function ringgit(int $sen): string
73
+    {
74
+        return number_format($sen / 100, 2, '.', '');
75
+    }
76
+
77
+    private function ownedStore(Request $request, string $slug): Store
78
+    {
79
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
80
+    }
81
+}

+ 43
- 0
app/Mail/OrderShipped.php Переглянути файл

@@ -0,0 +1,43 @@
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 when the merchant marks their order as shipped. Written in the store's language.
14
+ */
15
+class OrderShipped 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} telah dihantar - {$store->name}"
28
+                : "Order #{$this->order->number} is on its way - {$store->name}",
29
+        );
30
+    }
31
+
32
+    public function content(): Content
33
+    {
34
+        return new Content(
35
+            markdown: 'mail.orders.shipped',
36
+            with: [
37
+                'order' => $this->order->loadMissing('items'),
38
+                'store' => $this->order->store,
39
+                'malay' => $this->order->store->language->value === 'ms',
40
+            ],
41
+        );
42
+    }
43
+}

+ 7
- 0
app/Models/Order.php Переглянути файл

@@ -34,6 +34,9 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
34 34
  * @property string|null $payment_checkout_id
35 35
  * @property string|null $payment_reference
36 36
  * @property CarbonInterface|null $paid_at
37
+ * @property CarbonInterface|null $shipped_at
38
+ * @property string|null $shipping_courier
39
+ * @property string|null $tracking_number
37 40
  * @property CarbonInterface|null $created_at
38 41
  * @property CarbonInterface|null $updated_at
39 42
  * @property-read Store $store
@@ -86,6 +89,9 @@ class Order extends Model
86 89
             'shipping_total' => $this->shipping_total / 100,
87 90
             'total' => $this->total / 100,
88 91
             'paid_at' => $this->paid_at?->toIso8601String(),
92
+            'shipped_at' => $this->shipped_at?->toIso8601String(),
93
+            'shipping_courier' => $this->shipping_courier,
94
+            'tracking_number' => $this->tracking_number,
89 95
             'created_at' => $this->created_at?->toIso8601String(),
90 96
             'items' => $this->items->map(fn (OrderItem $item) => [
91 97
                 'id' => $item->id,
@@ -106,6 +112,7 @@ class Order extends Model
106 112
             'status' => OrderStatus::class,
107 113
             'shipping_address' => 'array',
108 114
             'paid_at' => 'datetime',
115
+            'shipped_at' => 'datetime',
109 116
         ];
110 117
     }
111 118
 }

+ 11
- 1
app/Models/Store.php Переглянути файл

@@ -28,6 +28,10 @@ use Illuminate\Support\Str;
28 28
  * @property StoreLanguage $language
29 29
  * @property StoreStatus $status
30 30
  * @property array<string, mixed>|null $plan
31
+ * @property string|null $whatsapp_number
32
+ * @property int $shipping_west
33
+ * @property int $shipping_east
34
+ * @property int|null $free_shipping_over
31 35
  * @property array<string, mixed>|null $published_plan
32 36
  * @property CarbonInterface|null $published_at
33 37
  * @property Carbon|null $created_at
@@ -52,11 +56,14 @@ class Store extends Model
52 56
     /**
53 57
      * Default values for new stores.
54 58
      *
55
-     * @var array<string, string>
59
+     * @var array<string, string|int>
56 60
      */
57 61
     protected $attributes = [
58 62
         'language' => 'en',
59 63
         'status' => 'draft',
64
+        // Starting shipping fees in sen, so a new store has sensible numbers before the merchant changes them.
65
+        'shipping_west' => 800,
66
+        'shipping_east' => 1500,
60 67
     ];
61 68
 
62 69
     protected static function booted(): void
@@ -160,6 +167,9 @@ class Store extends Model
160 167
             'plan' => 'array',
161 168
             'published_plan' => 'array',
162 169
             'published_at' => 'datetime',
170
+            'shipping_west' => 'integer',
171
+            'shipping_east' => 'integer',
172
+            'free_shipping_over' => 'integer',
163 173
         ];
164 174
     }
165 175
 }

+ 3
- 0
app/Providers/AppServiceProvider.php Переглянути файл

@@ -6,6 +6,8 @@ use App\Billing\StripeSubscriptionGateway;
6 6
 use App\Billing\SubscriptionGateway;
7 7
 use App\Commerce\Payments\PaymentGateway;
8 8
 use App\Commerce\Payments\StripeGateway;
9
+use App\Commerce\Shipping\FlatRateShipping;
10
+use App\Commerce\Shipping\ShippingProvider;
9 11
 use Carbon\CarbonImmutable;
10 12
 use Illuminate\Support\Facades\Date;
11 13
 use Illuminate\Support\Facades\DB;
@@ -22,6 +24,7 @@ class AppServiceProvider extends ServiceProvider
22 24
         // Payments go through one interface, so the provider can be changed in one place.
23 25
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
24 26
         $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
27
+        $this->app->bind(ShippingProvider::class, FlatRateShipping::class);
25 28
     }
26 29
 
27 30
     /**

+ 69
- 0
app/Storefront/StorefrontText.php Переглянути файл

@@ -0,0 +1,69 @@
1
+<?php
2
+
3
+namespace App\Storefront;
4
+
5
+/**
6
+ * Messages the server shows to shoppers, in the store's language.
7
+ * The words drawn by the browser live in resources/js/storefront/text.ts.
8
+ */
9
+final class StorefrontText
10
+{
11
+    private const array LINES = [
12
+        'en' => [
13
+            'cart_empty' => 'Your cart is empty.',
14
+            'minimum_total' => 'The order total must be at least RM 2.00.',
15
+            'sold_out' => 'This product is sold out.',
16
+            'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
17
+        ],
18
+        'ms' => [
19
+            'cart_empty' => 'Troli anda kosong.',
20
+            'minimum_total' => 'Jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
21
+            'sold_out' => 'Produk ini telah habis dijual.',
22
+            'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',
23
+        ],
24
+    ];
25
+
26
+    public static function line(string $language, string $key): string
27
+    {
28
+        return self::LINES[$language][$key] ?? self::LINES['en'][$key];
29
+    }
30
+
31
+    /**
32
+     * Messages for the checkout form's checks.
33
+     *
34
+     * @return array<string, string>
35
+     */
36
+    public static function checkoutMessages(string $language): array
37
+    {
38
+        if ($language === 'ms') {
39
+            return [
40
+                'required' => ':attribute diperlukan.',
41
+                'string' => ':attribute tidak sah.',
42
+                'email' => ':attribute mestilah alamat e-mel yang sah.',
43
+                'min' => ':attribute mestilah sekurang-kurangnya :min aksara.',
44
+                'max' => ':attribute tidak boleh melebihi :max aksara.',
45
+                'phone.regex' => 'Sila masukkan nombor telefon yang sah.',
46
+                'postcode.regex' => 'Poskod mestilah 5 digit.',
47
+                'state.in' => 'Sila pilih negeri.',
48
+            ];
49
+        }
50
+
51
+        return [
52
+            'phone.regex' => 'Please enter a valid phone number.',
53
+            'postcode.regex' => 'The postcode must be 5 digits.',
54
+            'state.in' => 'Please choose a state.',
55
+        ];
56
+    }
57
+
58
+    /**
59
+     * How the checkout fields are named inside those messages.
60
+     *
61
+     * @return array<string, string>
62
+     */
63
+    public static function checkoutFields(string $language): array
64
+    {
65
+        return $language === 'ms'
66
+            ? ['name' => 'Nama penuh', 'email' => 'E-mel', 'phone' => 'Nombor telefon', 'line1' => 'Alamat', 'line2' => 'Alamat baris 2', 'city' => 'Bandar', 'postcode' => 'Poskod', 'state' => 'Negeri']
67
+            : ['name' => 'full name', 'email' => 'email', 'phone' => 'phone number', 'line1' => 'address', 'line2' => 'address line 2', 'city' => 'city', 'postcode' => 'postcode', 'state' => 'state'];
68
+    }
69
+}

+ 35
- 0
app/Support/MalaysianPhone.php Переглянути файл

@@ -0,0 +1,35 @@
1
+<?php
2
+
3
+namespace App\Support;
4
+
5
+/**
6
+ * Turns Malaysian phone numbers as people type them ("012-345 6789", "+60 12 345 6789")
7
+ * into the digits-only form WhatsApp links need ("60123456789").
8
+ */
9
+final class MalaysianPhone
10
+{
11
+    public static function normalize(?string $phone): ?string
12
+    {
13
+        $digits = preg_replace('/\D/', '', (string) $phone) ?? '';
14
+
15
+        if (str_starts_with($digits, '0')) {
16
+            // Local form: 012-345 6789.
17
+            $digits = '6'.$digits;
18
+        } elseif (str_starts_with($digits, '1') && strlen($digits) >= 9 && strlen($digits) <= 10) {
19
+            // Mobile number typed without the leading 0: 12-345 6789.
20
+            $digits = '60'.$digits;
21
+        }
22
+
23
+        // Anything else must already carry Malaysia's country code (60). Other countries are refused.
24
+
25
+        return preg_match('/^60[1-9][0-9]{7,9}$/', $digits) === 1 ? $digits : null;
26
+    }
27
+
28
+    /**
29
+     * A WhatsApp chat link, optionally with a message already typed in.
30
+     */
31
+    public static function whatsappLink(string $number, ?string $text = null): string
32
+    {
33
+        return 'https://wa.me/'.$number.($text !== null ? '?text='.rawurlencode($text) : '');
34
+    }
35
+}

+ 38
- 0
database/migrations/2026_11_16_000000_add_shipping_and_whatsapp.php Переглянути файл

@@ -0,0 +1,38 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        Schema::table('stores', function (Blueprint $table) {
12
+            // Digits only, with country code, such as 60123456789.
13
+            $table->string('whatsapp_number', 20)->nullable()->after('language');
14
+            // Flat shipping fees in sen. "West" is Peninsular Malaysia; "east" is Sabah, Sarawak and Labuan.
15
+            $table->unsignedInteger('shipping_west')->default(800)->after('whatsapp_number');
16
+            $table->unsignedInteger('shipping_east')->default(1500)->after('shipping_west');
17
+            // Orders at or above this subtotal ship free. Null means never free.
18
+            $table->unsignedInteger('free_shipping_over')->nullable()->after('shipping_east');
19
+        });
20
+
21
+        Schema::table('orders', function (Blueprint $table) {
22
+            $table->timestamp('shipped_at')->nullable()->after('paid_at');
23
+            $table->string('shipping_courier', 60)->nullable()->after('shipped_at');
24
+            $table->string('tracking_number', 80)->nullable()->after('shipping_courier');
25
+        });
26
+    }
27
+
28
+    public function down(): void
29
+    {
30
+        Schema::table('orders', function (Blueprint $table) {
31
+            $table->dropColumn(['shipped_at', 'shipping_courier', 'tracking_number']);
32
+        });
33
+
34
+        Schema::table('stores', function (Blueprint $table) {
35
+            $table->dropColumn(['whatsapp_number', 'shipping_west', 'shipping_east', 'free_shipping_over']);
36
+        });
37
+    }
38
+};

+ 7
- 1
resources/js/components/stores/store-nav.tsx Переглянути файл

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

+ 8
- 0
resources/js/pages/stores/orders/index.tsx Переглянути файл

@@ -115,6 +115,14 @@ export default function OrdersIndex({
115 115
                                             >
116 116
                                                 {order.status_label}
117 117
                                             </Badge>
118
+                                            {order.shipped_at && (
119
+                                                <Badge
120
+                                                    variant="outline"
121
+                                                    className="ml-1.5"
122
+                                                >
123
+                                                    Shipped
124
+                                                </Badge>
125
+                                            )}
118 126
                                         </td>
119 127
                                         <td className="px-4 py-3 text-right tabular-nums">
120 128
                                             {formatRinggit(order.total)}

+ 148
- 1
resources/js/pages/stores/orders/show.tsx Переглянути файл

@@ -1,18 +1,33 @@
1
-import { Head, Link } from '@inertiajs/react';
1
+import { Form, Head, Link } from '@inertiajs/react';
2
+import { MessageCircle, Truck } from 'lucide-react';
2 3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
4
+import InputError from '@/components/input-error';
3 5
 import { Badge } from '@/components/ui/badge';
6
+import { Button } from '@/components/ui/button';
4 7
 import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
8
+import { Input } from '@/components/ui/input';
9
+import { Label } from '@/components/ui/label';
5 10
 import { formatDateTime, formatRinggit } from '@/lib/money';
6 11
 import { dashboard } from '@/routes';
7 12
 import type { Order, StoreSummary } from '@/types';
8 13
 
14
+const fieldClass =
15
+    'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm';
16
+
9 17
 export default function ShowOrder({
10 18
     store,
11 19
     order,
20
+    couriers,
21
+    customer_whatsapp_url,
12 22
 }: {
13 23
     store: StoreSummary;
14 24
     order: Order;
25
+    couriers: string[];
26
+    customer_whatsapp_url: string | null;
15 27
 }) {
28
+    const paid = order.status === 'paid';
29
+    const shipped = order.shipped_at !== null;
30
+
16 31
     const address = order.shipping_address;
17 32
 
18 33
     return (
@@ -42,6 +57,7 @@ export default function ShowOrder({
42 57
                         >
43 58
                             {order.status_label}
44 59
                         </Badge>
60
+                        {shipped && <Badge variant="outline">Shipped</Badge>}
45 61
                     </div>
46 62
                     <p className="text-sm text-muted-foreground">
47 63
                         Placed {formatDateTime(order.created_at)}
@@ -75,6 +91,22 @@ export default function ShowOrder({
75 91
                                 </li>
76 92
                             ))}
77 93
                         </ul>
94
+                        <div className="mt-3 space-y-1.5 border-t pt-3 text-sm">
95
+                            <div className="flex justify-between gap-4">
96
+                                <span>Subtotal</span>
97
+                                <span className="tabular-nums">
98
+                                    {formatRinggit(order.subtotal)}
99
+                                </span>
100
+                            </div>
101
+                            <div className="flex justify-between gap-4">
102
+                                <span>Shipping</span>
103
+                                <span className="tabular-nums">
104
+                                    {order.shipping_total === 0
105
+                                        ? 'Free'
106
+                                        : formatRinggit(order.shipping_total)}
107
+                                </span>
108
+                            </div>
109
+                        </div>
78 110
                         <div className="mt-3 flex justify-between gap-4 border-t pt-3 font-medium">
79 111
                             <span>Total</span>
80 112
                             <span className="tabular-nums">
@@ -100,6 +132,23 @@ export default function ShowOrder({
100 132
                                 </a>
101 133
                             </p>
102 134
                             <p>{order.customer_phone}</p>
135
+                            {customer_whatsapp_url && (
136
+                                <Button
137
+                                    variant="outline"
138
+                                    size="sm"
139
+                                    className="mt-2"
140
+                                    asChild
141
+                                >
142
+                                    <a
143
+                                        href={customer_whatsapp_url}
144
+                                        target="_blank"
145
+                                        rel="noreferrer"
146
+                                    >
147
+                                        <MessageCircle />
148
+                                        WhatsApp customer
149
+                                    </a>
150
+                                </Button>
151
+                            )}
103 152
                         </CardContent>
104 153
                     </Card>
105 154
 
@@ -119,6 +168,104 @@ export default function ShowOrder({
119 168
                         </CardContent>
120 169
                     </Card>
121 170
                 </div>
171
+
172
+                {paid && (
173
+                    <Card data-test="ship-order-card">
174
+                        <CardHeader>
175
+                            <CardTitle className="flex items-center gap-2">
176
+                                <Truck className="size-5" />
177
+                                {shipped ? 'Shipped' : 'Ship this order'}
178
+                            </CardTitle>
179
+                        </CardHeader>
180
+                        <CardContent>
181
+                            {shipped && (
182
+                                <p className="mb-4 text-sm text-muted-foreground">
183
+                                    Shipped {formatDateTime(order.shipped_at)}{' '}
184
+                                    with {order.shipping_courier}
185
+                                    {order.tracking_number
186
+                                        ? `, tracking ${order.tracking_number}`
187
+                                        : ''}
188
+                                    . You can correct the details below; the
189
+                                    customer is not emailed again.
190
+                                </p>
191
+                            )}
192
+                            <Form
193
+                                {...OrderController.ship.form({
194
+                                    slug: store.slug,
195
+                                    order: order.id,
196
+                                })}
197
+                                options={{ preserveScroll: true }}
198
+                                className="space-y-4"
199
+                            >
200
+                                {({ processing, errors }) => (
201
+                                    <>
202
+                                        <div className="grid gap-4 sm:grid-cols-2">
203
+                                            <div className="grid gap-2">
204
+                                                <Label htmlFor="shipping_courier">
205
+                                                    Courier
206
+                                                </Label>
207
+                                                <select
208
+                                                    id="shipping_courier"
209
+                                                    name="shipping_courier"
210
+                                                    required
211
+                                                    defaultValue={
212
+                                                        order.shipping_courier ??
213
+                                                        ''
214
+                                                    }
215
+                                                    className={fieldClass}
216
+                                                >
217
+                                                    <option value="" disabled>
218
+                                                        Choose a courier
219
+                                                    </option>
220
+                                                    {couriers.map((courier) => (
221
+                                                        <option
222
+                                                            key={courier}
223
+                                                            value={courier}
224
+                                                        >
225
+                                                            {courier}
226
+                                                        </option>
227
+                                                    ))}
228
+                                                </select>
229
+                                                <InputError
230
+                                                    message={
231
+                                                        errors.shipping_courier
232
+                                                    }
233
+                                                />
234
+                                            </div>
235
+                                            <div className="grid gap-2">
236
+                                                <Label htmlFor="tracking_number">
237
+                                                    Tracking number (optional)
238
+                                                </Label>
239
+                                                <Input
240
+                                                    id="tracking_number"
241
+                                                    name="tracking_number"
242
+                                                    maxLength={80}
243
+                                                    defaultValue={
244
+                                                        order.tracking_number ??
245
+                                                        ''
246
+                                                    }
247
+                                                />
248
+                                                <InputError
249
+                                                    message={
250
+                                                        errors.tracking_number
251
+                                                    }
252
+                                                />
253
+                                            </div>
254
+                                        </div>
255
+                                        <Button
256
+                                            disabled={processing}
257
+                                            data-test="ship-order-button"
258
+                                        >
259
+                                            {shipped
260
+                                                ? 'Save shipping details'
261
+                                                : 'Mark as shipped and email customer'}
262
+                                        </Button>
263
+                                    </>
264
+                                )}
265
+                            </Form>
266
+                        </CardContent>
267
+                    </Card>
268
+                )}
122 269
             </div>
123 270
         </>
124 271
     );

+ 5
- 0
resources/js/pages/stores/preview.tsx Переглянути файл

@@ -3,6 +3,7 @@ import { StorefrontRenderer } from '@/storefront/renderer';
3 3
 import { fontStylesheetUrl, storefrontTitlePrefix } from '@/storefront/theme';
4 4
 import type {
5 5
     FontMap,
6
+    ShopInfo,
6 7
     StoreCart,
7 8
     StorePlan,
8 9
     StoreProduct,
@@ -19,6 +20,7 @@ export default function PreviewStore({
19 20
     view,
20 21
     products,
21 22
     cart,
23
+    shop,
22 24
 }: {
23 25
     storeName: string;
24 26
     language: string;
@@ -30,6 +32,7 @@ export default function PreviewStore({
30 32
     view: StorefrontView;
31 33
     products: StoreProduct[];
32 34
     cart: StoreCart;
35
+    shop: ShopInfo;
33 36
 }) {
34 37
     const fontUrl = fontStylesheetUrl(plan.theme, fonts);
35 38
     const page =
@@ -63,6 +66,8 @@ export default function PreviewStore({
63 66
                 language={language}
64 67
                 products={products}
65 68
                 cart={cart}
69
+                storeName={storeName}
70
+                shop={shop}
66 71
             />
67 72
         </>
68 73
     );

+ 185
- 0
resources/js/pages/stores/settings.tsx Переглянути файл

@@ -0,0 +1,185 @@
1
+import { Form, Head, Link } from '@inertiajs/react';
2
+import StoreController from '@/actions/App/Http/Controllers/StoreController';
3
+import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
4
+import InputError from '@/components/input-error';
5
+import StoreNav from '@/components/stores/store-nav';
6
+import { Button } from '@/components/ui/button';
7
+import {
8
+    Card,
9
+    CardContent,
10
+    CardDescription,
11
+    CardHeader,
12
+    CardTitle,
13
+} from '@/components/ui/card';
14
+import { Input } from '@/components/ui/input';
15
+import { Label } from '@/components/ui/label';
16
+import { dashboard } from '@/routes';
17
+import type { StoreSummary } from '@/types';
18
+
19
+type Settings = {
20
+    whatsapp_number: string | null;
21
+    shipping_west: string;
22
+    shipping_east: string;
23
+    free_shipping_over: string | null;
24
+};
25
+
26
+export default function StoreSettings({
27
+    store,
28
+    settings,
29
+}: {
30
+    store: StoreSummary;
31
+    settings: Settings;
32
+}) {
33
+    return (
34
+        <>
35
+            <Head title={`Settings - ${store.name}`} />
36
+
37
+            <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
38
+                <div>
39
+                    <h1 className="text-xl font-semibold">{store.name}</h1>
40
+                    <p className="text-sm text-muted-foreground">
41
+                        <Link
42
+                            href={StoreController.show.url(store.slug)}
43
+                            className="hover:underline"
44
+                        >
45
+                            Back to store
46
+                        </Link>
47
+                    </p>
48
+                </div>
49
+
50
+                <StoreNav slug={store.slug} current="settings" />
51
+
52
+                <Form
53
+                    {...StoreSettingsController.update.form(store.slug)}
54
+                    options={{ preserveScroll: true }}
55
+                    className="max-w-2xl space-y-6"
56
+                >
57
+                    {({ processing, errors }) => (
58
+                        <>
59
+                            <Card>
60
+                                <CardHeader>
61
+                                    <CardTitle>WhatsApp</CardTitle>
62
+                                    <CardDescription>
63
+                                        Shoppers see a WhatsApp chat button on
64
+                                        every page of your store, and on their
65
+                                        order page. Leave empty to hide it.
66
+                                    </CardDescription>
67
+                                </CardHeader>
68
+                                <CardContent className="grid gap-2">
69
+                                    <Label htmlFor="whatsapp_number">
70
+                                        WhatsApp number
71
+                                    </Label>
72
+                                    <Input
73
+                                        id="whatsapp_number"
74
+                                        name="whatsapp_number"
75
+                                        type="tel"
76
+                                        inputMode="tel"
77
+                                        maxLength={30}
78
+                                        defaultValue={
79
+                                            settings.whatsapp_number ?? ''
80
+                                        }
81
+                                        placeholder="012-345 6789"
82
+                                    />
83
+                                    <InputError
84
+                                        message={errors.whatsapp_number}
85
+                                    />
86
+                                </CardContent>
87
+                            </Card>
88
+
89
+                            <Card>
90
+                                <CardHeader>
91
+                                    <CardTitle>Shipping fees</CardTitle>
92
+                                    <CardDescription>
93
+                                        Added at checkout, based on the
94
+                                        shopper&rsquo;s state.
95
+                                    </CardDescription>
96
+                                </CardHeader>
97
+                                <CardContent className="space-y-5">
98
+                                    <div className="grid gap-5 sm:grid-cols-2">
99
+                                        <div className="grid gap-2">
100
+                                            <Label htmlFor="shipping_west">
101
+                                                Peninsular Malaysia (RM)
102
+                                            </Label>
103
+                                            <Input
104
+                                                id="shipping_west"
105
+                                                name="shipping_west"
106
+                                                inputMode="decimal"
107
+                                                required
108
+                                                defaultValue={
109
+                                                    settings.shipping_west
110
+                                                }
111
+                                            />
112
+                                            <InputError
113
+                                                message={errors.shipping_west}
114
+                                            />
115
+                                        </div>
116
+                                        <div className="grid gap-2">
117
+                                            <Label htmlFor="shipping_east">
118
+                                                Sabah, Sarawak and Labuan (RM)
119
+                                            </Label>
120
+                                            <Input
121
+                                                id="shipping_east"
122
+                                                name="shipping_east"
123
+                                                inputMode="decimal"
124
+                                                required
125
+                                                defaultValue={
126
+                                                    settings.shipping_east
127
+                                                }
128
+                                            />
129
+                                            <InputError
130
+                                                message={errors.shipping_east}
131
+                                            />
132
+                                        </div>
133
+                                    </div>
134
+
135
+                                    <div className="grid gap-2 sm:max-w-[calc(50%-0.625rem)]">
136
+                                        <Label htmlFor="free_shipping_over">
137
+                                            Free shipping on orders over (RM,
138
+                                            optional)
139
+                                        </Label>
140
+                                        <Input
141
+                                            id="free_shipping_over"
142
+                                            name="free_shipping_over"
143
+                                            inputMode="decimal"
144
+                                            defaultValue={
145
+                                                settings.free_shipping_over ??
146
+                                                ''
147
+                                            }
148
+                                            placeholder="100.00"
149
+                                            aria-describedby="free-help"
150
+                                        />
151
+                                        <p
152
+                                            id="free-help"
153
+                                            className="text-xs text-muted-foreground"
154
+                                        >
155
+                                            Leave empty to always charge
156
+                                            shipping. Enter 0 to always ship
157
+                                            free.
158
+                                        </p>
159
+                                        <InputError
160
+                                            message={errors.free_shipping_over}
161
+                                        />
162
+                                    </div>
163
+                                </CardContent>
164
+                            </Card>
165
+
166
+                            <Button
167
+                                disabled={processing}
168
+                                data-test="save-settings-button"
169
+                            >
170
+                                Save settings
171
+                            </Button>
172
+                        </>
173
+                    )}
174
+                </Form>
175
+            </div>
176
+        </>
177
+    );
178
+}
179
+
180
+StoreSettings.layout = {
181
+    breadcrumbs: [
182
+        { title: 'Dashboard', href: dashboard() },
183
+        { title: 'Settings', href: '#' },
184
+    ],
185
+};

+ 10
- 3
resources/js/storefront/context.tsx Переглянути файл

@@ -1,5 +1,5 @@
1 1
 import { createContext, useContext } from 'react';
2
-import type { StoreCart, StoreProduct } from './types';
2
+import type { ShopInfo, 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. */
@@ -10,6 +10,8 @@ export type Storefront = {
10 10
     /** The merchant's real products that shoppers may see. */
11 11
     products: StoreProduct[];
12 12
     cart: StoreCart;
13
+    storeName: string;
14
+    shop: ShopInfo;
13 15
 };
14 16
 
15 17
 const StorefrontContext = createContext<Storefront>({
@@ -18,6 +20,8 @@ const StorefrontContext = createContext<Storefront>({
18 20
     language: 'en',
19 21
     products: [],
20 22
     cart: { count: 0, subtotal: 0, adjusted: false, lines: [] },
23
+    storeName: '',
24
+    shop: { whatsapp: null, free_shipping_over: null },
21 25
 });
22 26
 
23 27
 export const StorefrontProvider = StorefrontContext.Provider;
@@ -38,16 +42,19 @@ export function resolveHref(
38 42
     baseUrl: string,
39 43
     isHome: boolean,
40 44
 ): string {
45
+    // A live store's home page is "/"; in the owner's preview it is the preview address.
46
+    const home = baseUrl || '/';
47
+
41 48
     if (href.startsWith('#')) {
42 49
         if (isHome) {
43 50
             return href;
44 51
         }
45 52
 
46
-        return href === '#' ? baseUrl : baseUrl + href;
53
+        return href === '#' ? home : home + href;
47 54
     }
48 55
 
49 56
     if (href.startsWith('/')) {
50
-        return href === '/' ? baseUrl : baseUrl + href;
57
+        return href === '/' ? home : baseUrl + href;
51 58
     }
52 59
 
53 60
     return href;

+ 17
- 1
resources/js/storefront/pages/cart.tsx Переглянути файл

@@ -10,8 +10,16 @@ import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
10 10
 
11 11
 /** The shopper's cart. Built by us, in the store's colours and fonts. */
12 12
 export function CartPage() {
13
-    const { cart, language, baseUrl } = useStorefront();
13
+    const { cart, language, baseUrl, shop } = useStorefront();
14
+
14 15
     const t = storefrontText(language);
16
+    const freeOver = shop.free_shipping_over;
17
+    const freeShippingNote =
18
+        freeOver === null || freeOver === 0
19
+            ? null
20
+            : cart.subtotal >= freeOver
21
+              ? t.youGetFreeShipping
22
+              : t.spendMoreForFree(formatPrice(freeOver - cart.subtotal));
15 23
     const [busy, setBusy] = useState(false);
16 24
 
17 25
     function change(line: CartLine, quantity: number) {
@@ -140,6 +148,14 @@ export function CartPage() {
140 148
                             <p className="mt-2 text-sm text-(--sf-muted)">
141 149
                                 {t.shippingNote}
142 150
                             </p>
151
+                            {freeShippingNote && (
152
+                                <p
153
+                                    className="mt-2 text-sm font-medium"
154
+                                    data-test="free-shipping-note"
155
+                                >
156
+                                    {freeShippingNote}
157
+                                </p>
158
+                            )}
143 159
 
144 160
                             <SfButton
145 161
                                 href="/checkout"

+ 39
- 3
resources/js/storefront/pages/checkout.tsx Переглянути файл

@@ -35,7 +35,13 @@ function Field({
35 35
 }
36 36
 
37 37
 /** The shopper's details and address, before going to the payment page. */
38
-export function CheckoutPage({ states }: { states: string[] }) {
38
+export function CheckoutPage({
39
+    states,
40
+    shippingByState,
41
+}: {
42
+    states: string[];
43
+    shippingByState: Record<string, number>;
44
+}) {
39 45
     const { cart, language, baseUrl } = useStorefront();
40 46
     const t = storefrontText(language);
41 47
     const form = useForm({
@@ -51,6 +57,10 @@ export function CheckoutPage({ states }: { states: string[] }) {
51 57
     // "cart" errors come from the server: an empty cart, or the payment page could not be opened.
52 58
     const errors = form.errors as typeof form.errors & { cart?: string };
53 59
 
60
+    const shipping = form.data.state
61
+        ? (shippingByState[form.data.state] ?? null)
62
+        : null;
63
+
54 64
     function submit(event: FormEvent) {
55 65
         event.preventDefault();
56 66
         form.post(`${baseUrl}/checkout`, { preserveScroll: true });
@@ -217,10 +227,36 @@ export function CheckoutPage({ states }: { states: string[] }) {
217 227
                                 </li>
218 228
                             ))}
219 229
                         </ul>
220
-                        <div className="mt-5 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
230
+                        <div className="mt-5 space-y-2 border-t border-(--sf-border) pt-4 text-sm">
231
+                            <div className="flex justify-between gap-4">
232
+                                <span>{t.subtotal}</span>
233
+                                <span className="tabular-nums">
234
+                                    {formatPrice(cart.subtotal)}
235
+                                </span>
236
+                            </div>
237
+                            <div className="flex justify-between gap-4">
238
+                                <span>{t.shipping}</span>
239
+                                <span
240
+                                    className="tabular-nums"
241
+                                    aria-live="polite"
242
+                                >
243
+                                    {shipping === null
244
+                                        ? '—'
245
+                                        : shipping === 0
246
+                                          ? t.shippingFree
247
+                                          : formatPrice(shipping)}
248
+                                </span>
249
+                            </div>
250
+                            {shipping === null && (
251
+                                <p className="text-xs text-(--sf-muted)">
252
+                                    {t.chooseStateForShipping}
253
+                                </p>
254
+                            )}
255
+                        </div>
256
+                        <div className="mt-4 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
221 257
                             <span className="font-medium">{t.total}</span>
222 258
                             <span className="text-xl font-semibold tabular-nums">
223
-                                {formatPrice(cart.subtotal)}
259
+                                {formatPrice(cart.subtotal + (shipping ?? 0))}
224 260
                             </span>
225 261
                         </div>
226 262
                     </aside>

+ 56
- 5
resources/js/storefront/pages/order.tsx Переглянути файл

@@ -3,10 +3,11 @@ import { storefrontText } from '../text';
3 3
 import { formatPrice } from '../theme';
4 4
 import type { StoreOrder } from '../types';
5 5
 import { Container, SfButton } from '../ui';
6
+import { whatsappLink } from '../whatsapp';
6 7
 
7 8
 /** Where the shopper lands after the payment page: a thank-you, or a "not paid yet" notice. */
8 9
 export function OrderPage({ order }: { order: StoreOrder }) {
9
-    const { language } = useStorefront();
10
+    const { language, shop, storeName } = useStorefront();
10 11
     const t = storefrontText(language);
11 12
     const paid = order.status === 'paid';
12 13
     const address = order.shipping_address;
@@ -43,7 +44,23 @@ export function OrderPage({ order }: { order: StoreOrder }) {
43 44
                             </li>
44 45
                         ))}
45 46
                     </ul>
46
-                    <div className="mt-5 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
47
+                    <div className="mt-5 space-y-2 border-t border-(--sf-border) pt-4 text-sm">
48
+                        <div className="flex justify-between gap-4">
49
+                            <span>{t.subtotal}</span>
50
+                            <span className="tabular-nums">
51
+                                {formatPrice(order.subtotal)}
52
+                            </span>
53
+                        </div>
54
+                        <div className="flex justify-between gap-4">
55
+                            <span>{t.shipping}</span>
56
+                            <span className="tabular-nums">
57
+                                {order.shipping_total === 0
58
+                                    ? t.shippingFree
59
+                                    : formatPrice(order.shipping_total)}
60
+                            </span>
61
+                        </div>
62
+                    </div>
63
+                    <div className="mt-4 flex items-baseline justify-between gap-4 border-t border-(--sf-border) pt-4">
47 64
                         <span className="font-medium">{t.total}</span>
48 65
                         <span className="text-xl font-semibold tabular-nums">
49 66
                             {formatPrice(order.total)}
@@ -61,9 +78,43 @@ export function OrderPage({ order }: { order: StoreOrder }) {
61 78
                     </address>
62 79
                 </div>
63 80
 
64
-                <SfButton href={paid ? '/shop' : '/cart'} className="mt-8">
65
-                    {paid ? t.continueShopping : t.backToCart}
66
-                </SfButton>
81
+                {order.shipped_at && order.shipping_courier && (
82
+                    <div
83
+                        className="mt-6 rounded-(--sf-radius-card) border border-(--sf-border) p-5 text-sm"
84
+                        data-test="order-shipped"
85
+                    >
86
+                        <p className="font-medium">
87
+                            {t.shippedVia(order.shipping_courier)}
88
+                        </p>
89
+                        {order.tracking_number && (
90
+                            <p className="mt-1 text-(--sf-muted)">
91
+                                {t.trackingNumber}:{' '}
92
+                                <span className="font-mono text-(--sf-fg)">
93
+                                    {order.tracking_number}
94
+                                </span>
95
+                            </p>
96
+                        )}
97
+                    </div>
98
+                )}
99
+
100
+                <div className="mt-8 flex flex-wrap items-center gap-3">
101
+                    <SfButton href={paid ? '/shop' : '/cart'}>
102
+                        {paid ? t.continueShopping : t.backToCart}
103
+                    </SfButton>
104
+                    {shop.whatsapp && (
105
+                        <a
106
+                            href={whatsappLink(
107
+                                shop.whatsapp,
108
+                                t.whatsAppOrder(storeName, order.number),
109
+                            )}
110
+                            target="_blank"
111
+                            rel="noreferrer"
112
+                            className="inline-flex items-center justify-center rounded-(--sf-radius) border border-(--sf-border) px-5 py-2.5 text-sm font-semibold transition-colors hover:bg-(--sf-surface)"
113
+                        >
114
+                            {t.askAboutOrder}
115
+                        </a>
116
+                    )}
117
+                </div>
67 118
             </Container>
68 119
         </main>
69 120
     );

+ 24
- 2
resources/js/storefront/renderer.tsx Переглянути файл

@@ -16,9 +16,11 @@ import { Newsletter } from './sections/newsletter';
16 16
 import { ProductGrid } from './sections/product-grid';
17 17
 import { Testimonials } from './sections/testimonials';
18 18
 import { themeStyle } from './theme';
19
+import { WhatsAppButton } from './whatsapp';
19 20
 import type {
20 21
     FontMap,
21 22
     PlanSection,
23
+    ShopInfo,
22 24
     StoreCart,
23 25
     StorePlan,
24 26
     StoreProduct,
@@ -63,7 +65,12 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
63 65
     }
64 66
 
65 67
     if (view.type === 'checkout') {
66
-        return <CheckoutPage states={view.states} />;
68
+        return (
69
+            <CheckoutPage
70
+                states={view.states}
71
+                shippingByState={view.shippingByState}
72
+            />
73
+        );
67 74
     }
68 75
 
69 76
     if (view.type === 'order') {
@@ -102,6 +109,8 @@ export function StorefrontRenderer({
102 109
     language,
103 110
     products,
104 111
     cart,
112
+    storeName,
113
+    shop,
105 114
 }: {
106 115
     plan: StorePlan;
107 116
     fonts: FontMap;
@@ -110,12 +119,22 @@ export function StorefrontRenderer({
110 119
     language: string;
111 120
     products: StoreProduct[];
112 121
     cart: StoreCart;
122
+    storeName: string;
123
+    shop: ShopInfo;
113 124
 }): ReactNode {
114 125
     const isHome = view.type === 'page' && view.pageId === 'home';
115 126
 
116 127
     return (
117 128
         <StorefrontProvider
118
-            value={{ baseUrl, isHome, language, products, cart }}
129
+            value={{
130
+                baseUrl,
131
+                isHome,
132
+                language,
133
+                products,
134
+                cart,
135
+                storeName,
136
+                shop,
137
+            }}
119 138
         >
120 139
             <div
121 140
                 className="sf-root flex min-h-screen flex-col"
@@ -126,6 +145,9 @@ export function StorefrontRenderer({
126 145
                     <PageBody plan={plan} view={view} />
127 146
                 </div>
128 147
                 <Footer section={plan.footer} />
148
+                {/* Room under the footer so the WhatsApp button never covers its links. */}
149
+                {shop.whatsapp && <div className="h-20" aria-hidden="true" />}
150
+                <WhatsAppButton />
129 151
             </div>
130 152
         </StorefrontProvider>
131 153
     );

+ 31
- 0
resources/js/storefront/text.ts Переглянути файл

@@ -48,6 +48,21 @@ const words = {
48 48
             `Order #${number} has not been paid yet. Your cart is still saved, so you can try again.`,
49 49
         deliverTo: 'Deliver to',
50 50
         quantityShort: 'Qty',
51
+        shipping: 'Shipping',
52
+        shippingFree: 'Free',
53
+        chooseStateForShipping: 'Choose your state to see the shipping fee.',
54
+        freeShippingOver: (amount: string) =>
55
+            `Free shipping on orders over ${amount}.`,
56
+        spendMoreForFree: (amount: string) =>
57
+            `Add ${amount} more for free shipping.`,
58
+        youGetFreeShipping: 'You get free shipping.',
59
+        shippedVia: (courier: string) => `Shipped with ${courier}.`,
60
+        trackingNumber: 'Tracking number',
61
+        chatOnWhatsApp: 'Chat on WhatsApp',
62
+        askAboutOrder: 'Ask about this order on WhatsApp',
63
+        whatsAppHello: (store: string) => `Hi ${store}, I have a question.`,
64
+        whatsAppOrder: (store: string, number: number) =>
65
+            `Hi ${store}, I have a question about my order #${number}.`,
51 66
         cartAdjusted:
52 67
             'Some items changed because stock ran low. Please check your cart.',
53 68
         onlyLeft: (count: number) => `Only ${count} left`,
@@ -103,6 +118,22 @@ const words = {
103 118
             `Pesanan #${number} belum dibayar. Troli anda masih disimpan, jadi anda boleh cuba lagi.`,
104 119
         deliverTo: 'Hantar ke',
105 120
         quantityShort: 'Kuantiti',
121
+        shipping: 'Penghantaran',
122
+        shippingFree: 'Percuma',
123
+        chooseStateForShipping:
124
+            'Pilih negeri anda untuk melihat kos penghantaran.',
125
+        freeShippingOver: (amount: string) =>
126
+            `Penghantaran percuma untuk pesanan melebihi ${amount}.`,
127
+        spendMoreForFree: (amount: string) =>
128
+            `Tambah ${amount} lagi untuk penghantaran percuma.`,
129
+        youGetFreeShipping: 'Anda mendapat penghantaran percuma.',
130
+        shippedVia: (courier: string) => `Dihantar melalui ${courier}.`,
131
+        trackingNumber: 'Nombor penjejakan',
132
+        chatOnWhatsApp: 'Sembang di WhatsApp',
133
+        askAboutOrder: 'Tanya tentang pesanan ini di WhatsApp',
134
+        whatsAppHello: (store: string) => `Hai ${store}, saya ada soalan.`,
135
+        whatsAppOrder: (store: string, number: number) =>
136
+            `Hai ${store}, saya ada soalan tentang pesanan saya #${number}.`,
106 137
         cartAdjusted:
107 138
             'Beberapa item berubah kerana stok berkurangan. Sila semak troli anda.',
108 139
         onlyLeft: (count: number) => `Tinggal ${count} sahaja`,

+ 17
- 1
resources/js/storefront/types.ts Переглянути файл

@@ -212,6 +212,9 @@ export type StoreOrder = {
212 212
     shipping_total: number;
213 213
     total: number;
214 214
     paid_at: string | null;
215
+    shipped_at: string | null;
216
+    shipping_courier: string | null;
217
+    tracking_number: string | null;
215 218
     created_at: string | null;
216 219
     items: {
217 220
         id: number;
@@ -222,11 +225,24 @@ export type StoreOrder = {
222 225
     }[];
223 226
 };
224 227
 
228
+/** Store-wide details every page can use. */
229
+export type ShopInfo = {
230
+    /** Digits only with country code, such as 60123456789. */
231
+    whatsapp: string | null;
232
+    /** In ringgit. Orders at or above this ship free. */
233
+    free_shipping_over: number | null;
234
+};
235
+
225 236
 /** Which storefront page to show. */
226 237
 export type StorefrontView =
227 238
     | { type: 'page'; pageId: string }
228 239
     | { type: 'shop' }
229 240
     | { type: 'cart' }
230
-    | { type: 'checkout'; states: string[] }
241
+    | {
242
+          type: 'checkout';
243
+          states: string[];
244
+          /** Shipping fee in ringgit for each state. */
245
+          shippingByState: Record<string, number>;
246
+      }
231 247
     | { type: 'order'; order: StoreOrder }
232 248
     | { type: 'product'; product: StoreProduct };

+ 34
- 0
resources/js/storefront/whatsapp.tsx Переглянути файл

@@ -0,0 +1,34 @@
1
+import { MessageCircle } from 'lucide-react';
2
+import { useStorefront } from './context';
3
+import { storefrontText } from './text';
4
+
5
+export function whatsappLink(number: string, text: string): string {
6
+    return `https://wa.me/${number}?text=${encodeURIComponent(text)}`;
7
+}
8
+
9
+/**
10
+ * A round "chat on WhatsApp" button in the corner of every store page.
11
+ * Shows only when the merchant has set a WhatsApp number.
12
+ */
13
+export function WhatsAppButton() {
14
+    const { shop, language, storeName } = useStorefront();
15
+    const t = storefrontText(language);
16
+
17
+    if (!shop.whatsapp) {
18
+        return null;
19
+    }
20
+
21
+    return (
22
+        <a
23
+            href={whatsappLink(shop.whatsapp, t.whatsAppHello(storeName))}
24
+            target="_blank"
25
+            rel="noreferrer"
26
+            className="fixed right-4 bottom-4 z-30 inline-flex items-center gap-2 rounded-full bg-[#25D366] px-4 py-3 text-sm font-semibold text-[#073B1C] shadow-lg transition-transform hover:scale-105 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#25D366] sm:right-6 sm:bottom-6"
27
+            data-test="whatsapp-button"
28
+        >
29
+            <MessageCircle className="size-5" aria-hidden="true" />
30
+            <span className="hidden sm:inline">{t.chatOnWhatsApp}</span>
31
+            <span className="sr-only sm:hidden">{t.chatOnWhatsApp}</span>
32
+        </a>
33
+    );
34
+}

+ 3
- 0
resources/js/types/store.ts Переглянути файл

@@ -92,6 +92,9 @@ export type Order = {
92 92
     shipping_total: number;
93 93
     total: number;
94 94
     paid_at: string | null;
95
+    shipped_at: string | null;
96
+    shipping_courier: string | null;
97
+    tracking_number: string | null;
95 98
     created_at: string | null;
96 99
     items: {
97 100
         id: number;

+ 1
- 0
resources/views/mail/orders/confirmation.blade.php Переглянути файл

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

+ 31
- 0
resources/views/mail/orders/shipped.blade.php Переглянути файл

@@ -0,0 +1,31 @@
1
+<x-mail::message>
2
+# {{ $malay ? 'Pesanan anda dalam perjalanan' : 'Your order is on its way' }}
3
+
4
+{{ $malay ? 'Hai' : 'Hi' }} {{ $order->customer_name }},
5
+
6
+{{ $malay
7
+    ? "Pesanan #{$order->number} daripada {$store->name} telah dihantar melalui {$order->shipping_courier}."
8
+    : "Order #{$order->number} from {$store->name} has been sent with {$order->shipping_courier}." }}
9
+
10
+@if ($order->tracking_number)
11
+**{{ $malay ? 'Nombor penjejakan' : 'Tracking number' }}:** {{ $order->tracking_number }}
12
+
13
+{{ $malay ? 'Gunakan nombor ini di laman web kurier untuk menjejak bungkusan anda.' : "Use this number on the courier's website to follow your parcel." }}
14
+@endif
15
+
16
+<x-mail::table>
17
+| {{ $malay ? 'Produk' : 'Item' }} | {{ $malay ? 'Kuantiti' : 'Qty' }} |
18
+| :--- | :---: |
19
+@foreach ($order->items as $item)
20
+| {{ $item->name }} | {{ $item->quantity }} |
21
+@endforeach
22
+</x-mail::table>
23
+
24
+**{{ $malay ? 'Dihantar ke' : 'Delivering to' }}**
25
+
26
+{{ $order->shipping_address['line1'] }}@if ($order->shipping_address['line2']), {{ $order->shipping_address['line2'] }}@endif<br>
27
+{{ $order->shipping_address['postcode'] }} {{ $order->shipping_address['city'] }}, {{ $order->shipping_address['state'] }}
28
+
29
+{{ $malay ? 'Terima kasih,' : 'Thanks,' }}<br>
30
+{{ $store->name }}
31
+</x-mail::message>

+ 4
- 0
routes/web.php Переглянути файл

@@ -9,6 +9,7 @@ use App\Http\Controllers\StoreController;
9 9
 use App\Http\Controllers\StoreDesignController;
10 10
 use App\Http\Controllers\StoreGenerationController;
11 11
 use App\Http\Controllers\StorePublishController;
12
+use App\Http\Controllers\StoreSettingsController;
12 13
 use App\Http\Controllers\StripeWebhookController;
13 14
 use Illuminate\Support\Facades\Route;
14 15
 
@@ -80,6 +81,7 @@ Route::middleware(['auth', 'verified'])->group(function () {
80 81
 
81 82
     Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
82 83
     Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');
84
+    Route::post('stores/{slug}/orders/{order}/ship', [OrderController::class, 'ship'])->name('stores.orders.ship')->whereNumber('order');
83 85
 
84 86
     Route::get('stores/{slug}/products', [ProductController::class, 'index'])->name('stores.products.index');
85 87
     Route::get('stores/{slug}/products/create', [ProductController::class, 'create'])->name('stores.products.create');
@@ -89,6 +91,8 @@ Route::middleware(['auth', 'verified'])->group(function () {
89 91
     Route::post('stores/{slug}/products/{product}', [ProductController::class, 'update'])->name('stores.products.update')->whereNumber('product');
90 92
     Route::delete('stores/{slug}/products/{product}', [ProductController::class, 'destroy'])->name('stores.products.destroy')->whereNumber('product');
91 93
     Route::delete('stores/{slug}/products/{product}/images/{image}', [ProductController::class, 'destroyImage'])->name('stores.products.images.destroy')->whereNumber(['product', 'image']);
94
+    Route::get('stores/{slug}/settings', [StoreSettingsController::class, 'edit'])->name('stores.settings');
95
+    Route::put('stores/{slug}/settings', [StoreSettingsController::class, 'update'])->name('stores.settings.update');
92 96
     Route::post('stores/{slug}/publish', [StorePublishController::class, 'publish'])->name('stores.publish');
93 97
     Route::post('stores/{slug}/unpublish', [StorePublishController::class, 'unpublish'])->name('stores.unpublish');
94 98
     Route::post('stores/{slug}/generate', [StoreGenerationController::class, 'generate'])->name('stores.generate');

+ 317
- 0
tests/Feature/Malaysia/ShippingTest.php Переглянути файл

@@ -0,0 +1,317 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Malaysia;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Commerce\Payments\StripeGateway;
7
+use App\Mail\OrderConfirmation;
8
+use App\Mail\OrderShipped;
9
+use App\Models\Order;
10
+use App\Models\Product;
11
+use App\Models\Store;
12
+use App\Models\User;
13
+use App\StorePlan\SamplePlan;
14
+use App\Support\MalaysianPhone;
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 ShippingTest 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
+        $this->gateway = new FakeGateway;
37
+        $this->app->instance(PaymentGateway::class, $this->gateway);
38
+
39
+        $this->user = User::factory()->create();
40
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
41
+        $this->store->plan = SamplePlan::for($this->store);
42
+        $this->store->save();
43
+        $this->actingAs($this->user);
44
+    }
45
+
46
+    private function checkout(string $state, int $price = 1000, int $quantity = 1): Order
47
+    {
48
+        $product = Product::factory()->for($this->store)->create(['price' => $price, 'stock' => 50]);
49
+
50
+        // Start every order with an empty cart, since an unpaid order keeps its cart.
51
+        session()->forget('cart.'.$this->store->id);
52
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity]);
53
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
54
+            'name' => 'Aminah binti Ali',
55
+            'email' => 'aminah@example.com',
56
+            'phone' => '012-345 6789',
57
+            'line1' => '12 Jalan Mawar',
58
+            'city' => 'Kota Kinabalu',
59
+            'postcode' => '88000',
60
+            'state' => $state,
61
+        ])->assertRedirect();
62
+
63
+        return Order::latest('id')->firstOrFail();
64
+    }
65
+
66
+    private function settings(array $overrides = [])
67
+    {
68
+        return $this->put(route('stores.settings.update', $this->store->slug), [
69
+            'whatsapp_number' => '',
70
+            'shipping_west' => '8.00',
71
+            'shipping_east' => '15.00',
72
+            'free_shipping_over' => '',
73
+            ...$overrides,
74
+        ]);
75
+    }
76
+
77
+    public function test_a_new_store_has_sensible_starting_shipping_fees()
78
+    {
79
+        $this->get(route('stores.settings', $this->store->slug))
80
+            ->assertOk()
81
+            ->assertInertia(fn (Assert $page) => $page
82
+                ->component('stores/settings')
83
+                ->where('settings.shipping_west', '8.00')
84
+                ->where('settings.shipping_east', '15.00')
85
+                ->where('settings.free_shipping_over', null)
86
+                ->where('settings.whatsapp_number', null));
87
+    }
88
+
89
+    public function test_the_merchant_can_change_shipping_fees_and_whatsapp_number()
90
+    {
91
+        $this->settings([
92
+            'whatsapp_number' => '+60 12-345 6789',
93
+            'shipping_west' => '6.5',
94
+            'shipping_east' => '18',
95
+            'free_shipping_over' => '150',
96
+        ])->assertRedirect(route('stores.settings', $this->store->slug));
97
+
98
+        $this->store->refresh();
99
+
100
+        $this->assertSame('60123456789', $this->store->whatsapp_number);
101
+        $this->assertSame(650, $this->store->shipping_west);
102
+        $this->assertSame(1800, $this->store->shipping_east);
103
+        $this->assertSame(15000, $this->store->free_shipping_over);
104
+
105
+        // Clearing the fields removes WhatsApp and free shipping.
106
+        $this->settings();
107
+        $this->store->refresh();
108
+
109
+        $this->assertNull($this->store->whatsapp_number);
110
+        $this->assertNull($this->store->free_shipping_over);
111
+    }
112
+
113
+    public function test_settings_are_checked()
114
+    {
115
+        $this->settings(['whatsapp_number' => '12345', 'shipping_west' => '-1', 'shipping_east' => 'abc', 'free_shipping_over' => '1.234'])
116
+            ->assertSessionHasErrors(['shipping_west', 'shipping_east', 'free_shipping_over']);
117
+
118
+        $this->settings(['whatsapp_number' => '12345'])->assertSessionHasErrors('whatsapp_number');
119
+
120
+        $this->assertNull($this->store->fresh()->whatsapp_number);
121
+    }
122
+
123
+    public function test_east_malaysia_pays_the_east_fee_and_the_peninsula_the_west_fee()
124
+    {
125
+        foreach (['Sabah' => 1500, 'Sarawak' => 1500, 'Labuan' => 1500, 'Selangor' => 800, 'Johor' => 800, 'Kuala Lumpur' => 800] as $state => $fee) {
126
+            $order = $this->checkout($state);
127
+
128
+            $this->assertSame($fee, $order->shipping_total, "Wrong fee for [$state].");
129
+            $this->assertSame(1000 + $fee, $order->total);
130
+        }
131
+    }
132
+
133
+    public function test_orders_over_the_free_shipping_amount_ship_free()
134
+    {
135
+        $this->settings(['free_shipping_over' => '50']);
136
+
137
+        $this->assertSame(800, $this->checkout('Selangor', price: 4999)->shipping_total);
138
+        $this->assertSame(0, $this->checkout('Sabah', price: 5000)->shipping_total);
139
+        $this->assertSame(0, $this->checkout('Selangor', price: 2500, quantity: 2)->shipping_total);
140
+
141
+        $this->settings(['free_shipping_over' => '0']);
142
+
143
+        $this->assertSame(0, $this->checkout('Sarawak')->shipping_total);
144
+    }
145
+
146
+    public function test_the_checkout_page_shows_the_fee_for_each_state()
147
+    {
148
+        $this->settings(['free_shipping_over' => '100']);
149
+        $product = Product::factory()->for($this->store)->create(['price' => 2000, 'stock' => 5]);
150
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
151
+
152
+        $this->get(route('stores.preview.checkout', $this->store->slug))
153
+            ->assertInertia(fn (Assert $page) => $page
154
+                ->where('view.shippingByState.Selangor', 8)
155
+                ->where('view.shippingByState.Sabah', 15)
156
+                ->has('view.shippingByState', 16)
157
+                ->where('shop.free_shipping_over', 100)
158
+                ->where('shop.whatsapp', null));
159
+    }
160
+
161
+    public function test_a_paid_order_includes_shipping_in_what_must_be_paid_and_in_the_email()
162
+    {
163
+        $order = $this->checkout('Sabah', price: 2580);
164
+
165
+        // A payment that covers only the products is not enough.
166
+        $this->gateway->pay($order, amount: 2580);
167
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
168
+        $this->assertFalse($order->fresh()->isPaid());
169
+
170
+        $this->gateway->pay($order, amount: 4080);
171
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
172
+            ->assertInertia(fn (Assert $page) => $page
173
+                ->where('view.order.status', 'paid')
174
+                ->where('view.order.shipping_total', 15)
175
+                ->where('view.order.total', 40.8));
176
+
177
+        $mail = new OrderConfirmation($order->fresh());
178
+        $mail->assertSeeInHtml('RM 15.00');
179
+        $mail->assertSeeInHtml('RM 40.80');
180
+    }
181
+
182
+    public function test_the_merchant_can_mark_a_paid_order_as_shipped_and_the_shopper_is_emailed_once()
183
+    {
184
+        $order = $this->checkout('Selangor');
185
+        $ship = fn (array $data) => $this->post(route('stores.orders.ship', [$this->store->slug, $order->id]), $data);
186
+
187
+        // Not paid yet.
188
+        $ship(['shipping_courier' => 'J&T Express', 'tracking_number' => 'JT123'])->assertNotFound();
189
+
190
+        $this->gateway->pay($order);
191
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
192
+
193
+        $ship(['shipping_courier' => 'Teleport', 'tracking_number' => 'x'])->assertSessionHasErrors('shipping_courier');
194
+        $ship(['shipping_courier' => 'Pos Laju', 'tracking_number' => '<script>'])->assertSessionHasErrors('tracking_number');
195
+
196
+        $ship(['shipping_courier' => 'J&T Express', 'tracking_number' => ' 630012345678 '])
197
+            ->assertRedirect(route('stores.orders.show', [$this->store->slug, $order->id]));
198
+
199
+        $order->refresh();
200
+        $this->assertNotNull($order->shipped_at);
201
+        $this->assertSame('J&T Express', $order->shipping_courier);
202
+        $this->assertSame('630012345678', $order->tracking_number);
203
+        Mail::assertSent(OrderShipped::class, fn (OrderShipped $mail) => $mail->hasTo('aminah@example.com'));
204
+
205
+        // Correcting a typo saves it without emailing again.
206
+        $shippedAt = $order->shipped_at;
207
+        $ship(['shipping_courier' => 'Ninja Van', 'tracking_number' => 'NV999']);
208
+
209
+        $order->refresh();
210
+        $this->assertSame('Ninja Van', $order->shipping_courier);
211
+        $this->assertEquals($shippedAt, $order->shipped_at);
212
+        Mail::assertSent(OrderShipped::class, 1);
213
+
214
+        // The shopper sees it on their order page.
215
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
216
+            ->assertInertia(fn (Assert $page) => $page
217
+                ->where('view.order.shipping_courier', 'Ninja Van')
218
+                ->where('view.order.tracking_number', 'NV999'));
219
+    }
220
+
221
+    public function test_the_shipped_email_is_in_the_store_language()
222
+    {
223
+        $order = Order::factory()->for($this->store)->paid()->create([
224
+            'number' => 1009, 'shipped_at' => now(), 'shipping_courier' => 'Pos Laju', 'tracking_number' => 'EP123MY',
225
+        ]);
226
+        $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
227
+
228
+        $mail = new OrderShipped($order);
229
+        $mail->assertHasSubject('Order #1009 is on its way - Kedai Ali');
230
+        $mail->assertSeeInHtml('EP123MY');
231
+        $mail->assertSeeInHtml('Pos Laju');
232
+
233
+        $this->store->update(['language' => 'ms']);
234
+        $mail = new OrderShipped($order->fresh());
235
+        $mail->assertHasSubject('Pesanan #1009 telah dihantar - Kedai Ali');
236
+        $mail->assertSeeInHtml('Nombor penjejakan');
237
+    }
238
+
239
+    public function test_another_merchant_cannot_ship_or_change_settings()
240
+    {
241
+        $order = $this->checkout('Selangor');
242
+        $this->gateway->pay($order);
243
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
244
+
245
+        $this->actingAs(User::factory()->create());
246
+
247
+        $this->post(route('stores.orders.ship', [$this->store->slug, $order->id]), ['shipping_courier' => 'Pos Laju'])->assertNotFound();
248
+        $this->get(route('stores.settings', $this->store->slug))->assertNotFound();
249
+        $this->settings(['shipping_west' => '0'])->assertNotFound();
250
+
251
+        $this->assertNull($order->fresh()->shipped_at);
252
+        $this->assertSame(800, $this->store->fresh()->shipping_west);
253
+    }
254
+
255
+    public function test_the_whatsapp_number_reaches_the_store_and_the_merchant_gets_a_chat_link_to_the_shopper()
256
+    {
257
+        $this->settings(['whatsapp_number' => '0123456789']);
258
+        $order = $this->checkout('Selangor');
259
+
260
+        $this->get(route('stores.preview', $this->store->slug))
261
+            ->assertInertia(fn (Assert $page) => $page->where('shop.whatsapp', '60123456789'));
262
+
263
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
264
+            ->assertInertia(fn (Assert $page) => $page
265
+                ->has('couriers', 10)
266
+                ->where('customer_whatsapp_url', fn (string $url) => str_starts_with($url, 'https://wa.me/60123456789?text=')
267
+                    && str_contains(rawurldecode($url), 'order #'.$order->number)));
268
+    }
269
+
270
+    public function test_malaysian_phone_numbers_are_normalised_for_whatsapp()
271
+    {
272
+        $this->assertSame('60123456789', MalaysianPhone::normalize('012-345 6789'));
273
+        $this->assertSame('60123456789', MalaysianPhone::normalize('+60 12 345 6789'));
274
+        $this->assertSame('601123456789', MalaysianPhone::normalize('011-2345 6789'));
275
+        $this->assertSame('60123456789', MalaysianPhone::normalize('123456789'));
276
+        $this->assertNull(MalaysianPhone::normalize('12345'));
277
+        $this->assertNull(MalaysianPhone::normalize('+65 9123 4567'));
278
+        $this->assertNull(MalaysianPhone::normalize(''));
279
+        $this->assertSame('https://wa.me/60123456789?text=Hi%20there%20%231', MalaysianPhone::whatsappLink('60123456789', 'Hi there #1'));
280
+    }
281
+
282
+    public function test_checkout_messages_follow_the_store_language()
283
+    {
284
+        $this->store->update(['language' => 'ms']);
285
+        $product = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 5]);
286
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
287
+
288
+        $response = $this->post(route('stores.preview.checkout.store', $this->store->slug), [
289
+            'name' => '', 'email' => 'nope', 'phone' => 'x', 'line1' => 'ab', 'city' => 'KL', 'postcode' => '123', 'state' => 'Atlantis',
290
+        ]);
291
+
292
+        $response->assertSessionHasErrors([
293
+            'name' => 'Nama penuh diperlukan.',
294
+            'email' => 'E-mel mestilah alamat e-mel yang sah.',
295
+            'phone' => 'Sila masukkan nombor telefon yang sah.',
296
+            'line1' => 'Alamat mestilah sekurang-kurangnya 3 aksara.',
297
+            'postcode' => 'Poskod mestilah 5 digit.',
298
+            'state' => 'Sila pilih negeri.',
299
+        ]);
300
+
301
+        $soldOut = Product::factory()->for($this->store)->soldOut()->create();
302
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $soldOut->id, 'quantity' => 1])
303
+            ->assertSessionHasErrors(['quantity' => 'Produk ini telah habis dijual.']);
304
+    }
305
+
306
+    public function test_stripe_is_given_the_shipping_fee_as_its_own_line()
307
+    {
308
+        $order = Order::factory()->for($this->store)->create(['shipping_total' => 1500]);
309
+        $method = new \ReflectionMethod(StripeGateway::class, 'shippingLabel');
310
+
311
+        $this->assertSame('Shipping', $method->invoke(new StripeGateway, $order));
312
+        $this->assertSame('Free shipping', $method->invoke(new StripeGateway, $order->replicate()->fill([])->forceFill(['shipping_total' => 0])));
313
+
314
+        $this->store->update(['language' => 'ms']);
315
+        $this->assertSame('Penghantaran', $method->invoke(new StripeGateway, $order->fresh()));
316
+    }
317
+}

+ 8
- 3
tests/Feature/Stores/CheckoutTest.php Переглянути файл

@@ -109,7 +109,9 @@ class CheckoutTest extends TestCase
109 109
         $this->assertSame(1001, $order->number);
110 110
         $this->assertSame(OrderStatus::Pending, $order->status);
111 111
         $this->assertSame(3379, $order->subtotal);
112
-        $this->assertSame(3379, $order->total);
112
+        // Selangor is in Peninsular Malaysia: the store's default RM 8.00 fee.
113
+        $this->assertSame(800, $order->shipping_total);
114
+        $this->assertSame(4179, $order->total);
113 115
         $this->assertSame('MYR', $order->currency);
114 116
         $this->assertSame('fake', $order->payment_provider);
115 117
         $this->assertSame('cs_fake_1', $order->payment_checkout_id);
@@ -181,7 +183,9 @@ class CheckoutTest extends TestCase
181 183
                 ->where('view.type', 'order')
182 184
                 ->where('view.order.status', 'paid')
183 185
                 ->where('view.order.number', 1001)
184
-                ->where('view.order.total', 38.7)
186
+                ->where('view.order.subtotal', 38.7)
187
+                ->where('view.order.shipping_total', 8)
188
+                ->where('view.order.total', 46.7)
185 189
                 ->has('view.order.items', 1)
186 190
                 ->where('cart.count', 0));
187 191
 
@@ -246,7 +250,8 @@ class CheckoutTest extends TestCase
246 250
 
247 251
         $this->assertNull($item->product_id);
248 252
         $this->assertSame(['Sambal', 1290, 2580], [$item->name, $item->unit_price, $item->line_total]);
249
-        $this->assertSame(2580, $order->fresh()->total);
253
+        $this->assertSame(2580, $order->fresh()->subtotal);
254
+        $this->assertSame(3380, $order->fresh()->total);
250 255
 
251 256
         // Paying for it still works, even though the product is gone.
252 257
         $this->gateway->pay($order);

Завантаження…
Відмінити
Зберегти