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

Add EasyParcel courier booking and clearer back buttons

- Connect each store to the merchant's own EasyParcel account (guided setup in Settings, sign in and allow)
- Pickup address and usual parcel size in Settings
- On a paid order: compare courier prices, book one, print the label, tracking number filled in and shopper emailed
- Prices match what EasyParcel charges; low-credit and other EasyParcel errors shown in plain words
- Tested with the EasyParcel sandbox: real prices and a real booking with label
- Clear "Back" buttons at the top of every store page, including add and edit pages
- New easyparcel_accounts table and pickup/shipment columns (run php artisan migrate)
feature/easyparcel
fahmisaad 1 день назад
Родитель
Сommit
a25517d193
32 измененных файлов: 2775 добавлений и 122 удалений
  1. 5
    0
      .env
  2. 90
    46
      PROGRESS.md
  3. 534
    0
      app/Commerce/Shipping/EasyParcel/EasyParcel.php
  4. 19
    0
      app/Commerce/Shipping/EasyParcel/EasyParcelException.php
  5. 21
    0
      app/Commerce/Shipping/EasyParcel/Parcel.php
  6. 44
    0
      app/Commerce/Shipping/EasyParcel/Quote.php
  7. 38
    0
      app/Commerce/Shipping/EasyParcel/StateCodes.php
  8. 90
    0
      app/Http/Controllers/EasyParcelController.php
  9. 156
    1
      app/Http/Controllers/OrderController.php
  10. 100
    2
      app/Http/Controllers/StoreSettingsController.php
  11. 47
    0
      app/Models/EasyParcelAccount.php
  12. 11
    0
      app/Models/Order.php
  13. 17
    0
      app/Models/Store.php
  14. 2
    0
      app/Providers/AppServiceProvider.php
  15. 8
    0
      config/services.php
  16. 54
    0
      database/migrations/2026_11_26_000001_add_easyparcel.php
  17. 24
    0
      resources/js/components/back-button.tsx
  18. 510
    0
      resources/js/components/stores/courier-booking.tsx
  19. 252
    0
      resources/js/components/stores/easyparcel-setup.tsx
  20. 12
    4
      resources/js/pages/stores/collections/form.tsx
  21. 16
    8
      resources/js/pages/stores/discounts/automatic-form.tsx
  22. 14
    4
      resources/js/pages/stores/discounts/form.tsx
  23. 5
    9
      resources/js/pages/stores/discounts/index.tsx
  24. 5
    9
      resources/js/pages/stores/orders/index.tsx
  25. 32
    12
      resources/js/pages/stores/orders/show.tsx
  26. 11
    4
      resources/js/pages/stores/products/create.tsx
  27. 10
    4
      resources/js/pages/stores/products/edit.tsx
  28. 5
    9
      resources/js/pages/stores/products/index.tsx
  29. 204
    10
      resources/js/pages/stores/settings.tsx
  30. 8
    0
      resources/js/types/store.ts
  31. 7
    0
      routes/web.php
  32. 424
    0
      tests/Feature/Malaysia/EasyParcelTest.php

+ 5
- 0
.env Просмотреть файл

99
 # Optional. Lets Stripe tell the app about payments directly. Starts with whsec_.
99
 # Optional. Lets Stripe tell the app about payments directly. Starts with whsec_.
100
 STRIPE_WEBHOOK_SECRET=
100
 STRIPE_WEBHOOK_SECRET=
101
 
101
 
102
+# EasyParcel app from developer.easyparcel.com. Put the real values in .env.local, never here.
103
+# Its redirect address must be <APP_URL>/easyparcel/callback.
104
+EASYPARCEL_CLIENT_ID=
105
+EASYPARCEL_CLIENT_SECRET=
106
+
102
 # Published stores open at <store name>.<this domain>. Leave blank on a development machine to use localhost.
107
 # Published stores open at <store name>.<this domain>. Leave blank on a development machine to use localhost.
103
 STOREFRONT_DOMAIN=
108
 STOREFRONT_DOMAIN=

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

3
 This file is the single source of truth for the project plan and status.
3
 This file is the single source of truth for the project plan and status.
4
 Update it at the end of every work session.
4
 Update it at the end of every work session.
5
 
5
 
6
-**Last updated:** 2026-11-26
7
-**Current step:** Step 10 (before launch): the new design (Step 9 parts 1–7), home page, legal pages, dashboard and Select to edit are merged into `main` (2026-11-26); Step 9 part 8 on hold
8
-**Next action:** EasyParcel demo key. Also: have a lawyer read the privacy and terms pages, fill the `LEGAL_` lines, and choose: backup AI provider, hosting, Stripe Connect (who receives the money), Step 7 part 2, or part 8. New work branches from `main`
6
+**Last updated:** 2026-11-30
7
+**Current step:** Step 10: Stripe Connect (merchants get paid into their own Stripe account) is planned, not built. EasyParcel courier booking is done on branch `feature/easyparcel` (not committed yet). Step 9 part 8 on hold
8
+**Next action:** Commit `feature/easyparcel` and merge into `main`. Then you switch on Connect in the Stripe dashboard (test mode), and we build Stripe Connect on a new branch `feature/stripe-connect` from `main` (task list in Step 10). Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
9
 
9
 
10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11
 
11
 
121
 - Switching plans changes the existing subscription; Stripe charges or credits the difference on the next bill.
121
 - Switching plans changes the existing subscription; Stripe charges or credits the difference on the next bill.
122
 - Subscriptions go through one interface (`SubscriptionGateway`), like payments and AI.
122
 - Subscriptions go through one interface (`SubscriptionGateway`), like payments and AI.
123
 
123
 
124
+### How merchants get paid (planned 2026-11-30, not built yet)
125
+
126
+- Today every shopper payment lands in **our** Stripe account. Before real merchants sell, this changes to **Stripe Connect**: each store connects the merchant's own Stripe account, and shopper payments go straight there. Stripe pays it into the merchant's bank. We never hold shop money (holding other businesses' money can need a Bank Negara licence, and would make refunds and tax our problem).
127
+- Payments are "direct charges": the Stripe payment page is made on the merchant's account, so the merchant is the seller on the shopper's bank statement and receipt.
128
+- The merchant gets their own full Stripe Dashboard. They pay Stripe's fees, and handle refunds and disputes (bank chargebacks), because they are the seller.
129
+- **No cut for us** (decided 2026-11-30): we earn from the monthly plan only. A cut per sale (Stripe's "application fee") can be added later without merchants connecting again.
130
+- Setup: in Settings, the merchant clicks "Connect Stripe". We create a Stripe account for the store and send them to Stripe's own sign-up page, where Stripe checks their identity, SSM number and bank account. They come back to Settings. This is what Stripe recommends now, instead of the older "Connect with Stripe" sign-in.
131
+- One Stripe account per store, like EasyParcel.
132
+- A store cannot take orders until Stripe says it can accept payments. Shoppers see "This store is not taking orders yet" at checkout. The merchant sees a reminder in Settings and on the overview.
133
+- Each order saves which Stripe account it was paid into, so checks and refunds go to the right account even if the merchant reconnects later.
134
+- Discount coupons are made on the merchant's Stripe account, because the payment page lives there.
135
+- Stripe tells us about payments on merchants' accounts through a second webhook ("Connected accounts" events), and tells us when a merchant's setup is finished (`account.updated`).
136
+- FPX needs the merchant's SSM number (Stripe's rule). Merchants without a registered business may only be able to take cards.
137
+- Our own monthly plans (Billing) stay on our own Stripe account. Nothing changes there.
138
+- Plan B, if Stripe will not run Connect for a Malaysian platform: each merchant connects their own Malaysian payment gateway (such as CHIP or Billplz) instead, in the same "connect" way. The `PaymentGateway` interface already allows a second provider.
139
+
124
 ### How shipping and WhatsApp work (added in Step 7)
140
 ### How shipping and WhatsApp work (added in Step 7)
125
 
141
 
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.
142
 - 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.
143
 - 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.
144
 - 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.
145
 - `shipped_at`, `shipping_courier` and `tracking_number` on the order record the delivery. Only paid orders can be shipped.
146
+- **EasyParcel (decided 2026-11-26):** each merchant connects **their own** EasyParcel account (they sign up, top up credit, then click "Connect EasyParcel" and Allow). Parcels are paid from their credit, so we never hold shipping money. We cannot open EasyParcel accounts for merchants (EasyParcel checks identity and has no sign-up API), so Settings shows a 4-step guide instead. One account of ours for everyone (EasyParcel "Marketplace") was turned down: we would have to charge merchants back.
147
+- EasyParcel uses its new Open API (version 2026-09, `api.easyparcel.com`) with OAuth (PKCE). The app's client ID and secret come from developer.easyparcel.com and live in `.env.local`; the redirect address is `<APP_URL>/easyparcel/callback`. Sandbox or live is decided by which EasyParcel account the merchant signs in with. Tokens are stored encrypted in `easyparcel_accounts` and renewed by themselves. Code: `app/Commerce/Shipping/EasyParcel/`.
148
+- First version (2026-11-26): **book a courier on a paid order**. The merchant types the parcel (weight and size, filled from "Your usual parcel" in Settings), sees every courier's price cheapest first, picks one and a collection day, and books. EasyParcel takes the price from their credit. The order saves the shipment number, price, courier, tracking number, label and tracking link. The order counts as shipped, and the shopper gets the "on its way" email, once the tracking number is known (some couriers give it a minute later: "Check for the label"). Services that deliver to a collection point are left out. Paid EasyParcel extras (SMS, WhatsApp tracking) stay off.
149
+- Checkout prices: shoppers still pay the flat fees. Later, the merchant will be able to choose "live rate" (the real courier price) instead.
150
+- What the real EasyParcel sends (found in the sandbox test): courier names are company names ("J&T Express (Malaysia) Sdn. Bhd."), so we show the service name without brackets ("J&T Express") and keep "Pickup needs at least N parcels" as a note; the delivery time is `{"type":"days","value":"3"}`, shown as "About 3 days"; errors are wrapped one level deeper than the docs show. A changed `.env.local` needs the app server restarted.
151
+- Pickup address on the store (`pickup_address`, all or nothing), usual parcel `parcel_weight` (grams) and `parcel_size` (cm).
130
 - WhatsApp numbers are saved as digits with country code (`60123456789`). Only Malaysian numbers are accepted. `MalaysianPhone` does the cleaning.
152
 - 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`.
153
 - Messages the server shows to shoppers live in `App\Storefront\StorefrontText`; words drawn in the browser live in `resources/js/storefront/text.ts`.
132
 
154
 
421
 Part 2 (needs outside accounts):
443
 Part 2 (needs outside accounts):
422
 
444
 
423
 - [ ] Switch on FPX and GrabPay in the Stripe dashboard (your action), then test an FPX payment
445
 - [ ] Switch on FPX and GrabPay in the Stripe dashboard (your action), then test an FPX payment
424
-- [ ] EasyParcel live shipping rates and labels (needs an EasyParcel demo account and API key; plugs in behind `ShippingProvider`)
446
+- [~] EasyParcel (branch `feature/easyparcel`):
447
+    - [x] Connect the merchant's own EasyParcel account with a guided setup in Settings, pickup address, usual parcel size
448
+    - [x] Book a courier on a paid order: compare prices, book, print the label, tracking number and "on its way" email
449
+    - [x] App "AI Commerce" made in the EasyParcel Developer Hub (redirect `http://localhost:8000/easyparcel/callback`), keys in `.env.local`, sandbox account made. Tested for real on 2026-11-26: Luna Skin connected to the sandbox account, real courier prices came back (22 services, Pos MELPlus RM 7.63 cheapest), booking with no credit showed "this parcel needs RM 7.03"
450
+    - [x] Booked a sandbox parcel on 2026-11-26 (Luna Skin order #1001, Pos MELPlus pickup, EasyParcel ES-2611-TK58P, RM 7.03): tracking number and link saved, label opens as a PDF, "on its way" email sent. Found that EasyParcel's quoted total includes tracking extras we do not book (RM 0.60), so prices shown are now shipment + its tax, matching what is charged
451
+        - [ ] Live courier rate at checkout, as a choice next to the flat fees (plugs in behind `ShippingProvider`)
452
+        - [ ] Tracking updates by themselves (collected, in transit, delivered)
453
+        - [ ] Product weights, for a more exact parcel weight
425
 - [ ] Automatic WhatsApp order notifications (needs a WhatsApp Business Platform account from Meta, with approved message templates)
454
 - [ ] Automatic WhatsApp order notifications (needs a WhatsApp Business Platform account from Meta, with approved message templates)
426
 - [ ] 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
455
 - [ ] 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
427
 
456
 
472
 - [x] Our own home page at `/` (done 2026-11-22, branch `feature/homepage`, made from the part 7 branch)
501
 - [x] Our own home page at `/` (done 2026-11-22, branch `feature/homepage`, made from the part 7 branch)
473
 
502
 
474
 - [x] Overview dashboard with stats, store tree in the sidebar and daily AI note (done 2026-11-22, branch `feature/dashboard`)
503
 - [x] Overview dashboard with stats, store tree in the sidebar and daily AI note (done 2026-11-22, branch `feature/dashboard`)
504
+- [ ] Merchants get paid into their own Stripe account (Stripe Connect, planned 2026-11-30, see "How merchants get paid"):
505
+    - [ ] You: switch on Connect in the Stripe dashboard in **test mode** (dashboard.stripe.com/connect). On 2026-11-30 our test key was refused: "You can only create new accounts if you've signed up for Connect"
506
+    - [ ] Check that Stripe lets our Malaysian account create a Malaysian merchant account (a quick test with the test key). If not, ask Stripe support, or switch to plan B
507
+    - [ ] Branch `feature/stripe-connect` from `main`: a table for each store's Stripe account (account id, can take payments, payouts on, setup finished), and the Stripe account on each order
508
+    - [ ] Settings: a "Get paid" card with a guided setup, "Connect Stripe", "Finish setup" if they stopped halfway, and a connected view (payouts on, link to their Stripe Dashboard)
509
+    - [ ] Checkout: the payment page is made on the store's Stripe account (coupons too). Checkout is closed until the store can take payments
510
+    - [ ] Return page check and webhook for merchants' accounts, plus `account.updated`
511
+    - [ ] Overview reminder "Connect Stripe to take orders"
512
+    - [ ] Terms page: say how merchants are paid (straight to their own Stripe account, Stripe's terms apply, no cut), and change its "last changed" date
513
+    - [ ] Tests with a pretend Stripe
514
+    - [ ] Real test: set up a test merchant with Stripe's test details, pay with a test card, see the money in the merchant's test account; then an FPX test
515
+    - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
475
 - [ ] Choose hosting and deploy
516
 - [ ] Choose hosting and deploy
476
 - [x] Privacy policy and terms of service, naming the AI providers (done 2026-11-22, `/privacy` and `/terms`; a lawyer should read them before launch)
517
 - [x] Privacy policy and terms of service, naming the AI providers (done 2026-11-22, `/privacy` and `/terms`; a lawyer should read them before launch)
477
 - [ ] Backup AI provider in case one is down
518
 - [ ] Backup AI provider in case one is down
582
 
623
 
583
 ## 5. Open questions
624
 ## 5. Open questions
584
 
625
 
585
-- **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.
626
+- **Who receives the money?** Decided 2026-11-30: Stripe Connect, each merchant's own Stripe account, no cut for us (see "How merchants get paid"). Still open: whether Stripe runs Connect for our Malaysian account (we find out once Connect is switched on).
586
 - **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.
627
 - **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.
587
 - Hosting provider (decide at Step 10)
628
 - Hosting provider (decide at Step 10)
588
 
629
 
606
 
647
 
607
 Add one line per work session: date, what was done, what is next.
648
 Add one line per work session: date, what was done, what is next.
608
 
649
 
609
-| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Next                                                            |
610
-| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
611
-| 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) |
612
-| 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                   |
613
-| 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                 |
614
-| 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                 |
615
-| 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                    |
616
-| 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                                       |
617
-| 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                        |
618
-| 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             |
619
-| 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                |
620
-| 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                      |
621
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
622
-| 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                                              |
623
-| 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                                              |
624
-| 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                                    |
625
-| 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                                  |
626
-| 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                             |
627
-| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                                                                                                                                                                                                                    | Merge both branches, then Step 7 part 2 or Step 8               |
628
-| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Merge branches, then Step 7 part 2 or Step 8                    |
629
-| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                                                                                                                                                                                                                         | Merge, then product variants                                    |
630
-| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                                                                                                                                                                                                                              | Merge both branches, then bundles                               |
631
-| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                                                                                                                                                                                                                               | Merge, then chat commands                                       |
632
-| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                                                                                                                                                                                                                           | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
633
-| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                                                                                                                                                                                                                     | Merge; then Step 7 part 2 or Step 9                             |
634
-| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                          | Merge; then Step 7 part 2 or Step 9                             |
635
-| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Step 9 part 1: photos first                                     |
636
-| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                                                                                                                                                                                                                                 | Merge, then part 2                                              |
637
-| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                                                                                                                                                                                                                     | Commit; part 3 branches from part 2                             |
638
-| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                                                                                                                                                                                                                            | Commit; part 4 branches from part 3                             |
639
-| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser.                                                                                                                                                                                                     | Commit; part 5 branches from part 4                             |
640
-| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                                                                                                                                                                                                                        | Commit; part 6 branches from part 5                             |
641
-| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                                                                                                                                                                                                                    | Commit; then part 7 or merge                                    |
642
-| 2026-11-21 | Decided to keep `main` and the redesign apart for comparison. Split reviews out as part 8. Step 9 part 7 on branch `redesign/part-7-collections-bento-video` (from part 6): collections (Products tab, chat, pages, links), shop by, bento and video sections, with AI checks for collection names and video addresses. 282 tests pass; real DeepSeek created two collections for Luna Skin (confirmed) and added shop by and bento correctly; checked in the browser.                                                                                                                                                                                                 | Commit; part 8 branches from part 7                             |
643
-| 2026-11-22 | Added Video and Bento boxes to the Design tab (same branch, part 7), so both can be added and edited without chat. The merchant added a real YouTube video to Luna Skin by chat; it plays in the preview. 286 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                              | Commit part 7; then part 8                                      |
644
-| 2026-11-22 | Part 7 committed on `redesign/part-7-collections-bento-video`. Part 8 (real reviews) put on hold by the merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Choose next step                                                |
645
-| 2026-11-22 | Built our own home page on branch `feature/homepage`: content outline like afilink.app with our own look, real plan prices, store-name box that fills the Create store form. 288 tests pass; checked on desktop and phone. Then made the hero picture move like afilink's (pinned scroll on wide screens, plays once on phones, floating tags), fixed tags covering text, added hover lift on the hero pieces and pricing cards, made the store and bubble float, and added six more animations (fade-up, typing bubble, playing chat, changing styles, steps line, shop-types strip).                                                                                 | Commit; choose next step                                        |
646
-| 2026-11-22 | Home page committed. Added the privacy policy (`/privacy`) and terms of service (`/terms`) for Malaysian law, naming the AI companies from the AI settings, linked from the home footer and sign-up. 293 tests pass; checked on desktop and phone.                                                                                                                                                                                                                                                                                                                                                                                                                     | Commit; lawyer check; choose next                               |
647
-| 2026-11-22 | Redesigned the dashboard on branch `feature/dashboard` (picked from three trend designs: AI note on top of colourful boxes). Stats with filters, needs attention, sales chart, store tree in the sidebar, daily Store pulse from DeepSeek saved per day with 3 "Write again" a day, first-sale steps for new merchants. 303 tests pass; checked on desktop, phone and dark mode.                                                                                                                                                                                                                                                                                       | Commit; choose next step                                        |
648
-| 2026-11-25 | On `feature/dashboard` (not committed): store letter tiles in the sidebar; researched courier prices and APIs (J&T, Pos Laju, GDEX, DHL eCommerce): only GDEX has a public developer site, the others need a sales contract, so EasyParcel stays the plan; "Show in the preview": clicking a section name in the Design tab scrolls the preview to it and outlines it; banner photos now accepted from 300×200 and got ready in the background (enlarged, shrunk, upright, WebP); "Ask the AI" is now a floating button that opens a chat panel; Light/Dark switch above the user in the sidebar; Select to edit (click or drag in the preview, Ask the AI changes only that part). 310 tests pass; checked in the browser on desktop and phone preview. | Commit, then EasyParcel demo key                                |
649
-| 2026-11-26 | Decided to use the new design: merged `feature/dashboard` into `main`, old design kept as tag `old-design`. | EasyParcel demo key |
650
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | Next                                                                                       |
651
+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
652
+| 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)                            |
653
+| 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                                              |
654
+| 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                                            |
655
+| 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                                            |
656
+| 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                                               |
657
+| 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                                                                  |
658
+| 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                                                   |
659
+| 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                                        |
660
+| 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                                           |
661
+| 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                                                 |
662
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Step 5: publishing                                                                         |
663
+| 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                                                                         |
664
+| 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                                                                         |
665
+| 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                                                               |
666
+| 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                                                             |
667
+| 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                                                        |
668
+| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                                                                                                                                                                                                                                                                                                      | Merge both branches, then Step 7 part 2 or Step 8                                          |
669
+| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Merge branches, then Step 7 part 2 or Step 8                                               |
670
+| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Merge, then product variants                                                               |
671
+| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Merge both branches, then bundles                                                          |
672
+| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                                                                                                                                                                                                                                                                                                                 | Merge, then chat commands                                                                  |
673
+| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                                                                                                                                                                                                                                                                                                             | Merge; then automatic discounts, Step 7 part 2 or Step 9                                   |
674
+| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                                                                                                                                                                                                                                                                                                       | Merge; then Step 7 part 2 or Step 9                                                        |
675
+| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Merge; then Step 7 part 2 or Step 9                                                        |
676
+| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Step 9 part 1: photos first                                                                |
677
+| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                                                                                                                                                                                                                                                                                                                   | Merge, then part 2                                                                         |
678
+| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit; part 3 branches from part 2                                                        |
679
+| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                                                                                                                                                                                                                                                                                                              | Commit; part 4 branches from part 3                                                        |
680
+| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser.                                                                                                                                                                                                                                                                                       | Commit; part 5 branches from part 4                                                        |
681
+| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                                                                                                                                                                                                                                                                                                          | Commit; part 6 branches from part 5                                                        |
682
+| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Commit; then part 7 or merge                                                               |
683
+| 2026-11-21 | Decided to keep `main` and the redesign apart for comparison. Split reviews out as part 8. Step 9 part 7 on branch `redesign/part-7-collections-bento-video` (from part 6): collections (Products tab, chat, pages, links), shop by, bento and video sections, with AI checks for collection names and video addresses. 282 tests pass; real DeepSeek created two collections for Luna Skin (confirmed) and added shop by and bento correctly; checked in the browser.                                                                                                                                                                                                                                                                                   | Commit; part 8 branches from part 7                                                        |
684
+| 2026-11-22 | Added Video and Bento boxes to the Design tab (same branch, part 7), so both can be added and edited without chat. The merchant added a real YouTube video to Luna Skin by chat; it plays in the preview. 286 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Commit part 7; then part 8                                                                 |
685
+| 2026-11-22 | Part 7 committed on `redesign/part-7-collections-bento-video`. Part 8 (real reviews) put on hold by the merchant.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Choose next step                                                                           |
686
+| 2026-11-22 | Built our own home page on branch `feature/homepage`: content outline like afilink.app with our own look, real plan prices, store-name box that fills the Create store form. 288 tests pass; checked on desktop and phone. Then made the hero picture move like afilink's (pinned scroll on wide screens, plays once on phones, floating tags), fixed tags covering text, added hover lift on the hero pieces and pricing cards, made the store and bubble float, and added six more animations (fade-up, typing bubble, playing chat, changing styles, steps line, shop-types strip).                                                                                                                                                                   | Commit; choose next step                                                                   |
687
+| 2026-11-22 | Home page committed. Added the privacy policy (`/privacy`) and terms of service (`/terms`) for Malaysian law, naming the AI companies from the AI settings, linked from the home footer and sign-up. 293 tests pass; checked on desktop and phone.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit; lawyer check; choose next                                                          |
688
+| 2026-11-22 | Redesigned the dashboard on branch `feature/dashboard` (picked from three trend designs: AI note on top of colourful boxes). Stats with filters, needs attention, sales chart, store tree in the sidebar, daily Store pulse from DeepSeek saved per day with 3 "Write again" a day, first-sale steps for new merchants. 303 tests pass; checked on desktop, phone and dark mode.                                                                                                                                                                                                                                                                                                                                                                         | Commit; choose next step                                                                   |
689
+| 2026-11-25 | On `feature/dashboard` (not committed): store letter tiles in the sidebar; researched courier prices and APIs (J&T, Pos Laju, GDEX, DHL eCommerce): only GDEX has a public developer site, the others need a sales contract, so EasyParcel stays the plan; "Show in the preview": clicking a section name in the Design tab scrolls the preview to it and outlines it; banner photos now accepted from 300×200 and got ready in the background (enlarged, shrunk, upright, WebP); "Ask the AI" is now a floating button that opens a chat panel; Light/Dark switch above the user in the sidebar; Select to edit (click or drag in the preview, Ask the AI changes only that part). 310 tests pass; checked in the browser on desktop and phone preview. | Commit, then EasyParcel demo key                                                           |
690
+| 2026-11-26 | Decided to use the new design: merged `feature/dashboard` into `main`, old design kept as tag `old-design`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | EasyParcel demo key                                                                        |
691
+| 2026-11-26 | EasyParcel on branch `feature/easyparcel` (later the same day: real sandbox test passed for connect, prices and the low-credit message; fixed courier names, delivery times and error messages from what the real API sends): merchants connect their own EasyParcel account (guided setup in Settings, OAuth with EasyParcel's new Open API), add a pickup address and usual parcel, and book a courier on a paid order (prices cheapest first, label, tracking number, shopper emailed). 324 tests pass with a pretend EasyParcel; checked Settings and the order page in the browser.                                                                                                                                                                 | App keys in `.env.local`, then sandbox test                                                |
692
+| 2026-11-26 | EasyParcel sandbox booking passed: Pos MELPlus parcel booked for Luna Skin #1001 (RM 7.03), label PDF, tracking and email all worked. Prices shown now leave out tracking extras we do not book. 326 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | Commit and merge                                                                           |
693
+| 2026-11-30 | Planned how merchants get paid: Stripe Connect with each merchant's own Stripe account, direct charges, no cut for us. A test with our Stripe test key showed Connect is not switched on yet. Plan and tasks written in Step 10.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | Commit EasyParcel; switch on Connect in Stripe (test mode); build `feature/stripe-connect` |

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

1
+<?php
2
+
3
+namespace App\Commerce\Shipping\EasyParcel;
4
+
5
+use App\Models\EasyParcelAccount;
6
+use App\Models\Order;
7
+use App\Models\OrderItem;
8
+use App\Models\Store;
9
+use App\Support\MalaysianPhone;
10
+use Illuminate\Http\Client\ConnectionException;
11
+use Illuminate\Http\Client\PendingRequest;
12
+use Illuminate\Http\Client\Response;
13
+use Illuminate\Support\Arr;
14
+use Illuminate\Support\Facades\Http;
15
+use Illuminate\Support\Str;
16
+
17
+/**
18
+ * Talks to EasyParcel's Open API for one merchant at a time.
19
+ *
20
+ * Each merchant connects their own EasyParcel account (OAuth): they sign in on EasyParcel and click Allow,
21
+ * and we keep the tokens. Parcels are then quoted and booked on their account and paid from its credit.
22
+ * EasyParcel decides test (sandbox) or live by which account the merchant signs in with.
23
+ */
24
+final class EasyParcel
25
+{
26
+    /** Renew the access token this many seconds before it runs out. */
27
+    private const int RENEW_EARLY = 120;
28
+
29
+    public function __construct(private readonly array $config = []) {}
30
+
31
+    public static function fromConfig(): self
32
+    {
33
+        return new self((array) config('services.easyparcel'));
34
+    }
35
+
36
+    /** True once the app's own EasyParcel client ID and secret are in .env.local. */
37
+    public function isConfigured(): bool
38
+    {
39
+        return filled($this->config['client_id'] ?? null) && filled($this->config['client_secret'] ?? null);
40
+    }
41
+
42
+    public function redirectUri(): string
43
+    {
44
+        return route('easyparcel.callback');
45
+    }
46
+
47
+    /**
48
+     * The EasyParcel page where the merchant signs in and allows us to use their account.
49
+     * The verifier is kept by the caller and sent back in connect() (PKCE: proves the answer is for this request).
50
+     */
51
+    public function authorizeUrl(string $state, string $verifier): string
52
+    {
53
+        $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
54
+
55
+        return $this->baseUrl().'/oauth/login?'.http_build_query([
56
+            'response_type' => 'code',
57
+            'client_id' => $this->config['client_id'] ?? '',
58
+            'redirect_uri' => $this->redirectUri(),
59
+            'state' => $state,
60
+            'code_challenge' => $challenge,
61
+            'code_challenge_method' => 'S256',
62
+        ]);
63
+    }
64
+
65
+    /**
66
+     * Swap the code EasyParcel sent back for tokens, and save the connection on the store.
67
+     */
68
+    public function connect(Store $store, string $code, string $verifier): EasyParcelAccount
69
+    {
70
+        $tokens = $this->tokenRequest([
71
+            'grant_type' => 'authorization_code',
72
+            'code' => $code,
73
+            'redirect_uri' => $this->redirectUri(),
74
+            'code_verifier' => $verifier,
75
+        ]);
76
+
77
+        $account = $store->easyparcel()->firstOrNew();
78
+        $this->saveTokens($account, $tokens);
79
+
80
+        // The account's name, so the merchant sees which account is connected. Not needed to work.
81
+        try {
82
+            $info = $this->call($account, 'GET', 'account/get_account_information');
83
+            $account->account_name = Str::limit((string) (Arr::get($info, 'data.account.name') ?? ''), 120, '') ?: null;
84
+            $account->save();
85
+        } catch (EasyParcelException) {
86
+            // Keep the connection; the name is only for show.
87
+        }
88
+
89
+        return $account;
90
+    }
91
+
92
+    /**
93
+     * The account's credit balance in sen, or null when EasyParcel does not say.
94
+     */
95
+    public function balance(EasyParcelAccount $account): ?int
96
+    {
97
+        $wallet = Arr::get($this->call($account, 'GET', 'wallet'), 'data.wallet.0.balance');
98
+
99
+        return is_numeric($wallet) ? (int) round(((float) $wallet) * 100) : null;
100
+    }
101
+
102
+    /**
103
+     * Courier services for sending this order's parcel, cheapest first.
104
+     *
105
+     * @return list<Quote>
106
+     */
107
+    public function quotes(Store $store, Order $order, Parcel $parcel): array
108
+    {
109
+        $account = $this->accountOf($store);
110
+        $pickup = $this->pickupOf($store);
111
+
112
+        $answer = $this->call($account, 'POST', 'shipment/quotations', [
113
+            'shipment' => [[
114
+                'sender' => ['postcode' => $pickup['postcode'], 'subdivision_code' => StateCodes::for($pickup['state']), 'country' => 'MY'],
115
+                'receiver' => ['postcode' => $order->shipping_address['postcode'], 'subdivision_code' => StateCodes::for($order->shipping_address['state']), 'country' => 'MY'],
116
+                'parcel_value' => self::ringgit($order->subtotal - $order->discount_total),
117
+                'weight' => $parcel->kilograms(),
118
+                'length' => $parcel->length,
119
+                'width' => $parcel->width,
120
+                'height' => $parcel->height,
121
+            ]],
122
+        ]);
123
+
124
+        $result = Arr::get($answer, 'data.0', []);
125
+        $this->failIfError($result);
126
+
127
+        $quotes = [];
128
+
129
+        foreach ((array) Arr::get($result, 'quotations', []) as $quotation) {
130
+            $serviceId = (string) Arr::get($quotation, 'courier.service_id', '');
131
+            // The total includes paid extras (SMS, email, WhatsApp tracking) that we switch off when booking,
132
+            // so the real price is the shipment and its tax.
133
+            $shipping = Arr::get($quotation, 'pricing.shipment_price');
134
+            $price = is_numeric($shipping)
135
+                ? (float) $shipping + (float) (Arr::get($quotation, 'pricing.shipment_tax') ?? 0)
136
+                : Arr::get($quotation, 'pricing.total_amount');
137
+
138
+            // Services that deliver to a collection point need the shopper to pick one, which checkout does not ask.
139
+            if ($serviceId === '' || ! is_numeric($price) || Arr::get($quotation, 'courier.is_deliver_to_point') === true) {
140
+                continue;
141
+            }
142
+
143
+            $service = (string) Arr::get($quotation, 'courier.service_name', '');
144
+
145
+            $quotes[] = new Quote(
146
+                serviceId: $serviceId,
147
+                courier: self::shortName($service, (string) Arr::get($quotation, 'courier.courier_name', '')),
148
+                service: $service,
149
+                logo: Arr::get($quotation, 'courier.courier_logo') ?: null,
150
+                price: (int) round(((float) $price) * 100),
151
+                pickup: (bool) Arr::get($quotation, 'courier.is_pickup', false),
152
+                dropoff: (bool) Arr::get($quotation, 'courier.is_dropoff', false),
153
+                delivery: self::deliveryTime(Arr::get($quotation, 'courier.delivery_duration')),
154
+                note: preg_match('/min\.?\s*(\d+)\s*parcel/i', $service, $match) === 1
155
+                    ? __('Pickup needs at least :count parcels', ['count' => $match[1]])
156
+                    : null,
157
+            );
158
+        }
159
+
160
+        usort($quotes, fn (Quote $a, Quote $b) => $a->price <=> $b->price);
161
+
162
+        return $quotes;
163
+    }
164
+
165
+    /**
166
+     * Book a courier for the order. EasyParcel takes the price from the merchant's credit.
167
+     * The order is updated with the shipment number, price, label and tracking (when EasyParcel already has them).
168
+     */
169
+    public function book(Store $store, Order $order, Parcel $parcel, string $serviceId, string $collectionDate, ?string $courier = null): void
170
+    {
171
+        $account = $this->accountOf($store);
172
+        $pickup = $this->pickupOf($store);
173
+        $address = $order->shipping_address;
174
+        $order->loadMissing('items');
175
+        $pieces = max(1, (int) $order->items->sum('quantity'));
176
+
177
+        $answer = $this->call($account, 'POST', 'shipment/submit_orders', [
178
+            'shipment' => [[
179
+                'reference' => Str::limit("{$store->name} #{$order->number}", 25, ''),
180
+                'service_id' => $serviceId,
181
+                'collection_date' => $collectionDate,
182
+                'weight' => $parcel->kilograms(),
183
+                'length' => $parcel->length,
184
+                'width' => $parcel->width,
185
+                'height' => $parcel->height,
186
+                'item' => $order->items->map(fn (OrderItem $item) => [
187
+                    'content' => Str::limit($item->name, 35, ''),
188
+                    'weight' => round(max($parcel->kilograms() / $pieces, 0.01), 2),
189
+                    'length' => $parcel->length,
190
+                    'width' => $parcel->width,
191
+                    'height' => $parcel->height,
192
+                    'currency_code' => 'MYR',
193
+                    'value' => self::ringgit($item->unit_price),
194
+                    'quantity' => $item->quantity,
195
+                ])->values()->all(),
196
+                'sender' => [
197
+                    'name' => $pickup['name'],
198
+                    'phone_number_country_code' => 'MY',
199
+                    'phone_number' => self::localPhone($pickup['phone']),
200
+                    'email' => $store->user->email,
201
+                    'address_1' => $pickup['line1'],
202
+                    'address_2' => $pickup['line2'] ?? '',
203
+                    'postcode' => $pickup['postcode'],
204
+                    'city' => $pickup['city'],
205
+                    'subdivision_code' => StateCodes::for($pickup['state']),
206
+                    'country_code' => 'MY',
207
+                ],
208
+                'receiver' => [
209
+                    'name' => $order->customer_name,
210
+                    'phone_number_country_code' => 'MY',
211
+                    'phone_number' => self::localPhone($order->customer_phone),
212
+                    'email' => $order->customer_email,
213
+                    'address_1' => $address['line1'],
214
+                    'address_2' => $address['line2'] ?? '',
215
+                    'postcode' => $address['postcode'],
216
+                    'city' => $address['city'],
217
+                    'subdivision_code' => StateCodes::for($address['state']),
218
+                    'country_code' => 'MY',
219
+                ],
220
+                // Paid extras stay off; the shopper gets our own "on its way" email with the tracking link.
221
+                'feature' => ['sms_tracking' => false, 'email_tracking' => false, 'whatsapp_tracking' => false],
222
+            ]],
223
+        ]);
224
+
225
+        $result = Arr::get($answer, 'data.0', []);
226
+        $this->failIfError($result);
227
+        $shipment = Arr::get($result, 'shipments.0', []);
228
+        $this->failIfError($shipment);
229
+
230
+        $number = (string) Arr::get($shipment, 'shipment_number', '');
231
+
232
+        if ($number === '') {
233
+            throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel did not confirm the booking. Check your EasyParcel account before trying again.'));
234
+        }
235
+
236
+        $paid = Arr::get($shipment, 'pricing_breakdown.total_paid_amount');
237
+
238
+        $order->shipment_number = $number;
239
+        $order->shipment_order_number = Arr::get($result, 'order_details.order_number') ?: null;
240
+        $order->shipment_cost = is_numeric($paid) ? (int) round(((float) $paid) * 100) : null;
241
+        // The short name the merchant picked ("J&T Express"), not the company's full name.
242
+        $order->shipping_courier = Str::limit((string) ($courier ?: Arr::get($shipment, 'courier') ?: 'EasyParcel'), 60, '');
243
+        $this->takeLabel($order, $shipment);
244
+        $order->save();
245
+    }
246
+
247
+    /**
248
+     * Ask EasyParcel again for a booked parcel's label and tracking number, which some couriers give a little later.
249
+     */
250
+    public function refreshLabel(Store $store, Order $order): void
251
+    {
252
+        $answer = $this->call($this->accountOf($store), 'POST', 'shipment/details', ['shipment_number' => $order->shipment_number]);
253
+        $data = (array) Arr::get($answer, 'data', []);
254
+        $details = Arr::get($data, '0.shipment_details') ?? Arr::get($data, 'shipment_details') ?? Arr::get($data, '0') ?? $data;
255
+
256
+        $this->takeLabel($order, is_array($details) ? $details : []);
257
+        $order->save();
258
+    }
259
+
260
+    /**
261
+     * @param  array<string, mixed>  $shipment
262
+     */
263
+    private function takeLabel(Order $order, array $shipment): void
264
+    {
265
+        $awb = trim((string) (Arr::get($shipment, 'awb_number') ?? ''));
266
+        $label = (string) (Arr::get($shipment, 'awb_url') ?: Arr::get($shipment, 'awb_urls_by_format.A4') ?: '');
267
+        $tracking = (string) (Arr::get($shipment, 'tracking_url') ?? '');
268
+
269
+        if ($awb !== '') {
270
+            $order->tracking_number = Str::limit($awb, 80, '');
271
+        }
272
+
273
+        if (str_starts_with($label, 'https://')) {
274
+            $order->label_url = $label;
275
+        }
276
+
277
+        if (str_starts_with($tracking, 'https://')) {
278
+            $order->tracking_url = $tracking;
279
+        }
280
+    }
281
+
282
+    /**
283
+     * One call to the Open API on the merchant's account. Renews the access token when it has run out.
284
+     *
285
+     * @param  array<string, mixed>  $body
286
+     * @return array<string, mixed>
287
+     */
288
+    private function call(EasyParcelAccount $account, string $method, string $path, array $body = []): array
289
+    {
290
+        if ($account->expires_at !== null && $account->expires_at->isBefore(now()->addSeconds(self::RENEW_EARLY))) {
291
+            $this->renew($account);
292
+        }
293
+
294
+        $response = $this->send($account, $method, $path, $body);
295
+
296
+        if ($response->status() === 401) {
297
+            $this->renew($account);
298
+            $response = $this->send($account, $method, $path, $body);
299
+
300
+            if ($response->status() === 401) {
301
+                throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
302
+            }
303
+        }
304
+
305
+        if ($response->status() === 429) {
306
+            throw new EasyParcelException(__('EasyParcel is busy. Please wait a minute and try again.'));
307
+        }
308
+
309
+        $json = (array) $response->json();
310
+
311
+        if ($response->failed()) {
312
+            throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel could not do this right now (error :code). Please try again.', ['code' => $response->status()]));
313
+        }
314
+
315
+        return $json;
316
+    }
317
+
318
+    /**
319
+     * @param  array<string, mixed>  $body
320
+     */
321
+    private function send(EasyParcelAccount $account, string $method, string $path, array $body): Response
322
+    {
323
+        $url = $this->baseUrl().'/open_api/'.($this->config['api_version'] ?? '2026-09').'/'.$path;
324
+
325
+        try {
326
+            $request = $this->http()->withToken($account->access_token);
327
+
328
+            return $method === 'GET' ? $request->get($url) : $request->post($url, $body);
329
+        } catch (ConnectionException) {
330
+            throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
331
+        }
332
+    }
333
+
334
+    private function renew(EasyParcelAccount $account): void
335
+    {
336
+        if (blank($account->refresh_token)) {
337
+            throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
338
+        }
339
+
340
+        try {
341
+            $tokens = $this->tokenRequest(['grant_type' => 'refresh_token', 'refresh_token' => $account->refresh_token]);
342
+        } catch (EasyParcelException $e) {
343
+            throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED, $e);
344
+        }
345
+
346
+        $this->saveTokens($account, $tokens);
347
+    }
348
+
349
+    /**
350
+     * @param  array<string, string>  $form
351
+     * @return array<string, mixed>
352
+     */
353
+    private function tokenRequest(array $form): array
354
+    {
355
+        if (! $this->isConfigured()) {
356
+            throw new EasyParcelException(__('EasyParcel is not set up on this app yet.'));
357
+        }
358
+
359
+        try {
360
+            $response = $this->http()
361
+                ->withBasicAuth((string) $this->config['client_id'], (string) $this->config['client_secret'])
362
+                ->asForm()
363
+                ->post($this->baseUrl().'/oauth/token', $form);
364
+        } catch (ConnectionException) {
365
+            throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
366
+        }
367
+
368
+        $json = (array) $response->json();
369
+        // Some answers wrap the tokens in "data".
370
+        $tokens = isset($json['access_token']) ? $json : (array) ($json['data'] ?? []);
371
+
372
+        if ($response->failed() || blank($tokens['access_token'] ?? null)) {
373
+            throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel did not accept the connection. Please try again.'));
374
+        }
375
+
376
+        return $tokens;
377
+    }
378
+
379
+    /**
380
+     * @param  array<string, mixed>  $tokens
381
+     */
382
+    private function saveTokens(EasyParcelAccount $account, array $tokens): void
383
+    {
384
+        $account->access_token = (string) $tokens['access_token'];
385
+        // Keep the old refresh token when EasyParcel does not send a new one.
386
+        $account->refresh_token = filled($tokens['refresh_token'] ?? null) ? (string) $tokens['refresh_token'] : $account->refresh_token;
387
+        $account->expires_at = is_numeric($tokens['expires_in'] ?? null) ? now()->addSeconds((int) $tokens['expires_in']) : null;
388
+        $account->save();
389
+    }
390
+
391
+    private function accountOf(Store $store): EasyParcelAccount
392
+    {
393
+        return $store->easyparcel ?? throw new EasyParcelException(__('Connect EasyParcel in Settings first.'), EasyParcelException::DISCONNECTED);
394
+    }
395
+
396
+    /**
397
+     * @return array{name: string, phone: string, line1: string, line2: string|null, city: string, postcode: string, state: string}
398
+     */
399
+    private function pickupOf(Store $store): array
400
+    {
401
+        return $store->pickup_address ?? throw new EasyParcelException(__('Add your pickup address in Settings first.'));
402
+    }
403
+
404
+    /**
405
+     * @param  array<string, mixed>  $result
406
+     */
407
+    private function failIfError(array $result): void
408
+    {
409
+        if (($result['status'] ?? null) !== 'error') {
410
+            return;
411
+        }
412
+
413
+        throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel could not do this. Please check the details and try again.'));
414
+    }
415
+
416
+    /**
417
+     * The most useful sentence in an EasyParcel error answer.
418
+     *
419
+     * @param  array<string, mixed>  $json
420
+     */
421
+    private static function messageOf(array $json): ?string
422
+    {
423
+        // Errors come as strings, as {code, message} objects, or as lists of those inside a list.
424
+        $errors = [];
425
+        $list = is_array($json['errors'] ?? null) ? $json['errors'] : [];
426
+        array_walk_recursive($list, function (mixed $value, mixed $key) use (&$errors) {
427
+            if (is_string($value) && ($key === 'message' || is_int($key)) && trim($value) !== '') {
428
+                $errors[] = trim($value);
429
+            }
430
+        });
431
+
432
+        // Not enough credit: say how much the parcel needs, so the merchant knows what to top up.
433
+        foreach (self::errorObjects($json['errors'] ?? []) as $error) {
434
+            if (($error['code'] ?? null) === 'InsufficientCreditBalance') {
435
+                $needed = Arr::get($error, 'data.total_amount');
436
+
437
+                return is_numeric($needed)
438
+                    ? __('Not enough EasyParcel credit: this parcel needs RM :amount. Top up your EasyParcel account and try again.', ['amount' => number_format((float) $needed, 2)])
439
+                    : __('Not enough EasyParcel credit. Top up your EasyParcel account and try again.');
440
+            }
441
+        }
442
+
443
+        if ($errors !== []) {
444
+            return 'EasyParcel: '.Str::limit(implode(' ', array_unique($errors)), 300);
445
+        }
446
+
447
+        foreach (['message', 'error_description', 'error'] as $key) {
448
+            if (is_string($json[$key] ?? null) && trim($json[$key]) !== '') {
449
+                return 'EasyParcel: '.Str::limit(trim($json[$key]), 300);
450
+            }
451
+        }
452
+
453
+        return null;
454
+    }
455
+
456
+    /**
457
+     * Every {code, message} object in an error list, however deeply it is wrapped.
458
+     *
459
+     * @return list<array<string, mixed>>
460
+     */
461
+    private static function errorObjects(mixed $errors): array
462
+    {
463
+        if (! is_array($errors)) {
464
+            return [];
465
+        }
466
+
467
+        if (isset($errors['message']) || isset($errors['code'])) {
468
+            return [$errors];
469
+        }
470
+
471
+        return array_merge([], ...array_map(self::errorObjects(...), array_values($errors)));
472
+    }
473
+
474
+    /**
475
+     * "J&T Express (Pick Up) (From Door to Door)" becomes "J&T Express". The company name is the fallback.
476
+     */
477
+    private static function shortName(string $service, string $company): string
478
+    {
479
+        $short = trim((string) preg_replace(['/\((?:[^()]|\([^()]*\))*\)/', '/\s+/'], ['', ' '], $service));
480
+
481
+        if ($short !== '') {
482
+            return $short;
483
+        }
484
+
485
+        $company = trim((string) preg_replace('/\s*(\((?:Malaysia|M)\)|Sdn\.?\s*Bhd\.?|Berhad)\s*/i', ' ', $company));
486
+
487
+        return $company !== '' ? preg_replace('/\s+/', ' ', $company) : 'Courier';
488
+    }
489
+
490
+    /**
491
+     * EasyParcel sends the delivery time as {"type":"days","value":"3"} (sometimes as a JSON string), or nothing.
492
+     */
493
+    private static function deliveryTime(mixed $duration): ?string
494
+    {
495
+        if (is_string($duration)) {
496
+            $decoded = json_decode($duration, true);
497
+            $duration = is_array($decoded) ? $decoded : $duration;
498
+        }
499
+
500
+        if (is_array($duration) && is_numeric($duration['value'] ?? null) && ($duration['type'] ?? 'days') === 'days') {
501
+            $days = (int) $duration['value'];
502
+
503
+            return $days <= 1 ? __('Next day') : __('About :count days', ['count' => $days]);
504
+        }
505
+
506
+        return is_string($duration) && trim($duration) !== '' ? Str::limit(trim($duration), 40) : null;
507
+    }
508
+
509
+    private function http(): PendingRequest
510
+    {
511
+        // Quotes can take up to a minute when couriers are asked live.
512
+        return Http::acceptJson()->timeout(70);
513
+    }
514
+
515
+    private function baseUrl(): string
516
+    {
517
+        return rtrim((string) ($this->config['base_url'] ?? 'https://api.easyparcel.com'), '/');
518
+    }
519
+
520
+    private static function ringgit(int $sen): float
521
+    {
522
+        return round($sen / 100, 2);
523
+    }
524
+
525
+    /**
526
+     * EasyParcel wants the number without Malaysia's 60, such as 123456789.
527
+     */
528
+    private static function localPhone(string $phone): string
529
+    {
530
+        $normalized = MalaysianPhone::normalize($phone);
531
+
532
+        return $normalized !== null ? substr($normalized, 2) : preg_replace('/\D/', '', $phone);
533
+    }
534
+}

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

1
+<?php
2
+
3
+namespace App\Commerce\Shipping\EasyParcel;
4
+
5
+use RuntimeException;
6
+
7
+/**
8
+ * Something went wrong talking to EasyParcel. The message is written for the merchant.
9
+ */
10
+final class EasyParcelException extends RuntimeException
11
+{
12
+    /** The connection no longer works (token expired or access removed): the merchant must connect again. */
13
+    public const int DISCONNECTED = 1;
14
+
15
+    public function disconnected(): bool
16
+    {
17
+        return $this->getCode() === self::DISCONNECTED;
18
+    }
19
+}

+ 21
- 0
app/Commerce/Shipping/EasyParcel/Parcel.php Просмотреть файл

1
+<?php
2
+
3
+namespace App\Commerce\Shipping\EasyParcel;
4
+
5
+/**
6
+ * The box being sent: weight in grams, size in centimetres.
7
+ */
8
+final readonly class Parcel
9
+{
10
+    public function __construct(
11
+        public int $grams,
12
+        public int $length,
13
+        public int $width,
14
+        public int $height,
15
+    ) {}
16
+
17
+    public function kilograms(): float
18
+    {
19
+        return round(max($this->grams, 10) / 1000, 2);
20
+    }
21
+}

+ 44
- 0
app/Commerce/Shipping/EasyParcel/Quote.php Просмотреть файл

1
+<?php
2
+
3
+namespace App\Commerce\Shipping\EasyParcel;
4
+
5
+/**
6
+ * One courier service EasyParcel offers for a parcel, with its price.
7
+ */
8
+final readonly class Quote
9
+{
10
+    public function __construct(
11
+        public string $serviceId,
12
+        public string $courier,
13
+        public string $service,
14
+        public ?string $logo,
15
+        /** In sen. */
16
+        public int $price,
17
+        /** The courier comes to the merchant's pickup address. */
18
+        public bool $pickup,
19
+        /** The merchant takes the parcel to a counter. */
20
+        public bool $dropoff,
21
+        /** Such as "About 3 days", when EasyParcel says. */
22
+        public ?string $delivery,
23
+        /** Something the merchant must know, such as "Pickup needs at least 3 parcels". */
24
+        public ?string $note = null,
25
+    ) {}
26
+
27
+    /**
28
+     * @return array<string, mixed>
29
+     */
30
+    public function toArray(): array
31
+    {
32
+        return [
33
+            'service_id' => $this->serviceId,
34
+            'courier' => $this->courier,
35
+            'service' => $this->service,
36
+            'logo' => $this->logo,
37
+            'price' => $this->price / 100,
38
+            'pickup' => $this->pickup,
39
+            'dropoff' => $this->dropoff,
40
+            'delivery' => $this->delivery,
41
+            'note' => $this->note,
42
+        ];
43
+    }
44
+}

+ 38
- 0
app/Commerce/Shipping/EasyParcel/StateCodes.php Просмотреть файл

1
+<?php
2
+
3
+namespace App\Commerce\Shipping\EasyParcel;
4
+
5
+/**
6
+ * EasyParcel names Malaysian states by their ISO 3166-2 code, such as MY-07 for Pulau Pinang.
7
+ */
8
+final class StateCodes
9
+{
10
+    /**
11
+     * Keyed by the names in MalaysianStates::ALL.
12
+     *
13
+     * @var array<string, string>
14
+     */
15
+    public const array CODES = [
16
+        'Johor' => 'MY-01',
17
+        'Kedah' => 'MY-02',
18
+        'Kelantan' => 'MY-03',
19
+        'Melaka' => 'MY-04',
20
+        'Negeri Sembilan' => 'MY-05',
21
+        'Pahang' => 'MY-06',
22
+        'Pulau Pinang' => 'MY-07',
23
+        'Perak' => 'MY-08',
24
+        'Perlis' => 'MY-09',
25
+        'Selangor' => 'MY-10',
26
+        'Terengganu' => 'MY-11',
27
+        'Sabah' => 'MY-12',
28
+        'Sarawak' => 'MY-13',
29
+        'Kuala Lumpur' => 'MY-14',
30
+        'Labuan' => 'MY-15',
31
+        'Putrajaya' => 'MY-16',
32
+    ];
33
+
34
+    public static function for(string $state): ?string
35
+    {
36
+        return self::CODES[$state] ?? null;
37
+    }
38
+}

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

1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Shipping\EasyParcel\EasyParcel;
6
+use App\Commerce\Shipping\EasyParcel\EasyParcelException;
7
+use App\Models\Store;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Support\Str;
11
+use Inertia\Inertia;
12
+use Symfony\Component\HttpFoundation\Response;
13
+
14
+/**
15
+ * Connecting a store to the merchant's own EasyParcel account: they sign in on EasyParcel, click Allow, and come back.
16
+ */
17
+class EasyParcelController extends Controller
18
+{
19
+    private const string SESSION_KEY = 'easyparcel.connect';
20
+
21
+    public function connect(Request $request, string $slug, EasyParcel $easyparcel): Response
22
+    {
23
+        $store = $this->ownedStore($request, $slug);
24
+
25
+        if (! $easyparcel->isConfigured()) {
26
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('EasyParcel is not set up on this app yet.')]);
27
+
28
+            return to_route('stores.settings', $store->slug);
29
+        }
30
+
31
+        $state = Str::random(40);
32
+        $verifier = Str::random(64);
33
+        $request->session()->put(self::SESSION_KEY, ['state' => $state, 'verifier' => $verifier, 'store' => $store->id]);
34
+
35
+        // A full page visit to EasyParcel, not an Inertia one.
36
+        return Inertia::location($easyparcel->authorizeUrl($state, $verifier));
37
+    }
38
+
39
+    /**
40
+     * EasyParcel sends the merchant back here, with a code when they clicked Allow.
41
+     */
42
+    public function callback(Request $request, EasyParcel $easyparcel): RedirectResponse
43
+    {
44
+        $pending = $request->session()->pull(self::SESSION_KEY);
45
+        $store = is_array($pending) ? $request->user()->stores()->whereKey($pending['store'] ?? 0)->first() : null;
46
+
47
+        if ($store === null || ! hash_equals((string) ($pending['state'] ?? ''), (string) $request->query('state', ''))) {
48
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('That EasyParcel link has expired. Please click Connect EasyParcel again.')]);
49
+
50
+            return to_route('dashboard');
51
+        }
52
+
53
+        $code = (string) $request->query('code', '');
54
+
55
+        if ($code === '') {
56
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('EasyParcel was not connected.')]);
57
+
58
+            return to_route('stores.settings', $store->slug);
59
+        }
60
+
61
+        try {
62
+            $account = $easyparcel->connect($store, $code, (string) $pending['verifier']);
63
+        } catch (EasyParcelException $e) {
64
+            Inertia::flash('toast', ['type' => 'error', 'message' => $e->getMessage()]);
65
+
66
+            return to_route('stores.settings', $store->slug);
67
+        }
68
+
69
+        Inertia::flash('toast', ['type' => 'success', 'message' => $account->account_name !== null
70
+            ? __('EasyParcel connected: :name.', ['name' => $account->account_name])
71
+            : __('EasyParcel connected.')]);
72
+
73
+        return to_route('stores.settings', $store->slug);
74
+    }
75
+
76
+    public function disconnect(Request $request, string $slug): RedirectResponse
77
+    {
78
+        $store = $this->ownedStore($request, $slug);
79
+        $store->easyparcel()->delete();
80
+
81
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('EasyParcel disconnected. Booked parcels are not affected.')]);
82
+
83
+        return to_route('stores.settings', $store->slug);
84
+    }
85
+
86
+    private function ownedStore(Request $request, string $slug): Store
87
+    {
88
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
89
+    }
90
+}

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

3
 namespace App\Http\Controllers;
3
 namespace App\Http\Controllers;
4
 
4
 
5
 use App\Commerce\Couriers;
5
 use App\Commerce\Couriers;
6
+use App\Commerce\Shipping\EasyParcel\EasyParcel;
7
+use App\Commerce\Shipping\EasyParcel\EasyParcelException;
8
+use App\Commerce\Shipping\EasyParcel\Parcel;
9
+use App\Commerce\Shipping\EasyParcel\Quote;
6
 use App\Mail\OrderShipped;
10
 use App\Mail\OrderShipped;
7
 use App\Models\Order;
11
 use App\Models\Order;
8
 use App\Models\Store;
12
 use App\Models\Store;
9
 use App\Support\MalaysianPhone;
13
 use App\Support\MalaysianPhone;
14
+use Carbon\CarbonInterface;
10
 use Illuminate\Http\RedirectResponse;
15
 use Illuminate\Http\RedirectResponse;
11
 use Illuminate\Http\Request;
16
 use Illuminate\Http\Request;
12
 use Illuminate\Support\Facades\Mail;
17
 use Illuminate\Support\Facades\Mail;
34
         ]);
39
         ]);
35
     }
40
     }
36
 
41
 
37
-    public function show(Request $request, string $slug, int $order): Response
42
+    public function show(Request $request, string $slug, int $order, EasyParcel $easyparcel): Response
38
     {
43
     {
39
         $store = $this->ownedStore($request, $slug);
44
         $store = $this->ownedStore($request, $slug);
40
         $order = $store->orders()->with('items')->whereKey($order)->firstOrFail();
45
         $order = $store->orders()->with('items')->whereKey($order)->firstOrFail();
41
         $customerWhatsapp = MalaysianPhone::normalize($order->customer_phone);
46
         $customerWhatsapp = MalaysianPhone::normalize($order->customer_phone);
47
+        $size = $store->parcel_size ?? self::DEFAULT_SIZE;
42
 
48
 
43
         return Inertia::render('stores/orders/show', [
49
         return Inertia::render('stores/orders/show', [
44
             'store' => ['name' => $store->name, 'slug' => $store->slug],
50
             'store' => ['name' => $store->name, 'slug' => $store->slug],
45
             'order' => $order->toDisplay(),
51
             'order' => $order->toDisplay(),
46
             'couriers' => Couriers::ALL,
52
             'couriers' => Couriers::ALL,
53
+            // Booking a courier through the merchant's EasyParcel account.
54
+            'easyparcel' => [
55
+                'connected' => $store->easyparcel()->exists(),
56
+                'has_pickup_address' => $store->pickup_address !== null,
57
+                'parcel' => ['weight' => $store->parcel_weight / 1000, ...$size],
58
+                'collection_date' => self::firstCollectionDate()->toDateString(),
59
+            ],
60
+            // Asked for only when the merchant clicks "See courier prices", with the parcel they typed.
61
+            'courier_quotes' => Inertia::optional(fn () => $this->quotes($request, $store, $order, $easyparcel)),
47
             // A chat with the shopper, with a first message already typed in the store's language.
62
             // A chat with the shopper, with a first message already typed in the store's language.
48
             'customer_whatsapp_url' => $customerWhatsapp !== null
63
             'customer_whatsapp_url' => $customerWhatsapp !== null
49
                 ? MalaysianPhone::whatsappLink($customerWhatsapp, $store->language->value === 'ms'
64
                 ? MalaysianPhone::whatsappLink($customerWhatsapp, $store->language->value === 'ms'
89
         return to_route('stores.orders.show', [$store->slug, $order->id]);
104
         return to_route('stores.orders.show', [$store->slug, $order->id]);
90
     }
105
     }
91
 
106
 
107
+    /**
108
+     * Book the chosen courier on the merchant's EasyParcel account, and print its label.
109
+     * The shopper gets the "on its way" email once the courier's tracking number is known.
110
+     */
111
+    public function book(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse
112
+    {
113
+        $store = $this->ownedStore($request, $slug);
114
+        $order = $store->orders()->whereKey($order)->firstOrFail();
115
+
116
+        abort_unless($order->isPaid(), 404);
117
+
118
+        if ($order->shipment_number !== null) {
119
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('A courier is already booked for this order.')]);
120
+
121
+            return to_route('stores.orders.show', [$store->slug, $order->id]);
122
+        }
123
+
124
+        $today = now(self::TIMEZONE)->startOfDay();
125
+        $lastDay = $today->addDays(14);
126
+        $validated = $request->validate([
127
+            ...self::parcelRules(),
128
+            'service_id' => ['required', 'string', 'max:40'],
129
+            'courier' => ['nullable', 'string', 'max:60'],
130
+            'collection_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:'.$today->toDateString(), 'before_or_equal:'.$lastDay->toDateString()],
131
+        ], [
132
+            'collection_date.after_or_equal' => __('Choose today or a later day.'),
133
+            'collection_date.before_or_equal' => __('Choose a day within the next two weeks.'),
134
+        ]);
135
+
136
+        try {
137
+            $easyparcel->book($store, $order, self::parcelFrom($validated), $validated['service_id'], $validated['collection_date'], $validated['courier'] ?? null);
138
+        } catch (EasyParcelException $e) {
139
+            return back()->withErrors(['booking' => $e->getMessage()]);
140
+        }
141
+
142
+        $emailed = $this->markShipped($order);
143
+
144
+        Inertia::flash('toast', ['type' => 'success', 'message' => match (true) {
145
+            $emailed => __('Courier booked. Print the label and stick it on the parcel. We emailed the customer.'),
146
+            $order->tracking_number !== null => __('Courier booked. Print the label and stick it on the parcel.'),
147
+            default => __('Courier booked. The label is being prepared; check again in a minute.'),
148
+        }]);
149
+
150
+        return to_route('stores.orders.show', [$store->slug, $order->id]);
151
+    }
152
+
153
+    /**
154
+     * Some couriers give the label and tracking number a little after booking. Ask EasyParcel again.
155
+     */
156
+    public function refreshLabel(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse
157
+    {
158
+        $store = $this->ownedStore($request, $slug);
159
+        $order = $store->orders()->whereKey($order)->whereNotNull('shipment_number')->firstOrFail();
160
+
161
+        try {
162
+            $easyparcel->refreshLabel($store, $order);
163
+        } catch (EasyParcelException $e) {
164
+            return back()->withErrors(['booking' => $e->getMessage()]);
165
+        }
166
+
167
+        $emailed = $this->markShipped($order);
168
+
169
+        Inertia::flash('toast', $order->label_url !== null
170
+            ? ['type' => 'success', 'message' => $emailed ? __('The label is ready. We emailed the customer.') : __('The label is ready.')]
171
+            : ['type' => 'info', 'message' => __('The label is not ready yet. Try again in a minute.')]);
172
+
173
+        return to_route('stores.orders.show', [$store->slug, $order->id]);
174
+    }
175
+
176
+    /** A box most small parcels fit, in cm, when the merchant has not set their own. */
177
+    public const array DEFAULT_SIZE = ['length' => 20, 'width' => 15, 'height' => 10];
178
+
179
+    private const string TIMEZONE = 'Asia/Kuala_Lumpur';
180
+
181
+    /**
182
+     * @return list<array<string, mixed>>|array{error: string}
183
+     */
184
+    private function quotes(Request $request, Store $store, Order $order, EasyParcel $easyparcel): array
185
+    {
186
+        $validator = validator($request->query(), self::parcelRules());
187
+
188
+        if ($validator->fails()) {
189
+            return ['error' => (string) $validator->errors()->first()];
190
+        }
191
+
192
+        try {
193
+            return array_map(fn (Quote $quote) => $quote->toArray(), $easyparcel->quotes($store, $order, self::parcelFrom($validator->validated())));
194
+        } catch (EasyParcelException $e) {
195
+            return ['error' => $e->getMessage()];
196
+        }
197
+    }
198
+
199
+    /**
200
+     * @return array<string, list<string>>
201
+     */
202
+    private static function parcelRules(): array
203
+    {
204
+        return [
205
+            'weight' => ['required', 'numeric', 'min:0.01', 'max:70'],
206
+            'length' => ['required', 'integer', 'min:1', 'max:200'],
207
+            'width' => ['required', 'integer', 'min:1', 'max:200'],
208
+            'height' => ['required', 'integer', 'min:1', 'max:200'],
209
+        ];
210
+    }
211
+
212
+    /**
213
+     * @param  array<string, mixed>  $input
214
+     */
215
+    private static function parcelFrom(array $input): Parcel
216
+    {
217
+        return new Parcel((int) round(((float) $input['weight']) * 1000), (int) $input['length'], (int) $input['width'], (int) $input['height']);
218
+    }
219
+
220
+    /**
221
+     * Couriers collect on working days, and same-day collection is only booked before noon.
222
+     */
223
+    private static function firstCollectionDate(): CarbonInterface
224
+    {
225
+        $now = now(self::TIMEZONE);
226
+        $day = ($now->hour < 12 ? $now : $now->addDay())->startOfDay();
227
+
228
+        return $day->isSunday() ? $day->addDay() : $day;
229
+    }
230
+
231
+    /**
232
+     * Once a booked parcel has its tracking number, the order counts as shipped and the shopper is emailed once.
233
+     */
234
+    private function markShipped(Order $order): bool
235
+    {
236
+        if ($order->shipped_at !== null || $order->tracking_number === null) {
237
+            return false;
238
+        }
239
+
240
+        $order->shipped_at = now();
241
+        $order->save();
242
+        Mail::to($order->customer_email)->send(new OrderShipped($order));
243
+
244
+        return true;
245
+    }
246
+
92
     private function ownedStore(Request $request, string $slug): Store
247
     private function ownedStore(Request $request, string $slug): Store
93
     {
248
     {
94
         return $request->user()->stores()->where('slug', $slug)->firstOrFail();
249
         return $request->user()->stores()->where('slug', $slug)->firstOrFail();

+ 100
- 2
app/Http/Controllers/StoreSettingsController.php Просмотреть файл

2
 
2
 
3
 namespace App\Http\Controllers;
3
 namespace App\Http\Controllers;
4
 
4
 
5
+use App\Commerce\MalaysianStates;
6
+use App\Commerce\Shipping\EasyParcel\EasyParcel;
7
+use App\Commerce\Shipping\EasyParcel\EasyParcelException;
8
+use App\Models\EasyParcelAccount;
5
 use App\Models\Store;
9
 use App\Models\Store;
6
 use App\Storefront\Announcements;
10
 use App\Storefront\Announcements;
7
 use App\Support\MalaysianPhone;
11
 use App\Support\MalaysianPhone;
8
 use Illuminate\Http\RedirectResponse;
12
 use Illuminate\Http\RedirectResponse;
9
 use Illuminate\Http\Request;
13
 use Illuminate\Http\Request;
14
+use Illuminate\Validation\Rule;
10
 use Illuminate\Validation\ValidationException;
15
 use Illuminate\Validation\ValidationException;
11
 use Inertia\Inertia;
16
 use Inertia\Inertia;
12
 use Inertia\Response;
17
 use Inertia\Response;
13
 
18
 
14
 /**
19
 /**
15
- * Store-wide settings that are not part of the design: WhatsApp number, shipping fees and the announcement bar.
20
+ * Store-wide settings that are not part of the design: WhatsApp number, shipping fees, EasyParcel and the announcement bar.
16
  */
21
  */
17
 class StoreSettingsController extends Controller
22
 class StoreSettingsController extends Controller
18
 {
23
 {
19
-    public function edit(Request $request, string $slug): Response
24
+    public function edit(Request $request, string $slug, EasyParcel $easyparcel): Response
20
     {
25
     {
21
         $store = $this->ownedStore($request, $slug);
26
         $store = $this->ownedStore($request, $slug);
27
+        $account = $store->easyparcel;
28
+        $pickup = $store->pickup_address;
29
+        $size = $store->parcel_size ?? OrderController::DEFAULT_SIZE;
22
 
30
 
23
         return Inertia::render('stores/settings', [
31
         return Inertia::render('stores/settings', [
24
             'store' => ['name' => $store->name, 'slug' => $store->slug],
32
             'store' => ['name' => $store->name, 'slug' => $store->slug],
30
                 'announcement_enabled' => $store->announcement_enabled,
38
                 'announcement_enabled' => $store->announcement_enabled,
31
                 // One line per message, the way the form edits them.
39
                 // One line per message, the way the form edits them.
32
                 'announcement_messages' => implode("\n", $store->announcement_messages ?? []),
40
                 'announcement_messages' => implode("\n", $store->announcement_messages ?? []),
41
+                'pickup' => [
42
+                    'name' => $pickup['name'] ?? '',
43
+                    'phone' => $pickup['phone'] ?? '',
44
+                    'line1' => $pickup['line1'] ?? '',
45
+                    'line2' => $pickup['line2'] ?? '',
46
+                    'city' => $pickup['city'] ?? '',
47
+                    'postcode' => $pickup['postcode'] ?? '',
48
+                    'state' => $pickup['state'] ?? '',
49
+                ],
50
+                'parcel_weight' => rtrim(rtrim(number_format($store->parcel_weight / 1000, 2, '.', ''), '0'), '.'),
51
+                'parcel_length' => (string) $size['length'],
52
+                'parcel_width' => (string) $size['width'],
53
+                'parcel_height' => (string) $size['height'],
33
             ],
54
             ],
55
+            'states' => MalaysianStates::ALL,
56
+            'easyparcel' => [
57
+                // False until the app's own EasyParcel keys are in .env.local.
58
+                'available' => $easyparcel->isConfigured(),
59
+                'connected' => $account !== null,
60
+                'account_name' => $account?->account_name,
61
+                'redirect_uri' => $easyparcel->redirectUri(),
62
+            ],
63
+            // Asked from EasyParcel after the page shows, so a slow answer never holds up Settings.
64
+            'easyparcelBalance' => $account !== null ? Inertia::defer(fn () => self::balance($easyparcel, $account)) : null,
34
             // What the store adds by itself today, so the merchant sees the whole bar.
65
             // What the store adds by itself today, so the merchant sees the whole bar.
35
             'automaticAnnouncements' => Announcements::automatic($store, $store->automaticDiscounts()->where('active', true)->orderByDesc('value')->get()->filter->isLive()->values()),
66
             'automaticAnnouncements' => Announcements::automatic($store, $store->automaticDiscounts()->where('active', true)->orderByDesc('value')->get()->filter->isLive()->values()),
36
         ]);
67
         ]);
48
             'announcement_enabled' => ['boolean'],
79
             'announcement_enabled' => ['boolean'],
49
             // One message per line.
80
             // One message per line.
50
             'announcement_messages' => ['nullable', 'string', 'max:400'],
81
             'announcement_messages' => ['nullable', 'string', 'max:400'],
82
+            // Where couriers collect parcels. All or nothing.
83
+            'pickup_name' => ['nullable', 'string', 'max:60'],
84
+            'pickup_phone' => ['nullable', 'string', 'max:30', 'required_with:pickup_line1'],
85
+            'pickup_line1' => ['nullable', 'string', 'max:100', 'required_with:pickup_name,pickup_phone,pickup_city,pickup_postcode'],
86
+            'pickup_line2' => ['nullable', 'string', 'max:100'],
87
+            'pickup_city' => ['nullable', 'string', 'max:60', 'required_with:pickup_line1'],
88
+            'pickup_postcode' => ['nullable', 'regex:/^\d{5}$/', 'required_with:pickup_line1'],
89
+            'pickup_state' => ['nullable', Rule::in(MalaysianStates::ALL), 'required_with:pickup_line1'],
90
+            'parcel_weight' => ['nullable', 'numeric', 'min:0.01', 'max:70'],
91
+            'parcel_length' => ['nullable', 'integer', 'min:1', 'max:200'],
92
+            'parcel_width' => ['nullable', 'integer', 'min:1', 'max:200'],
93
+            'parcel_height' => ['nullable', 'integer', 'min:1', 'max:200'],
94
+        ], [
95
+            'pickup_postcode.regex' => __('Enter a 5-digit postcode.'),
96
+            'pickup_line1.required_with' => __('Enter the street address.'),
97
+            'pickup_phone.required_with' => __('Enter a phone number the courier can call.'),
98
+            'pickup_city.required_with' => __('Enter the town or city.'),
99
+            'pickup_postcode.required_with' => __('Enter the postcode.'),
100
+            'pickup_state.required_with' => __('Choose the state.'),
51
         ]);
101
         ]);
52
 
102
 
103
+        $pickup = null;
104
+
105
+        if (filled($validated['pickup_line1'] ?? null)) {
106
+            $phone = MalaysianPhone::normalize($validated['pickup_phone'] ?? null);
107
+
108
+            if ($phone === null) {
109
+                throw ValidationException::withMessages(['pickup_phone' => __('Enter a Malaysian phone number, such as 012-345 6789.')]);
110
+            }
111
+
112
+            $pickup = [
113
+                'name' => trim((string) ($validated['pickup_name'] ?? '')) ?: $store->name,
114
+                'phone' => $phone,
115
+                'line1' => trim($validated['pickup_line1']),
116
+                'line2' => filled($validated['pickup_line2'] ?? null) ? trim($validated['pickup_line2']) : null,
117
+                'city' => trim($validated['pickup_city']),
118
+                'postcode' => $validated['pickup_postcode'],
119
+                'state' => $validated['pickup_state'],
120
+            ];
121
+        }
122
+
53
         $messages = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($validated['announcement_messages'] ?? '')) ?: [])));
123
         $messages = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($validated['announcement_messages'] ?? '')) ?: [])));
54
 
124
 
55
         if (count($messages) > Announcements::MAX_OWN) {
125
         if (count($messages) > Announcements::MAX_OWN) {
80
         $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
150
         $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
81
         $store->announcement_enabled = (bool) ($validated['announcement_enabled'] ?? false);
151
         $store->announcement_enabled = (bool) ($validated['announcement_enabled'] ?? false);
82
         $store->announcement_messages = $messages === [] ? null : $messages;
152
         $store->announcement_messages = $messages === [] ? null : $messages;
153
+        $store->pickup_address = $pickup;
154
+
155
+        // The usual parcel. Left as it was when the form does not send it.
156
+        if (filled($validated['parcel_weight'] ?? null)) {
157
+            $store->parcel_weight = (int) round(((float) $validated['parcel_weight']) * 1000);
158
+        }
159
+
160
+        if (filled($validated['parcel_length'] ?? null) && filled($validated['parcel_width'] ?? null) && filled($validated['parcel_height'] ?? null)) {
161
+            $store->parcel_size = [
162
+                'length' => (int) $validated['parcel_length'],
163
+                'width' => (int) $validated['parcel_width'],
164
+                'height' => (int) $validated['parcel_height'],
165
+            ];
166
+        }
83
         $store->save();
167
         $store->save();
84
 
168
 
85
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
169
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
87
         return to_route('stores.settings', $store->slug);
171
         return to_route('stores.settings', $store->slug);
88
     }
172
     }
89
 
173
 
174
+    /**
175
+     * @return array{amount: float|null, error: string|null}
176
+     */
177
+    private static function balance(EasyParcel $easyparcel, EasyParcelAccount $account): array
178
+    {
179
+        try {
180
+            $sen = $easyparcel->balance($account);
181
+
182
+            return ['amount' => $sen !== null ? $sen / 100 : null, 'error' => null];
183
+        } catch (EasyParcelException $e) {
184
+            return ['amount' => null, 'error' => $e->getMessage()];
185
+        }
186
+    }
187
+
90
     private static function sen(mixed $ringgit): int
188
     private static function sen(mixed $ringgit): int
91
     {
189
     {
92
         return (int) round(((float) $ringgit) * 100);
190
         return (int) round(((float) $ringgit) * 100);

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

1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Carbon\CarbonInterface;
6
+use Illuminate\Database\Eloquent\Attributes\Fillable;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
+
10
+/**
11
+ * A store's connected EasyParcel account. Parcels booked from the store are paid from its credit.
12
+ *
13
+ * @property int $id
14
+ * @property int $store_id
15
+ * @property string|null $account_name
16
+ * @property string $access_token
17
+ * @property string|null $refresh_token
18
+ * @property CarbonInterface|null $expires_at
19
+ * @property-read Store $store
20
+ */
21
+#[Fillable(['account_name', 'access_token', 'refresh_token', 'expires_at'])]
22
+class EasyParcelAccount extends Model
23
+{
24
+    protected $table = 'easyparcel_accounts';
25
+
26
+    protected $hidden = ['access_token', 'refresh_token'];
27
+
28
+    /**
29
+     * @return BelongsTo<Store, $this>
30
+     */
31
+    public function store(): BelongsTo
32
+    {
33
+        return $this->belongsTo(Store::class);
34
+    }
35
+
36
+    /**
37
+     * @return array<string, string>
38
+     */
39
+    protected function casts(): array
40
+    {
41
+        return [
42
+            'access_token' => 'encrypted',
43
+            'refresh_token' => 'encrypted',
44
+            'expires_at' => 'datetime',
45
+        ];
46
+    }
47
+}

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

40
  * @property CarbonInterface|null $shipped_at
40
  * @property CarbonInterface|null $shipped_at
41
  * @property string|null $shipping_courier
41
  * @property string|null $shipping_courier
42
  * @property string|null $tracking_number
42
  * @property string|null $tracking_number
43
+ * @property string|null $shipment_number EasyParcel's number for the booked parcel, such as ES-2602-4VW9E
44
+ * @property string|null $shipment_order_number EasyParcel's order number, such as EI-2602-4P2SK
45
+ * @property int|null $shipment_cost What the merchant paid EasyParcel, in sen
46
+ * @property string|null $label_url The courier label (AWB) to print
47
+ * @property string|null $tracking_url
43
  * @property CarbonInterface|null $created_at
48
  * @property CarbonInterface|null $created_at
44
  * @property CarbonInterface|null $updated_at
49
  * @property CarbonInterface|null $updated_at
45
  * @property-read Store $store
50
  * @property-read Store $store
98
             'shipped_at' => $this->shipped_at?->toIso8601String(),
103
             'shipped_at' => $this->shipped_at?->toIso8601String(),
99
             'shipping_courier' => $this->shipping_courier,
104
             'shipping_courier' => $this->shipping_courier,
100
             'tracking_number' => $this->tracking_number,
105
             'tracking_number' => $this->tracking_number,
106
+            'shipment' => $this->shipment_number === null ? null : [
107
+                'number' => $this->shipment_number,
108
+                'cost' => $this->shipment_cost !== null ? $this->shipment_cost / 100 : null,
109
+                'label_url' => $this->label_url ?: null,
110
+                'tracking_url' => $this->tracking_url ?: null,
111
+            ],
101
             'created_at' => $this->created_at?->toIso8601String(),
112
             'created_at' => $this->created_at?->toIso8601String(),
102
             'items' => $this->items->map(fn (OrderItem $item) => [
113
             'items' => $this->items->map(fn (OrderItem $item) => [
103
                 'id' => $item->id,
114
                 'id' => $item->id,

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

13
 use Illuminate\Database\Eloquent\Model;
13
 use Illuminate\Database\Eloquent\Model;
14
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
14
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
15
 use Illuminate\Database\Eloquent\Relations\HasMany;
15
 use Illuminate\Database\Eloquent\Relations\HasMany;
16
+use Illuminate\Database\Eloquent\Relations\HasOne;
16
 use Illuminate\Support\Carbon;
17
 use Illuminate\Support\Carbon;
17
 use Illuminate\Support\Str;
18
 use Illuminate\Support\Str;
18
 
19
 
32
  * @property int $shipping_west
33
  * @property int $shipping_west
33
  * @property int $shipping_east
34
  * @property int $shipping_east
34
  * @property int|null $free_shipping_over
35
  * @property int|null $free_shipping_over
36
+ * @property array{name: string, phone: string, line1: string, line2: string|null, city: string, postcode: string, state: string}|null $pickup_address Where couriers collect parcels
37
+ * @property int $parcel_weight The usual parcel's weight in grams
38
+ * @property array{length: int, width: int, height: int}|null $parcel_size The usual parcel's size in cm
35
  * @property bool $announcement_enabled
39
  * @property bool $announcement_enabled
36
  * @property list<string>|null $announcement_messages The merchant's own announcement lines
40
  * @property list<string>|null $announcement_messages The merchant's own announcement lines
37
  * @property array<string, mixed>|null $published_plan
41
  * @property array<string, mixed>|null $published_plan
173
         return $this->hasMany(AutomaticDiscount::class);
177
         return $this->hasMany(AutomaticDiscount::class);
174
     }
178
     }
175
 
179
 
180
+    /**
181
+     * The EasyParcel account the merchant connected, if any.
182
+     *
183
+     * @return HasOne<EasyParcelAccount, $this>
184
+     */
185
+    public function easyparcel(): HasOne
186
+    {
187
+        return $this->hasOne(EasyParcelAccount::class);
188
+    }
189
+
176
     /**
190
     /**
177
      * @return HasMany<Order, $this>
191
      * @return HasMany<Order, $this>
178
      */
192
      */
210
             'free_shipping_over' => 'integer',
224
             'free_shipping_over' => 'integer',
211
             'announcement_enabled' => 'boolean',
225
             'announcement_enabled' => 'boolean',
212
             'announcement_messages' => 'array',
226
             'announcement_messages' => 'array',
227
+            'pickup_address' => 'array',
228
+            'parcel_weight' => 'integer',
229
+            'parcel_size' => 'array',
213
         ];
230
         ];
214
     }
231
     }
215
 }
232
 }

+ 2
- 0
app/Providers/AppServiceProvider.php Просмотреть файл

6
 use App\Billing\SubscriptionGateway;
6
 use App\Billing\SubscriptionGateway;
7
 use App\Commerce\Payments\PaymentGateway;
7
 use App\Commerce\Payments\PaymentGateway;
8
 use App\Commerce\Payments\StripeGateway;
8
 use App\Commerce\Payments\StripeGateway;
9
+use App\Commerce\Shipping\EasyParcel\EasyParcel;
9
 use App\Commerce\Shipping\FlatRateShipping;
10
 use App\Commerce\Shipping\FlatRateShipping;
10
 use App\Commerce\Shipping\ShippingProvider;
11
 use App\Commerce\Shipping\ShippingProvider;
11
 use Carbon\CarbonImmutable;
12
 use Carbon\CarbonImmutable;
25
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
26
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
26
         $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
27
         $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
27
         $this->app->bind(ShippingProvider::class, FlatRateShipping::class);
28
         $this->app->bind(ShippingProvider::class, FlatRateShipping::class);
29
+        $this->app->bind(EasyParcel::class, fn () => EasyParcel::fromConfig());
28
     }
30
     }
29
 
31
 
30
     /**
32
     /**

+ 8
- 0
config/services.php Просмотреть файл

44
         'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
44
         'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
45
     ],
45
     ],
46
 
46
 
47
+    'easyparcel' => [
48
+        // From the app made in EasyParcel's Developer Hub (developer.easyparcel.com). Each merchant then connects their own account.
49
+        'client_id' => env('EASYPARCEL_CLIENT_ID'),
50
+        'client_secret' => env('EASYPARCEL_CLIENT_SECRET'),
51
+        'base_url' => env('EASYPARCEL_BASE_URL', 'https://api.easyparcel.com'),
52
+        'api_version' => env('EASYPARCEL_API_VERSION', '2026-09'),
53
+    ],
54
+
47
 ];
55
 ];

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

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
+    /**
10
+     * EasyParcel: the merchant's connected account, where parcels are collected from, and the courier booked for an order.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::create('easyparcel_accounts', function (Blueprint $table) {
15
+            $table->id();
16
+            $table->foreignId('store_id')->unique()->constrained()->cascadeOnDelete();
17
+            $table->string('account_name')->nullable();
18
+            // Kept encrypted. They let us act on the merchant's EasyParcel account.
19
+            $table->text('access_token');
20
+            $table->text('refresh_token')->nullable();
21
+            $table->timestamp('expires_at')->nullable();
22
+            $table->timestamps();
23
+        });
24
+
25
+        Schema::table('stores', function (Blueprint $table) {
26
+            // Where couriers collect parcels from: name, phone, line1, line2, city, postcode, state.
27
+            $table->json('pickup_address')->nullable()->after('free_shipping_over');
28
+            // The usual parcel, used to fill in the booking form: weight in grams, size in cm.
29
+            $table->unsignedInteger('parcel_weight')->default(1000)->after('pickup_address');
30
+            $table->json('parcel_size')->nullable()->after('parcel_weight');
31
+        });
32
+
33
+        Schema::table('orders', function (Blueprint $table) {
34
+            $table->string('shipment_number')->nullable()->after('tracking_number');
35
+            $table->string('shipment_order_number')->nullable()->after('shipment_number');
36
+            $table->unsignedInteger('shipment_cost')->nullable()->after('shipment_order_number');
37
+            $table->text('label_url')->nullable()->after('shipment_cost');
38
+            $table->text('tracking_url')->nullable()->after('label_url');
39
+        });
40
+    }
41
+
42
+    public function down(): void
43
+    {
44
+        Schema::table('orders', function (Blueprint $table) {
45
+            $table->dropColumn(['shipment_number', 'shipment_order_number', 'shipment_cost', 'label_url', 'tracking_url']);
46
+        });
47
+
48
+        Schema::table('stores', function (Blueprint $table) {
49
+            $table->dropColumn(['pickup_address', 'parcel_weight', 'parcel_size']);
50
+        });
51
+
52
+        Schema::dropIfExists('easyparcel_accounts');
53
+    }
54
+};

+ 24
- 0
resources/js/components/back-button.tsx Просмотреть файл

1
+import { Link } from '@inertiajs/react';
2
+import type { InertiaLinkProps } from '@inertiajs/react';
3
+import { ArrowLeft } from 'lucide-react';
4
+import { Button } from '@/components/ui/button';
5
+
6
+/**
7
+ * The "← Back to …" button at the top of a page. Outlined, so it is easy to see.
8
+ */
9
+export function BackButton({
10
+    href,
11
+    children,
12
+}: {
13
+    href: InertiaLinkProps['href'];
14
+    children: React.ReactNode;
15
+}) {
16
+    return (
17
+        <Button variant="outline" size="sm" className="-ml-0.5" asChild>
18
+            <Link href={href} data-test="back-button">
19
+                <ArrowLeft />
20
+                {children}
21
+            </Link>
22
+        </Button>
23
+    );
24
+}

+ 510
- 0
resources/js/components/stores/courier-booking.tsx Просмотреть файл

1
+import { Form, Link, router, usePage } from '@inertiajs/react';
2
+import {
3
+    ExternalLink,
4
+    MapPin,
5
+    Printer,
6
+    RefreshCw,
7
+    Store as StoreIcon,
8
+    Truck,
9
+} from 'lucide-react';
10
+import { useState } from 'react';
11
+import OrderController from '@/actions/App/Http/Controllers/OrderController';
12
+import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
13
+import InputError from '@/components/input-error';
14
+import { Badge } from '@/components/ui/badge';
15
+import { Button } from '@/components/ui/button';
16
+import {
17
+    Card,
18
+    CardContent,
19
+    CardDescription,
20
+    CardHeader,
21
+    CardTitle,
22
+} from '@/components/ui/card';
23
+import { Input } from '@/components/ui/input';
24
+import { Label } from '@/components/ui/label';
25
+import { Spinner } from '@/components/ui/spinner';
26
+import { formatRinggit } from '@/lib/money';
27
+import { cn } from '@/lib/utils';
28
+import type { Order, StoreSummary } from '@/types';
29
+
30
+export type CourierQuote = {
31
+    service_id: string;
32
+    courier: string;
33
+    service: string;
34
+    logo: string | null;
35
+    /** In ringgit. */
36
+    price: number;
37
+    pickup: boolean;
38
+    dropoff: boolean;
39
+    delivery: string | null;
40
+    /** Something to know, such as "Pickup needs at least 3 parcels". */
41
+    note: string | null;
42
+};
43
+
44
+export type EasyParcelState = {
45
+    connected: boolean;
46
+    has_pickup_address: boolean;
47
+    parcel: { weight: number; length: number; width: number; height: number };
48
+    /** The first day a courier can collect, YYYY-MM-DD. */
49
+    collection_date: string;
50
+};
51
+
52
+type Parcel = {
53
+    weight: string;
54
+    length: string;
55
+    width: string;
56
+    height: string;
57
+};
58
+
59
+/**
60
+ * Book a courier through the merchant's EasyParcel account:
61
+ * type the parcel, see each courier's price, pick one, book, print the label.
62
+ */
63
+export function CourierBooking({
64
+    store,
65
+    order,
66
+    easyparcel,
67
+    quotes,
68
+}: {
69
+    store: StoreSummary;
70
+    order: Order;
71
+    easyparcel: EasyParcelState;
72
+    quotes: CourierQuote[] | { error: string } | undefined;
73
+}) {
74
+    if (order.shipment) {
75
+        return <BookedCourier store={store} order={order} />;
76
+    }
77
+
78
+    if (!easyparcel.connected || !easyparcel.has_pickup_address) {
79
+        return (
80
+            <Card data-test="courier-booking-setup">
81
+                <CardHeader>
82
+                    <CardTitle className="flex items-center gap-2">
83
+                        <Truck className="size-5" />
84
+                        Book a courier
85
+                    </CardTitle>
86
+                    <CardDescription>
87
+                        Compare courier prices and print the label here, through
88
+                        your own EasyParcel account.{' '}
89
+                        {!easyparcel.connected
90
+                            ? 'Connect EasyParcel and add your pickup address in Settings to start.'
91
+                            : 'Add your pickup address in Settings to start.'}
92
+                    </CardDescription>
93
+                </CardHeader>
94
+                <CardContent>
95
+                    <Button variant="outline" size="sm" asChild>
96
+                        <Link
97
+                            href={`${StoreSettingsController.edit.url(store.slug)}#easyparcel`}
98
+                        >
99
+                            Set up in Settings
100
+                        </Link>
101
+                    </Button>
102
+                </CardContent>
103
+            </Card>
104
+        );
105
+    }
106
+
107
+    return (
108
+        <QuoteAndBook
109
+            store={store}
110
+            order={order}
111
+            easyparcel={easyparcel}
112
+            quotes={quotes}
113
+        />
114
+    );
115
+}
116
+
117
+function QuoteAndBook({
118
+    store,
119
+    order,
120
+    easyparcel,
121
+    quotes,
122
+}: {
123
+    store: StoreSummary;
124
+    order: Order;
125
+    easyparcel: EasyParcelState;
126
+    quotes: CourierQuote[] | { error: string } | undefined;
127
+}) {
128
+    // A failed booking comes back as a fresh page, without the courier list, so its message is shown up here.
129
+    const bookingError = usePage().props.errors.booking as string | undefined;
130
+    const [parcel, setParcel] = useState<Parcel>({
131
+        weight: String(easyparcel.parcel.weight),
132
+        length: String(easyparcel.parcel.length),
133
+        width: String(easyparcel.parcel.width),
134
+        height: String(easyparcel.parcel.height),
135
+    });
136
+    const [loading, setLoading] = useState(false);
137
+    const [chosen, setChosen] = useState<string | null>(null);
138
+    // Prices are for the parcel as it was typed. Changing it asks for new prices.
139
+    const [pricedFor, setPricedFor] = useState<string | null>(null);
140
+    const typed = JSON.stringify(parcel);
141
+    const list = Array.isArray(quotes) ? quotes : null;
142
+    const fresh = list !== null && pricedFor === typed;
143
+    const picked = fresh
144
+        ? (list.find((quote) => quote.service_id === chosen) ?? null)
145
+        : null;
146
+
147
+    const seePrices = () => {
148
+        setLoading(true);
149
+        setChosen(null);
150
+        router.reload({
151
+            only: ['courier_quotes'],
152
+            data: parcel,
153
+            onSuccess: () => setPricedFor(typed),
154
+            onFinish: () => setLoading(false),
155
+        });
156
+    };
157
+
158
+    const field = (key: keyof Parcel, label: string, step: string) => (
159
+        <div className="grid gap-1.5">
160
+            <Label htmlFor={`parcel-${key}`} className="text-xs">
161
+                {label}
162
+            </Label>
163
+            <Input
164
+                id={`parcel-${key}`}
165
+                inputMode="decimal"
166
+                type="number"
167
+                min={key === 'weight' ? 0.01 : 1}
168
+                step={step}
169
+                value={parcel[key]}
170
+                onChange={(event) =>
171
+                    setParcel({ ...parcel, [key]: event.target.value })
172
+                }
173
+            />
174
+        </div>
175
+    );
176
+
177
+    return (
178
+        <Card data-test="courier-booking">
179
+            <CardHeader>
180
+                <CardTitle className="flex items-center gap-2">
181
+                    <Truck className="size-5" />
182
+                    Book a courier
183
+                </CardTitle>
184
+                <CardDescription>
185
+                    Through your EasyParcel account. The price is taken from
186
+                    your EasyParcel credit.
187
+                </CardDescription>
188
+            </CardHeader>
189
+            <CardContent className="space-y-5">
190
+                <div>
191
+                    <p className="mb-2 text-sm font-medium">The parcel</p>
192
+                    <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
193
+                        {field('weight', 'Weight (kg)', '0.01')}
194
+                        {field('length', 'Length (cm)', '1')}
195
+                        {field('width', 'Width (cm)', '1')}
196
+                        {field('height', 'Height (cm)', '1')}
197
+                    </div>
198
+                    <Button
199
+                        type="button"
200
+                        variant="outline"
201
+                        className="mt-3"
202
+                        onClick={seePrices}
203
+                        disabled={loading}
204
+                        data-test="see-courier-prices"
205
+                    >
206
+                        {loading && <Spinner />}
207
+                        {loading
208
+                            ? 'Asking couriers…'
209
+                            : fresh
210
+                              ? 'Refresh prices'
211
+                              : 'See courier prices'}
212
+                    </Button>
213
+                </div>
214
+
215
+                {bookingError && !fresh && (
216
+                    <p
217
+                        className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
218
+                        role="alert"
219
+                        data-test="booking-error"
220
+                    >
221
+                        Not booked. {bookingError}
222
+                    </p>
223
+                )}
224
+
225
+                {quotes && !Array.isArray(quotes) && pricedFor === typed && (
226
+                    <p
227
+                        className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"
228
+                        role="alert"
229
+                    >
230
+                        {quotes.error}
231
+                    </p>
232
+                )}
233
+
234
+                {fresh && list.length === 0 && (
235
+                    <p className="text-sm text-muted-foreground">
236
+                        No courier can take this parcel. Check its weight and
237
+                        size, or your pickup address.
238
+                    </p>
239
+                )}
240
+
241
+                {fresh && list.length > 0 && (
242
+                    <fieldset>
243
+                        <legend className="mb-2 text-sm font-medium">
244
+                            Choose a courier
245
+                        </legend>
246
+                        <div
247
+                            className="grid max-h-[26rem] gap-2 overflow-y-auto pr-1"
248
+                            data-test="courier-quotes"
249
+                        >
250
+                            {list.map((quote) => (
251
+                                <label
252
+                                    key={quote.service_id}
253
+                                    className={cn(
254
+                                        'flex cursor-pointer items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50',
255
+                                        chosen === quote.service_id &&
256
+                                            'border-primary bg-primary/5 ring-1 ring-primary',
257
+                                    )}
258
+                                >
259
+                                    <input
260
+                                        type="radio"
261
+                                        name="courier_choice"
262
+                                        className="sr-only"
263
+                                        checked={chosen === quote.service_id}
264
+                                        onChange={() =>
265
+                                            setChosen(quote.service_id)
266
+                                        }
267
+                                    />
268
+                                    {quote.logo ? (
269
+                                        <img
270
+                                            src={quote.logo}
271
+                                            alt=""
272
+                                            className="size-10 shrink-0 rounded bg-white object-contain p-0.5"
273
+                                        />
274
+                                    ) : (
275
+                                        <span className="flex size-10 shrink-0 items-center justify-center rounded bg-muted">
276
+                                            <Truck className="size-5 text-muted-foreground" />
277
+                                        </span>
278
+                                    )}
279
+                                    <span className="min-w-0 flex-1">
280
+                                        <span className="block truncate text-sm font-medium">
281
+                                            {quote.courier}
282
+                                        </span>
283
+                                        <span className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
284
+                                            {quote.pickup && (
285
+                                                <Badge
286
+                                                    variant="secondary"
287
+                                                    className="gap-1 font-normal"
288
+                                                >
289
+                                                    <MapPin className="size-3" />
290
+                                                    Picks up from you
291
+                                                </Badge>
292
+                                            )}
293
+                                            {quote.dropoff && (
294
+                                                <Badge
295
+                                                    variant="secondary"
296
+                                                    className="gap-1 font-normal"
297
+                                                >
298
+                                                    <StoreIcon className="size-3" />
299
+                                                    Drop off at a counter
300
+                                                </Badge>
301
+                                            )}
302
+                                            {quote.delivery && (
303
+                                                <span>{quote.delivery}</span>
304
+                                            )}
305
+                                            {quote.note && (
306
+                                                <span className="text-amber-700 dark:text-amber-400">
307
+                                                    {quote.note}
308
+                                                </span>
309
+                                            )}
310
+                                        </span>
311
+                                    </span>
312
+                                    <span className="text-sm font-semibold tabular-nums">
313
+                                        {formatRinggit(quote.price)}
314
+                                    </span>
315
+                                </label>
316
+                            ))}
317
+                        </div>
318
+                        <p className="mt-2 text-xs text-muted-foreground">
319
+                            The shopper paid{' '}
320
+                            {order.shipping_total === 0
321
+                                ? 'no shipping (free)'
322
+                                : `${formatRinggit(order.shipping_total)} for shipping`}
323
+                            .
324
+                        </p>
325
+                    </fieldset>
326
+                )}
327
+
328
+                {picked && (
329
+                    <Form
330
+                        {...OrderController.book.form({
331
+                            slug: store.slug,
332
+                            order: order.id,
333
+                        })}
334
+                        options={{ preserveScroll: true }}
335
+                        className="space-y-4 border-t pt-4"
336
+                    >
337
+                        {({ processing, errors }) => (
338
+                            <>
339
+                                <input
340
+                                    type="hidden"
341
+                                    name="service_id"
342
+                                    value={picked.service_id}
343
+                                />
344
+                                <input
345
+                                    type="hidden"
346
+                                    name="courier"
347
+                                    value={picked.courier}
348
+                                />
349
+                                {Object.entries(parcel).map(([key, value]) => (
350
+                                    <input
351
+                                        key={key}
352
+                                        type="hidden"
353
+                                        name={key}
354
+                                        value={value}
355
+                                    />
356
+                                ))}
357
+                                <div className="grid gap-1.5 sm:max-w-56">
358
+                                    <Label htmlFor="collection_date">
359
+                                        {picked.pickup
360
+                                            ? 'Collection day'
361
+                                            : 'Day you drop it off'}
362
+                                    </Label>
363
+                                    <Input
364
+                                        id="collection_date"
365
+                                        name="collection_date"
366
+                                        type="date"
367
+                                        min={easyparcel.collection_date}
368
+                                        defaultValue={
369
+                                            easyparcel.collection_date
370
+                                        }
371
+                                        required
372
+                                    />
373
+                                    <InputError
374
+                                        message={errors.collection_date}
375
+                                    />
376
+                                </div>
377
+                                <InputError
378
+                                    message={
379
+                                        errors.booking ??
380
+                                        errors.service_id ??
381
+                                        errors.weight ??
382
+                                        errors.length ??
383
+                                        errors.width ??
384
+                                        errors.height
385
+                                    }
386
+                                />
387
+                                <Button
388
+                                    disabled={processing}
389
+                                    data-test="book-courier-button"
390
+                                >
391
+                                    {processing && <Spinner />}
392
+                                    Book {picked.courier} for{' '}
393
+                                    {formatRinggit(picked.price)}
394
+                                </Button>
395
+                            </>
396
+                        )}
397
+                    </Form>
398
+                )}
399
+            </CardContent>
400
+        </Card>
401
+    );
402
+}
403
+
404
+function BookedCourier({
405
+    store,
406
+    order,
407
+}: {
408
+    store: StoreSummary;
409
+    order: Order;
410
+}) {
411
+    const shipment = order.shipment!;
412
+
413
+    return (
414
+        <Card data-test="courier-booked">
415
+            <CardHeader>
416
+                <CardTitle className="flex items-center gap-2">
417
+                    <Truck className="size-5" />
418
+                    Courier booked
419
+                </CardTitle>
420
+                <CardDescription>
421
+                    {order.shipping_courier} · EasyParcel {shipment.number}
422
+                    {shipment.cost !== null &&
423
+                        ` · Paid ${formatRinggit(shipment.cost)}`}
424
+                </CardDescription>
425
+            </CardHeader>
426
+            <CardContent className="space-y-4 text-sm">
427
+                {order.tracking_number ? (
428
+                    <p>
429
+                        Tracking number{' '}
430
+                        <span className="font-medium tabular-nums">
431
+                            {order.tracking_number}
432
+                        </span>
433
+                        {order.shipped_at &&
434
+                            '. The customer was emailed this number.'}
435
+                    </p>
436
+                ) : (
437
+                    <p className="text-muted-foreground">
438
+                        The courier is preparing the label. It usually takes a
439
+                        minute or two.
440
+                    </p>
441
+                )}
442
+
443
+                <div className="flex flex-wrap gap-2">
444
+                    {shipment.label_url && (
445
+                        <Button asChild>
446
+                            <a
447
+                                href={shipment.label_url}
448
+                                target="_blank"
449
+                                rel="noreferrer"
450
+                                data-test="print-label"
451
+                            >
452
+                                <Printer />
453
+                                Print label
454
+                            </a>
455
+                        </Button>
456
+                    )}
457
+                    {shipment.tracking_url && (
458
+                        <Button variant="outline" asChild>
459
+                            <a
460
+                                href={shipment.tracking_url}
461
+                                target="_blank"
462
+                                rel="noreferrer"
463
+                            >
464
+                                <ExternalLink />
465
+                                Track parcel
466
+                            </a>
467
+                        </Button>
468
+                    )}
469
+                    {(!shipment.label_url || !order.tracking_number) && (
470
+                        <Form
471
+                            {...OrderController.refreshLabel.form({
472
+                                slug: store.slug,
473
+                                order: order.id,
474
+                            })}
475
+                            options={{ preserveScroll: true }}
476
+                        >
477
+                            {({ processing, errors }) => (
478
+                                <>
479
+                                    <Button
480
+                                        variant="outline"
481
+                                        disabled={processing}
482
+                                        data-test="refresh-label"
483
+                                    >
484
+                                        <RefreshCw
485
+                                            className={cn(
486
+                                                processing && 'animate-spin',
487
+                                            )}
488
+                                        />
489
+                                        Check for the label
490
+                                    </Button>
491
+                                    <InputError
492
+                                        className="mt-2"
493
+                                        message={errors.booking}
494
+                                    />
495
+                                </>
496
+                            )}
497
+                        </Form>
498
+                    )}
499
+                </div>
500
+
501
+                {shipment.label_url && (
502
+                    <p className="text-xs text-muted-foreground">
503
+                        Print the label, stick it on the parcel, and hand it to
504
+                        the courier (or drop it off at a counter).
505
+                    </p>
506
+                )}
507
+            </CardContent>
508
+        </Card>
509
+    );
510
+}

+ 252
- 0
resources/js/components/stores/easyparcel-setup.tsx Просмотреть файл

1
+import { Deferred, router } from '@inertiajs/react';
2
+import { Check, ExternalLink, Link2, Unlink } from 'lucide-react';
3
+import { useState } from 'react';
4
+import EasyParcelController from '@/actions/App/Http/Controllers/EasyParcelController';
5
+import { Badge } from '@/components/ui/badge';
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 { Skeleton } from '@/components/ui/skeleton';
15
+import { Spinner } from '@/components/ui/spinner';
16
+import { formatRinggit } from '@/lib/money';
17
+import { cn } from '@/lib/utils';
18
+import type { StoreSummary } from '@/types';
19
+
20
+export type EasyParcelSettings = {
21
+    /** False until the app's own EasyParcel keys are set. */
22
+    available: boolean;
23
+    connected: boolean;
24
+    account_name: string | null;
25
+    redirect_uri: string;
26
+};
27
+
28
+const SIGN_UP_URL = 'https://easyparcel.com/my/';
29
+
30
+/**
31
+ * A guided setup for booking couriers through the merchant's own EasyParcel account.
32
+ * It sits inside the Settings form, so its buttons never submit that form.
33
+ */
34
+export function EasyParcelSetup({
35
+    store,
36
+    easyparcel,
37
+    balance,
38
+    hasPickup,
39
+}: {
40
+    store: StoreSummary;
41
+    easyparcel: EasyParcelSettings;
42
+    balance?: { amount: number | null; error: string | null } | null;
43
+    hasPickup: boolean;
44
+}) {
45
+    const [busy, setBusy] = useState(false);
46
+
47
+    const connect = () => {
48
+        setBusy(true);
49
+        // EasyParcel's sign-in page opens in this tab, then brings the merchant back here.
50
+        router.post(
51
+            EasyParcelController.connect.url(store.slug),
52
+            {},
53
+            { onFinish: () => setBusy(false) },
54
+        );
55
+    };
56
+
57
+    const disconnect = () => {
58
+        if (
59
+            !window.confirm(
60
+                'Disconnect EasyParcel? You can connect again at any time. Parcels already booked are not affected.',
61
+            )
62
+        ) {
63
+            return;
64
+        }
65
+
66
+        router.delete(EasyParcelController.disconnect.url(store.slug), {
67
+            preserveScroll: true,
68
+        });
69
+    };
70
+
71
+    return (
72
+        <Card id="easyparcel" data-test="easyparcel-setup">
73
+            <CardHeader>
74
+                <CardTitle className="flex flex-wrap items-center gap-2">
75
+                    Couriers with EasyParcel
76
+                    {easyparcel.connected && (
77
+                        <Badge className="bg-emerald-600 text-white hover:bg-emerald-600">
78
+                            <Check className="size-3" />
79
+                            Connected
80
+                        </Badge>
81
+                    )}
82
+                </CardTitle>
83
+                <CardDescription>
84
+                    Compare J&amp;T, Pos Laju, Ninja Van, DHL and more on each
85
+                    order, book the cheapest and print the label. Parcels are
86
+                    paid from your own EasyParcel credit.
87
+                </CardDescription>
88
+            </CardHeader>
89
+            <CardContent>
90
+                {easyparcel.connected ? (
91
+                    <div className="space-y-4">
92
+                        <div className="rounded-lg border p-4 text-sm">
93
+                            <p>
94
+                                Connected to{' '}
95
+                                <span className="font-medium">
96
+                                    {easyparcel.account_name ??
97
+                                        'your EasyParcel account'}
98
+                                </span>
99
+                            </p>
100
+                            <div className="mt-1 text-muted-foreground">
101
+                                <Deferred
102
+                                    data="easyparcelBalance"
103
+                                    fallback={<Skeleton className="h-4 w-40" />}
104
+                                >
105
+                                    <BalanceLine balance={balance} />
106
+                                </Deferred>
107
+                            </div>
108
+                        </div>
109
+                        {!hasPickup && (
110
+                            <p className="text-sm text-amber-700 dark:text-amber-400">
111
+                                One more step: add your pickup address below,
112
+                                then save.
113
+                            </p>
114
+                        )}
115
+                        <div className="flex flex-wrap gap-2">
116
+                            <Button type="button" variant="outline" asChild>
117
+                                <a
118
+                                    href={SIGN_UP_URL}
119
+                                    target="_blank"
120
+                                    rel="noreferrer"
121
+                                >
122
+                                    <ExternalLink />
123
+                                    Top up on EasyParcel
124
+                                </a>
125
+                            </Button>
126
+                            <Button
127
+                                type="button"
128
+                                variant="ghost"
129
+                                onClick={disconnect}
130
+                                data-test="easyparcel-disconnect"
131
+                            >
132
+                                <Unlink />
133
+                                Disconnect
134
+                            </Button>
135
+                        </div>
136
+                    </div>
137
+                ) : (
138
+                    <ol className="space-y-4">
139
+                        <Step
140
+                            number={1}
141
+                            title="Create a free EasyParcel account"
142
+                        >
143
+                            Sign up on EasyParcel and finish their identity
144
+                            check. Already have an account? Skip this.
145
+                            <a
146
+                                href={SIGN_UP_URL}
147
+                                target="_blank"
148
+                                rel="noreferrer"
149
+                                className="mt-1 flex w-fit items-center gap-1 font-medium text-foreground underline underline-offset-2"
150
+                            >
151
+                                Open EasyParcel
152
+                                <ExternalLink className="size-3.5" />
153
+                            </a>
154
+                        </Step>
155
+                        <Step number={2} title="Top up some credit">
156
+                            In EasyParcel, top up a little credit (RM 20 is
157
+                            enough to start). Each courier you book is paid from
158
+                            it.
159
+                        </Step>
160
+                        <Step
161
+                            number={3}
162
+                            title="Add your pickup address"
163
+                            done={hasPickup}
164
+                        >
165
+                            Fill it in below and save, so couriers know where to
166
+                            collect.
167
+                        </Step>
168
+                        <Step number={4} title="Connect">
169
+                            Sign in to EasyParcel and click Allow. You come
170
+                            straight back here.
171
+                            <div className="mt-2">
172
+                                {easyparcel.available ? (
173
+                                    <Button
174
+                                        type="button"
175
+                                        onClick={connect}
176
+                                        disabled={busy}
177
+                                        data-test="easyparcel-connect"
178
+                                    >
179
+                                        {busy ? <Spinner /> : <Link2 />}
180
+                                        Connect EasyParcel
181
+                                    </Button>
182
+                                ) : (
183
+                                    <p
184
+                                        className="rounded-md bg-muted p-3 text-xs"
185
+                                        data-test="easyparcel-unavailable"
186
+                                    >
187
+                                        EasyParcel is not switched on for this
188
+                                        app yet. The app owner adds
189
+                                        EASYPARCEL_CLIENT_ID and
190
+                                        EASYPARCEL_CLIENT_SECRET to .env.local,
191
+                                        with {easyparcel.redirect_uri} as the
192
+                                        redirect address.
193
+                                    </p>
194
+                                )}
195
+                            </div>
196
+                        </Step>
197
+                    </ol>
198
+                )}
199
+            </CardContent>
200
+        </Card>
201
+    );
202
+}
203
+
204
+function BalanceLine({
205
+    balance,
206
+}: {
207
+    balance?: { amount: number | null; error: string | null } | null;
208
+}) {
209
+    if (balance?.error) {
210
+        return <span className="text-destructive">{balance.error}</span>;
211
+    }
212
+
213
+    return (
214
+        <span data-test="easyparcel-balance">
215
+            Credit:{' '}
216
+            {balance?.amount != null ? formatRinggit(balance.amount) : '—'}
217
+        </span>
218
+    );
219
+}
220
+
221
+function Step({
222
+    number,
223
+    title,
224
+    done = false,
225
+    children,
226
+}: {
227
+    number: number;
228
+    title: string;
229
+    done?: boolean;
230
+    children: React.ReactNode;
231
+}) {
232
+    return (
233
+        <li className="flex gap-3">
234
+            <span
235
+                className={cn(
236
+                    'flex size-7 shrink-0 items-center justify-center rounded-full border text-sm font-medium',
237
+                    done && 'border-emerald-600 bg-emerald-600 text-white',
238
+                )}
239
+                aria-hidden="true"
240
+            >
241
+                {done ? <Check className="size-4" /> : number}
242
+            </span>
243
+            <div className="text-sm text-muted-foreground">
244
+                <p className="font-medium text-foreground">
245
+                    {title}
246
+                    {done && <span className="sr-only"> (done)</span>}
247
+                </p>
248
+                {children}
249
+            </div>
250
+        </li>
251
+    );
252
+}

+ 12
- 4
resources/js/pages/stores/collections/form.tsx Просмотреть файл

2
 import { ImageOff } from 'lucide-react';
2
 import { ImageOff } from 'lucide-react';
3
 import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
3
 import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
5
+import { BackButton } from '@/components/back-button';
5
 import Heading from '@/components/heading';
6
 import Heading from '@/components/heading';
6
 import InputError from '@/components/input-error';
7
 import InputError from '@/components/input-error';
7
 import { Button } from '@/components/ui/button';
8
 import { Button } from '@/components/ui/button';
53
             />
54
             />
54
 
55
 
55
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
56
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
56
-                <Heading
57
-                    title={collection ? 'Edit collection' : 'New collection'}
58
-                    description="A group of products shoppers can browse, such as Sun care or Gifts under RM 50."
59
-                />
57
+                <div className="space-y-4">
58
+                    <BackButton href={ProductController.index.url(store.slug)}>
59
+                        Back to products
60
+                    </BackButton>
61
+                    <Heading
62
+                        title={
63
+                            collection ? 'Edit collection' : 'New collection'
64
+                        }
65
+                        description="A group of products shoppers can browse, such as Sun care or Gifts under RM 50."
66
+                    />
67
+                </div>
60
 
68
 
61
                 <Form {...action} className="space-y-6">
69
                 <Form {...action} className="space-y-6">
62
                     {({ processing, errors }) => (
70
                     {({ processing, errors }) => (

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

2
 import { useState } from 'react';
2
 import { useState } from 'react';
3
 import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
3
 import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
4
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
5
+import { BackButton } from '@/components/back-button';
5
 import Heading from '@/components/heading';
6
 import Heading from '@/components/heading';
6
 import InputError from '@/components/input-error';
7
 import InputError from '@/components/input-error';
7
 import { Button } from '@/components/ui/button';
8
 import { Button } from '@/components/ui/button';
51
             />
52
             />
52
 
53
 
53
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
54
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
54
-                <Heading
55
-                    title={
56
-                        offer
57
-                            ? 'Edit automatic discount'
58
-                            : 'New automatic discount'
59
-                    }
60
-                    description="No code needed. It applies by itself when a cart qualifies."
61
-                />
55
+                <div className="space-y-4">
56
+                    <BackButton
57
+                        href={DiscountCodeController.index.url(store.slug)}
58
+                    >
59
+                        Back to discounts
60
+                    </BackButton>
61
+                    <Heading
62
+                        title={
63
+                            offer
64
+                                ? 'Edit automatic discount'
65
+                                : 'New automatic discount'
66
+                        }
67
+                        description="No code needed. It applies by itself when a cart qualifies."
68
+                    />
69
+                </div>
62
 
70
 
63
                 <Form {...action} className="space-y-6">
71
                 <Form {...action} className="space-y-6">
64
                     {({ processing, errors }) => (
72
                     {({ processing, errors }) => (

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

1
 import { Form, Head, Link } from '@inertiajs/react';
1
 import { Form, Head, Link } from '@inertiajs/react';
2
 import { useState } from 'react';
2
 import { useState } from 'react';
3
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
3
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4
+import { BackButton } from '@/components/back-button';
4
 import Heading from '@/components/heading';
5
 import Heading from '@/components/heading';
5
 import InputError from '@/components/input-error';
6
 import InputError from '@/components/input-error';
6
 import { Button } from '@/components/ui/button';
7
 import { Button } from '@/components/ui/button';
45
             />
46
             />
46
 
47
 
47
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
48
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
48
-                <Heading
49
-                    title={code ? 'Edit discount code' : 'New discount code'}
50
-                    description={`For ${store.name}. Shoppers type the code in their cart.`}
51
-                />
49
+                <div className="space-y-4">
50
+                    <BackButton
51
+                        href={DiscountCodeController.index.url(store.slug)}
52
+                    >
53
+                        Back to discounts
54
+                    </BackButton>
55
+                    <Heading
56
+                        title={
57
+                            code ? 'Edit discount code' : 'New discount code'
58
+                        }
59
+                        description={`For ${store.name}. Shoppers type the code in their cart.`}
60
+                    />
61
+                </div>
52
 
62
 
53
                 <Form {...action} className="space-y-6">
63
                 <Form {...action} className="space-y-6">
54
                     {({ processing, errors }) => (
64
                     {({ processing, errors }) => (

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

3
 import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
3
 import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
4
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
6
+import { BackButton } from '@/components/back-button';
6
 import StoreNav from '@/components/stores/store-nav';
7
 import StoreNav from '@/components/stores/store-nav';
7
 import { Badge } from '@/components/ui/badge';
8
 import { Badge } from '@/components/ui/badge';
8
 import { Button } from '@/components/ui/button';
9
 import { Button } from '@/components/ui/button';
59
             <Head title={`Discounts - ${store.name}`} />
60
             <Head title={`Discounts - ${store.name}`} />
60
 
61
 
61
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
62
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
62
-                <div>
63
+                <div className="space-y-4">
64
+                    <BackButton href={StoreController.show.url(store.slug)}>
65
+                        Back to store
66
+                    </BackButton>
63
                     <h1 className="text-xl font-semibold">{store.name}</h1>
67
                     <h1 className="text-xl font-semibold">{store.name}</h1>
64
-                    <p className="text-sm text-muted-foreground">
65
-                        <Link
66
-                            href={StoreController.show.url(store.slug)}
67
-                            className="hover:underline"
68
-                        >
69
-                            Back to store
70
-                        </Link>
71
-                    </p>
72
                 </div>
68
                 </div>
73
 
69
 
74
                 <StoreNav slug={store.slug} current="discounts" />
70
                 <StoreNav slug={store.slug} current="discounts" />

+ 5
- 9
resources/js/pages/stores/orders/index.tsx Просмотреть файл

2
 import { ReceiptText } from 'lucide-react';
2
 import { ReceiptText } from 'lucide-react';
3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
4
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
4
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
+import { BackButton } from '@/components/back-button';
5
 import StoreNav from '@/components/stores/store-nav';
6
 import StoreNav from '@/components/stores/store-nav';
6
 import { Badge } from '@/components/ui/badge';
7
 import { Badge } from '@/components/ui/badge';
7
 import { formatDateTime, formatRinggit } from '@/lib/money';
8
 import { formatDateTime, formatRinggit } from '@/lib/money';
23
             <Head title={`Orders - ${store.name}`} />
24
             <Head title={`Orders - ${store.name}`} />
24
 
25
 
25
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
26
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
26
-                <div>
27
+                <div className="space-y-4">
28
+                    <BackButton href={StoreController.show.url(store.slug)}>
29
+                        Back to store
30
+                    </BackButton>
27
                     <h1 className="text-xl font-semibold">{store.name}</h1>
31
                     <h1 className="text-xl font-semibold">{store.name}</h1>
28
-                    <p className="text-sm text-muted-foreground">
29
-                        <Link
30
-                            href={StoreController.show.url(store.slug)}
31
-                            className="hover:underline"
32
-                        >
33
-                            Back to store
34
-                        </Link>
35
-                    </p>
36
                 </div>
32
                 </div>
37
 
33
 
38
                 <StoreNav slug={store.slug} current="orders" />
34
                 <StoreNav slug={store.slug} current="orders" />

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

1
-import { Form, Head, Link } from '@inertiajs/react';
1
+import { Form, Head } from '@inertiajs/react';
2
 import { MessageCircle, Truck } from 'lucide-react';
2
 import { MessageCircle, Truck } from 'lucide-react';
3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
3
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
4
+import { BackButton } from '@/components/back-button';
4
 import InputError from '@/components/input-error';
5
 import InputError from '@/components/input-error';
6
+import { CourierBooking } from '@/components/stores/courier-booking';
7
+import type {
8
+    CourierQuote,
9
+    EasyParcelState,
10
+} from '@/components/stores/courier-booking';
5
 import { Badge } from '@/components/ui/badge';
11
 import { Badge } from '@/components/ui/badge';
6
 import { Button } from '@/components/ui/button';
12
 import { Button } from '@/components/ui/button';
7
 import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
13
 import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
19
     order,
25
     order,
20
     couriers,
26
     couriers,
21
     customer_whatsapp_url,
27
     customer_whatsapp_url,
28
+    easyparcel,
29
+    courier_quotes,
22
 }: {
30
 }: {
23
     store: StoreSummary;
31
     store: StoreSummary;
24
     order: Order;
32
     order: Order;
25
     couriers: string[];
33
     couriers: string[];
26
     customer_whatsapp_url: string | null;
34
     customer_whatsapp_url: string | null;
35
+    easyparcel: EasyParcelState;
36
+    /** Only after the merchant asks for courier prices. */
37
+    courier_quotes?: CourierQuote[] | { error: string };
27
 }) {
38
 }) {
28
     const paid = order.status === 'paid';
39
     const paid = order.status === 'paid';
29
     const shipped = order.shipped_at !== null;
40
     const shipped = order.shipped_at !== null;
36
 
47
 
37
             <div className="mx-auto w-full max-w-3xl space-y-6 p-4">
48
             <div className="mx-auto w-full max-w-3xl space-y-6 p-4">
38
                 <div>
49
                 <div>
39
-                    <p className="text-sm text-muted-foreground">
40
-                        <Link
41
-                            href={OrderController.index.url(store.slug)}
42
-                            className="hover:underline"
43
-                        >
44
-                            Back to orders
45
-                        </Link>
46
-                    </p>
47
-                    <div className="mt-1 flex flex-wrap items-center gap-3">
50
+                    <BackButton href={OrderController.index.url(store.slug)}>
51
+                        Back to orders
52
+                    </BackButton>
53
+                    <div className="mt-4 flex flex-wrap items-center gap-3">
48
                         <h1 className="text-xl font-semibold">
54
                         <h1 className="text-xl font-semibold">
49
                             Order #{order.number}
55
                             Order #{order.number}
50
                         </h1>
56
                         </h1>
188
                     </Card>
194
                     </Card>
189
                 </div>
195
                 </div>
190
 
196
 
191
-                {paid && (
197
+                {paid && (order.shipment !== null || !shipped) && (
198
+                    <CourierBooking
199
+                        store={store}
200
+                        order={order}
201
+                        easyparcel={easyparcel}
202
+                        quotes={courier_quotes}
203
+                    />
204
+                )}
205
+
206
+                {/* Couriers booked here are shipped by EasyParcel; the form is for sending any other way. */}
207
+                {paid && order.shipment === null && (
192
                     <Card data-test="ship-order-card">
208
                     <Card data-test="ship-order-card">
193
                         <CardHeader>
209
                         <CardHeader>
194
                             <CardTitle className="flex items-center gap-2">
210
                             <CardTitle className="flex items-center gap-2">
195
                                 <Truck className="size-5" />
211
                                 <Truck className="size-5" />
196
-                                {shipped ? 'Shipped' : 'Ship this order'}
212
+                                {shipped
213
+                                    ? 'Shipped'
214
+                                    : easyparcel.connected
215
+                                      ? 'Or mark as shipped yourself'
216
+                                      : 'Ship this order'}
197
                             </CardTitle>
217
                             </CardTitle>
198
                         </CardHeader>
218
                         </CardHeader>
199
                         <CardContent>
219
                         <CardContent>

+ 11
- 4
resources/js/pages/stores/products/create.tsx Просмотреть файл

1
 import { Head } from '@inertiajs/react';
1
 import { Head } from '@inertiajs/react';
2
+import ProductController from '@/actions/App/Http/Controllers/ProductController';
3
+import { BackButton } from '@/components/back-button';
2
 import Heading from '@/components/heading';
4
 import Heading from '@/components/heading';
3
 import ProductForm from '@/components/stores/product-form';
5
 import ProductForm from '@/components/stores/product-form';
4
 import { dashboard } from '@/routes';
6
 import { dashboard } from '@/routes';
20
             <Head title={`Add product - ${store.name}`} />
22
             <Head title={`Add product - ${store.name}`} />
21
 
23
 
22
             <div className="mx-auto w-full max-w-2xl space-y-6 p-4">
24
             <div className="mx-auto w-full max-w-2xl space-y-6 p-4">
23
-                <Heading
24
-                    title="Add a product"
25
-                    description={`A new product for ${store.name}.`}
26
-                />
25
+                <div className="space-y-4">
26
+                    <BackButton href={ProductController.index.url(store.slug)}>
27
+                        Back to products
28
+                    </BackButton>
29
+                    <Heading
30
+                        title="Add a product"
31
+                        description={`A new product for ${store.name}.`}
32
+                    />
33
+                </div>
27
 
34
 
28
                 <ProductForm
35
                 <ProductForm
29
                     store={store}
36
                     store={store}

+ 10
- 4
resources/js/pages/stores/products/edit.tsx Просмотреть файл

1
 import { Form, Head } from '@inertiajs/react';
1
 import { Form, Head } from '@inertiajs/react';
2
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
2
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
3
+import { BackButton } from '@/components/back-button';
3
 import Heading from '@/components/heading';
4
 import Heading from '@/components/heading';
4
 import ProductForm from '@/components/stores/product-form';
5
 import ProductForm from '@/components/stores/product-form';
5
 import { Button } from '@/components/ui/button';
6
 import { Button } from '@/components/ui/button';
39
             <Head title={`${product.name} - ${store.name}`} />
40
             <Head title={`${product.name} - ${store.name}`} />
40
 
41
 
41
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
42
             <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
42
-                <Heading
43
-                    title="Edit product"
44
-                    description={`${product.name}, in ${store.name}.`}
45
-                />
43
+                <div className="space-y-4">
44
+                    <BackButton href={ProductController.index.url(store.slug)}>
45
+                        Back to products
46
+                    </BackButton>
47
+                    <Heading
48
+                        title="Edit product"
49
+                        description={`${product.name}, in ${store.name}.`}
50
+                    />
51
+                </div>
46
 
52
 
47
                 <ProductForm
53
                 <ProductForm
48
                     store={store}
54
                     store={store}

+ 5
- 9
resources/js/pages/stores/products/index.tsx Просмотреть файл

3
 import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
3
 import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
6
+import { BackButton } from '@/components/back-button';
6
 import StoreNav from '@/components/stores/store-nav';
7
 import StoreNav from '@/components/stores/store-nav';
7
 import { Badge } from '@/components/ui/badge';
8
 import { Badge } from '@/components/ui/badge';
8
 import { Button } from '@/components/ui/button';
9
 import { Button } from '@/components/ui/button';
30
             <Head title={`Products - ${store.name}`} />
31
             <Head title={`Products - ${store.name}`} />
31
 
32
 
32
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
33
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
33
-                <div>
34
+                <div className="space-y-4">
35
+                    <BackButton href={StoreController.show.url(store.slug)}>
36
+                        Back to store
37
+                    </BackButton>
34
                     <h1 className="text-xl font-semibold">{store.name}</h1>
38
                     <h1 className="text-xl font-semibold">{store.name}</h1>
35
-                    <p className="text-sm text-muted-foreground">
36
-                        <Link
37
-                            href={StoreController.show.url(store.slug)}
38
-                            className="hover:underline"
39
-                        >
40
-                            Back to store
41
-                        </Link>
42
-                    </p>
43
                 </div>
39
                 </div>
44
 
40
 
45
                 <StoreNav slug={store.slug} current="products" />
41
                 <StoreNav slug={store.slug} current="products" />

+ 204
- 10
resources/js/pages/stores/settings.tsx Просмотреть файл

1
-import { Form, Head, Link } from '@inertiajs/react';
1
+import { Form, Head } from '@inertiajs/react';
2
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
2
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
3
+import { BackButton } from '@/components/back-button';
3
 import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
4
 import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
4
 import InputError from '@/components/input-error';
5
 import InputError from '@/components/input-error';
6
+import type { EasyParcelSettings } from '@/components/stores/easyparcel-setup';
7
+import { EasyParcelSetup } from '@/components/stores/easyparcel-setup';
5
 import StoreNav from '@/components/stores/store-nav';
8
 import StoreNav from '@/components/stores/store-nav';
6
 import { Button } from '@/components/ui/button';
9
 import { Button } from '@/components/ui/button';
7
 import { Checkbox } from '@/components/ui/checkbox';
10
 import { Checkbox } from '@/components/ui/checkbox';
25
     announcement_enabled: boolean;
28
     announcement_enabled: boolean;
26
     /** One message per line. */
29
     /** One message per line. */
27
     announcement_messages: string;
30
     announcement_messages: string;
31
+    pickup: {
32
+        name: string;
33
+        phone: string;
34
+        line1: string;
35
+        line2: string;
36
+        city: string;
37
+        postcode: string;
38
+        state: string;
39
+    };
40
+    parcel_weight: string;
41
+    parcel_length: string;
42
+    parcel_width: string;
43
+    parcel_height: string;
28
 };
44
 };
29
 
45
 
30
 export default function StoreSettings({
46
 export default function StoreSettings({
31
     store,
47
     store,
32
     settings,
48
     settings,
33
     automaticAnnouncements,
49
     automaticAnnouncements,
50
+    states,
51
+    easyparcel,
52
+    easyparcelBalance,
34
 }: {
53
 }: {
35
     store: StoreSummary;
54
     store: StoreSummary;
36
     settings: Settings;
55
     settings: Settings;
37
     automaticAnnouncements: string[];
56
     automaticAnnouncements: string[];
57
+    states: string[];
58
+    easyparcel: EasyParcelSettings;
59
+    /** Loaded after the page shows. Null when EasyParcel is not connected. */
60
+    easyparcelBalance?: { amount: number | null; error: string | null } | null;
38
 }) {
61
 }) {
39
     return (
62
     return (
40
         <>
63
         <>
41
             <Head title={`Settings - ${store.name}`} />
64
             <Head title={`Settings - ${store.name}`} />
42
 
65
 
43
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
66
             <div className="mx-auto w-full max-w-6xl space-y-6 p-4">
44
-                <div>
67
+                <div className="space-y-4">
68
+                    <BackButton href={StoreController.show.url(store.slug)}>
69
+                        Back to store
70
+                    </BackButton>
45
                     <h1 className="text-xl font-semibold">{store.name}</h1>
71
                     <h1 className="text-xl font-semibold">{store.name}</h1>
46
-                    <p className="text-sm text-muted-foreground">
47
-                        <Link
48
-                            href={StoreController.show.url(store.slug)}
49
-                            className="hover:underline"
50
-                        >
51
-                            Back to store
52
-                        </Link>
53
-                    </p>
54
                 </div>
72
                 </div>
55
 
73
 
56
                 <StoreNav slug={store.slug} current="settings" />
74
                 <StoreNav slug={store.slug} current="settings" />
169
                                 </CardContent>
187
                                 </CardContent>
170
                             </Card>
188
                             </Card>
171
 
189
 
190
+                            <EasyParcelSetup
191
+                                store={store}
192
+                                easyparcel={easyparcel}
193
+                                balance={easyparcelBalance}
194
+                                hasPickup={settings.pickup.line1 !== ''}
195
+                            />
196
+
197
+                            <Card id="pickup">
198
+                                <CardHeader>
199
+                                    <CardTitle>Pickup address</CardTitle>
200
+                                    <CardDescription>
201
+                                        Where couriers collect your parcels,
202
+                                        printed on every label as the sender.
203
+                                    </CardDescription>
204
+                                </CardHeader>
205
+                                <CardContent className="space-y-5">
206
+                                    <div className="grid gap-5 sm:grid-cols-2">
207
+                                        <TextField
208
+                                            name="pickup_name"
209
+                                            label="Sender name"
210
+                                            value={settings.pickup.name}
211
+                                            placeholder={store.name}
212
+                                            error={errors.pickup_name}
213
+                                            maxLength={60}
214
+                                        />
215
+                                        <TextField
216
+                                            name="pickup_phone"
217
+                                            label="Phone for the courier"
218
+                                            value={settings.pickup.phone}
219
+                                            placeholder="012-345 6789"
220
+                                            error={errors.pickup_phone}
221
+                                            maxLength={30}
222
+                                            type="tel"
223
+                                        />
224
+                                    </div>
225
+                                    <TextField
226
+                                        name="pickup_line1"
227
+                                        label="Address"
228
+                                        value={settings.pickup.line1}
229
+                                        placeholder="No. 12, Jalan Mawar 3"
230
+                                        error={errors.pickup_line1}
231
+                                        maxLength={100}
232
+                                    />
233
+                                    <TextField
234
+                                        name="pickup_line2"
235
+                                        label="Address line 2 (optional)"
236
+                                        value={settings.pickup.line2}
237
+                                        placeholder="Taman Melati"
238
+                                        error={errors.pickup_line2}
239
+                                        maxLength={100}
240
+                                    />
241
+                                    <div className="grid gap-5 sm:grid-cols-3">
242
+                                        <TextField
243
+                                            name="pickup_postcode"
244
+                                            label="Postcode"
245
+                                            value={settings.pickup.postcode}
246
+                                            placeholder="53100"
247
+                                            error={errors.pickup_postcode}
248
+                                            maxLength={5}
249
+                                            inputMode="numeric"
250
+                                        />
251
+                                        <TextField
252
+                                            name="pickup_city"
253
+                                            label="Town or city"
254
+                                            value={settings.pickup.city}
255
+                                            placeholder="Kuala Lumpur"
256
+                                            error={errors.pickup_city}
257
+                                            maxLength={60}
258
+                                        />
259
+                                        <div className="grid gap-2">
260
+                                            <Label htmlFor="pickup_state">
261
+                                                State
262
+                                            </Label>
263
+                                            <select
264
+                                                id="pickup_state"
265
+                                                name="pickup_state"
266
+                                                defaultValue={
267
+                                                    settings.pickup.state
268
+                                                }
269
+                                                className="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"
270
+                                            >
271
+                                                <option value="">Choose</option>
272
+                                                {states.map((state) => (
273
+                                                    <option
274
+                                                        key={state}
275
+                                                        value={state}
276
+                                                    >
277
+                                                        {state}
278
+                                                    </option>
279
+                                                ))}
280
+                                            </select>
281
+                                            <InputError
282
+                                                message={errors.pickup_state}
283
+                                            />
284
+                                        </div>
285
+                                    </div>
286
+
287
+                                    <div className="space-y-2 border-t pt-5">
288
+                                        <p className="text-sm font-medium">
289
+                                            Your usual parcel
290
+                                        </p>
291
+                                        <p className="text-xs text-muted-foreground">
292
+                                            Filled in for you when booking a
293
+                                            courier. You can change it for each
294
+                                            order.
295
+                                        </p>
296
+                                        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
297
+                                            <TextField
298
+                                                name="parcel_weight"
299
+                                                label="Weight (kg)"
300
+                                                value={settings.parcel_weight}
301
+                                                error={errors.parcel_weight}
302
+                                                inputMode="decimal"
303
+                                            />
304
+                                            <TextField
305
+                                                name="parcel_length"
306
+                                                label="Length (cm)"
307
+                                                value={settings.parcel_length}
308
+                                                error={errors.parcel_length}
309
+                                                inputMode="numeric"
310
+                                            />
311
+                                            <TextField
312
+                                                name="parcel_width"
313
+                                                label="Width (cm)"
314
+                                                value={settings.parcel_width}
315
+                                                error={errors.parcel_width}
316
+                                                inputMode="numeric"
317
+                                            />
318
+                                            <TextField
319
+                                                name="parcel_height"
320
+                                                label="Height (cm)"
321
+                                                value={settings.parcel_height}
322
+                                                error={errors.parcel_height}
323
+                                                inputMode="numeric"
324
+                                            />
325
+                                        </div>
326
+                                    </div>
327
+                                </CardContent>
328
+                            </Card>
329
+
172
                             <Card>
330
                             <Card>
173
                                 <CardHeader>
331
                                 <CardHeader>
174
                                     <CardTitle>Announcement bar</CardTitle>
332
                                     <CardTitle>Announcement bar</CardTitle>
264
     );
422
     );
265
 }
423
 }
266
 
424
 
425
+function TextField({
426
+    name,
427
+    label,
428
+    value,
429
+    error,
430
+    placeholder,
431
+    maxLength,
432
+    type = 'text',
433
+    inputMode,
434
+}: {
435
+    name: string;
436
+    label: string;
437
+    value: string;
438
+    error?: string;
439
+    placeholder?: string;
440
+    maxLength?: number;
441
+    type?: string;
442
+    inputMode?: 'text' | 'numeric' | 'decimal' | 'tel';
443
+}) {
444
+    return (
445
+        <div className="grid gap-2">
446
+            <Label htmlFor={name}>{label}</Label>
447
+            <Input
448
+                id={name}
449
+                name={name}
450
+                type={type}
451
+                inputMode={inputMode}
452
+                maxLength={maxLength}
453
+                defaultValue={value}
454
+                placeholder={placeholder}
455
+            />
456
+            <InputError message={error} />
457
+        </div>
458
+    );
459
+}
460
+
267
 StoreSettings.layout = {
461
 StoreSettings.layout = {
268
     breadcrumbs: [
462
     breadcrumbs: [
269
         { title: 'Overview', href: dashboard() },
463
         { title: 'Overview', href: dashboard() },

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

131
     shipped_at: string | null;
131
     shipped_at: string | null;
132
     shipping_courier: string | null;
132
     shipping_courier: string | null;
133
     tracking_number: string | null;
133
     tracking_number: string | null;
134
+    /** A courier booked through EasyParcel. */
135
+    shipment: {
136
+        number: string;
137
+        /** What the merchant paid EasyParcel, in ringgit. */
138
+        cost: number | null;
139
+        label_url: string | null;
140
+        tracking_url: string | null;
141
+    } | null;
134
     created_at: string | null;
142
     created_at: string | null;
135
     items: {
143
     items: {
136
         id: number;
144
         id: number;

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

8
 use App\Http\Controllers\CollectionController;
8
 use App\Http\Controllers\CollectionController;
9
 use App\Http\Controllers\DashboardController;
9
 use App\Http\Controllers\DashboardController;
10
 use App\Http\Controllers\DiscountCodeController;
10
 use App\Http\Controllers\DiscountCodeController;
11
+use App\Http\Controllers\EasyParcelController;
11
 use App\Http\Controllers\FeaturedProductController;
12
 use App\Http\Controllers\FeaturedProductController;
12
 use App\Http\Controllers\HeroImageController;
13
 use App\Http\Controllers\HeroImageController;
13
 use App\Http\Controllers\HomeController;
14
 use App\Http\Controllers\HomeController;
121
     Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
122
     Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
122
     Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');
123
     Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');
123
     Route::post('stores/{slug}/orders/{order}/ship', [OrderController::class, 'ship'])->name('stores.orders.ship')->whereNumber('order');
124
     Route::post('stores/{slug}/orders/{order}/ship', [OrderController::class, 'ship'])->name('stores.orders.ship')->whereNumber('order');
125
+    Route::post('stores/{slug}/orders/{order}/book', [OrderController::class, 'book'])->middleware('throttle:10,1')->name('stores.orders.book')->whereNumber('order');
126
+    Route::post('stores/{slug}/orders/{order}/label', [OrderController::class, 'refreshLabel'])->middleware('throttle:20,1')->name('stores.orders.label')->whereNumber('order');
127
+    Route::post('stores/{slug}/easyparcel/connect', [EasyParcelController::class, 'connect'])->name('stores.easyparcel.connect');
128
+    Route::delete('stores/{slug}/easyparcel', [EasyParcelController::class, 'disconnect'])->name('stores.easyparcel.disconnect');
129
+    // EasyParcel sends the merchant back here after they click Allow. One address for every store (the store is kept in the session).
130
+    Route::get('easyparcel/callback', [EasyParcelController::class, 'callback'])->name('easyparcel.callback');
124
 
131
 
125
     Route::get('stores/{slug}/products', [ProductController::class, 'index'])->name('stores.products.index');
132
     Route::get('stores/{slug}/products', [ProductController::class, 'index'])->name('stores.products.index');
126
     Route::get('stores/{slug}/products/create', [ProductController::class, 'create'])->name('stores.products.create');
133
     Route::get('stores/{slug}/products/create', [ProductController::class, 'create'])->name('stores.products.create');

+ 424
- 0
tests/Feature/Malaysia/EasyParcelTest.php Просмотреть файл

1
+<?php
2
+
3
+namespace Tests\Feature\Malaysia;
4
+
5
+use App\Mail\OrderShipped;
6
+use App\Models\EasyParcelAccount;
7
+use App\Models\Order;
8
+use App\Models\Store;
9
+use App\Models\User;
10
+use Illuminate\Foundation\Testing\RefreshDatabase;
11
+use Illuminate\Http\Client\Request;
12
+use Illuminate\Support\Facades\DB;
13
+use Illuminate\Support\Facades\Http;
14
+use Illuminate\Support\Facades\Mail;
15
+use Illuminate\Testing\TestResponse;
16
+use Inertia\Testing\AssertableInertia as Assert;
17
+use Tests\TestCase;
18
+
19
+/**
20
+ * Booking couriers through the merchant's own EasyParcel account. EasyParcel itself is pretend (Http::fake).
21
+ */
22
+class EasyParcelTest extends TestCase
23
+{
24
+    use RefreshDatabase;
25
+
26
+    private const string API = 'https://api.easyparcel.com/open_api/2026-09/';
27
+
28
+    private User $user;
29
+
30
+    private Store $store;
31
+
32
+    protected function setUp(): void
33
+    {
34
+        parent::setUp();
35
+
36
+        Mail::fake();
37
+        Http::preventStrayRequests();
38
+        config(['services.easyparcel.client_id' => 'test-client', 'services.easyparcel.client_secret' => 'test-secret']);
39
+
40
+        $this->user = User::factory()->create(['email' => 'owner@example.com']);
41
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
42
+        $this->actingAs($this->user);
43
+    }
44
+
45
+    private function connectStore(array $tokens = []): EasyParcelAccount
46
+    {
47
+        return $this->store->easyparcel()->create([
48
+            'account_name' => 'Kedai Ali Sdn Bhd',
49
+            'access_token' => 'access-1',
50
+            'refresh_token' => 'refresh-1',
51
+            'expires_at' => now()->addHours(5),
52
+            ...$tokens,
53
+        ]);
54
+    }
55
+
56
+    private function addPickup(): void
57
+    {
58
+        $this->store->pickup_address = [
59
+            'name' => 'Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null,
60
+            'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang',
61
+        ];
62
+        $this->store->save();
63
+    }
64
+
65
+    private function paidOrder(): Order
66
+    {
67
+        $order = Order::factory()->paid()->for($this->store)->create(['number' => 1042, 'shipping_total' => 800]);
68
+        $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau 250g', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
69
+
70
+        return $order;
71
+    }
72
+
73
+    private static function quotation(string $serviceId, string $courier, float $price, array $extra = []): array
74
+    {
75
+        return [
76
+            'courier' => [
77
+                'service_id' => $serviceId, 'service_name' => "{$courier} (Pick Up)", 'courier_name' => $courier,
78
+                'courier_logo' => 'https://example.com/logo.png', 'delivery_duration' => '1-3 working days',
79
+                'is_pickup' => true, 'is_dropoff' => false, 'is_deliver_to_point' => false, ...$extra,
80
+            ],
81
+            'pricing' => ['currency' => 'MYR', 'total_amount' => $price],
82
+        ];
83
+    }
84
+
85
+    private function book(Order $order, array $overrides = []): TestResponse
86
+    {
87
+        return $this->post(route('stores.orders.book', [$this->store->slug, $order->id]), [
88
+            'service_id' => 'EP-CS0J1', 'courier' => 'J&T Express', 'weight' => '1.2', 'length' => '20', 'width' => '15', 'height' => '10',
89
+            'collection_date' => now('Asia/Kuala_Lumpur')->addDay()->toDateString(),
90
+            ...$overrides,
91
+        ]);
92
+    }
93
+
94
+    public function test_connecting_sends_the_merchant_to_easyparcel_and_saves_the_account_when_they_come_back()
95
+    {
96
+        Http::fake([
97
+            'api.easyparcel.com/oauth/token' => Http::response(['token_type' => 'Bearer', 'access_token' => 'access-new', 'refresh_token' => 'refresh-new', 'expires_in' => 36000]),
98
+            self::API.'account/get_account_information' => Http::response(['status_code' => 200, 'data' => ['account' => ['name' => 'Kedai Ali Sdn Bhd']]]),
99
+        ]);
100
+
101
+        $response = $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
102
+        $response->assertStatus(409);
103
+        $location = $response->headers->get('X-Inertia-Location');
104
+        $this->assertStringStartsWith('https://api.easyparcel.com/oauth/login?', $location);
105
+        parse_str((string) parse_url($location, PHP_URL_QUERY), $query);
106
+        $this->assertSame('test-client', $query['client_id']);
107
+        $this->assertSame(route('easyparcel.callback'), $query['redirect_uri']);
108
+        $this->assertSame('S256', $query['code_challenge_method']);
109
+
110
+        $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $query['state']]))
111
+            ->assertRedirect(route('stores.settings', $this->store->slug));
112
+
113
+        $account = $this->store->fresh()->easyparcel;
114
+        $this->assertSame('Kedai Ali Sdn Bhd', $account->account_name);
115
+        $this->assertSame('access-new', $account->access_token);
116
+        $this->assertSame('refresh-new', $account->refresh_token);
117
+        // Tokens are kept encrypted in the database.
118
+        $this->assertStringNotContainsString('access-new', (string) DB::table('easyparcel_accounts')->value('access_token'));
119
+
120
+        Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token'
121
+            && $request['grant_type'] === 'authorization_code'
122
+            && $request['code'] === 'the-code'
123
+            && $request->hasHeader('Authorization', 'Basic '.base64_encode('test-client:test-secret')));
124
+    }
125
+
126
+    public function test_a_callback_with_the_wrong_state_is_refused()
127
+    {
128
+        Http::fake();
129
+        $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
130
+
131
+        $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => 'not-the-one']))->assertRedirect(route('dashboard'));
132
+
133
+        $this->assertNull($this->store->fresh()->easyparcel);
134
+        Http::assertNothingSent();
135
+    }
136
+
137
+    public function test_another_merchant_cannot_use_the_callback_for_this_store()
138
+    {
139
+        Http::fake();
140
+        $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
141
+        $state = session('easyparcel.connect.state');
142
+
143
+        $this->actingAs(User::factory()->create());
144
+        $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $state]))->assertRedirect(route('dashboard'));
145
+
146
+        $this->assertNull($this->store->fresh()->easyparcel);
147
+    }
148
+
149
+    public function test_settings_save_the_pickup_address_and_show_the_connection()
150
+    {
151
+        $this->connectStore();
152
+        Http::fake([self::API.'wallet' => Http::response(['status_code' => 200, 'data' => ['wallet' => [['balance' => 54.3, 'currency' => 'MYR']]]])]);
153
+
154
+        $this->put(route('stores.settings.update', $this->store->slug), [
155
+            'shipping_west' => '8', 'shipping_east' => '15',
156
+            'pickup_phone' => '012-345 6789', 'pickup_line1' => '1 Jalan Bukit', 'pickup_city' => 'Bayan Lepas',
157
+            'pickup_postcode' => '11950', 'pickup_state' => 'Pulau Pinang',
158
+            'parcel_weight' => '0.5', 'parcel_length' => '25', 'parcel_width' => '18', 'parcel_height' => '8',
159
+        ])->assertSessionHasNoErrors();
160
+
161
+        $store = $this->store->fresh();
162
+        $this->assertSame(['name' => 'Kedai Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null, 'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang'], $store->pickup_address);
163
+        $this->assertSame(500, $store->parcel_weight);
164
+        $this->assertSame(['length' => 25, 'width' => 18, 'height' => 8], $store->parcel_size);
165
+
166
+        $this->get(route('stores.settings', $this->store->slug))
167
+            ->assertInertia(fn (Assert $page) => $page
168
+                ->where('easyparcel.connected', true)
169
+                ->where('easyparcel.account_name', 'Kedai Ali Sdn Bhd')
170
+                ->where('settings.pickup.postcode', '11950')
171
+                ->missing('easyparcelBalance')
172
+                ->loadDeferredProps(fn (Assert $reload) => $reload->where('easyparcelBalance.amount', 54.3)));
173
+    }
174
+
175
+    public function test_a_half_filled_pickup_address_is_refused()
176
+    {
177
+        $this->put(route('stores.settings.update', $this->store->slug), [
178
+            'shipping_west' => '8', 'shipping_east' => '15', 'pickup_line1' => '1 Jalan Bukit',
179
+        ])->assertSessionHasErrors(['pickup_phone', 'pickup_city', 'pickup_postcode', 'pickup_state']);
180
+    }
181
+
182
+    public function test_the_merchant_sees_courier_prices_cheapest_first()
183
+    {
184
+        $this->connectStore();
185
+        $this->addPickup();
186
+        $order = $this->paidOrder();
187
+
188
+        Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
189
+            'status' => 'success',
190
+            'quotations' => [
191
+                self::quotation('EP-CS0PL', 'Poslaju National Courier', 9.5, ['service_name' => 'Poslaju (Pick Up with min 3 parcel(s)) (From Door to Door)', 'delivery_duration' => '{"type":"days","value":"3"}']),
192
+                self::quotation('EP-CS0J1', 'J&T Express', 6.8),
193
+                self::quotation('EP-CS0PT', 'Collect at point', 4.0, ['is_deliver_to_point' => true]),
194
+            ],
195
+        ]]])]);
196
+
197
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
198
+            ->assertOk()
199
+            ->assertInertia(fn (Assert $page) => $page
200
+                ->where('easyparcel.connected', true)
201
+                ->where('easyparcel.has_pickup_address', true)
202
+                ->missing('courier_quotes'));
203
+
204
+        // "See courier prices" reloads only the prices, with the parcel the merchant typed.
205
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1.2', 'length' => 20, 'width' => 15, 'height' => 10]))
206
+            ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
207
+                ->has('courier_quotes', 2)
208
+                ->where('courier_quotes.0.courier', 'J&T Express')
209
+                ->where('courier_quotes.0.price', 6.8)
210
+                ->where('courier_quotes.0.delivery', '1-3 working days')
211
+                ->where('courier_quotes.1.courier', 'Poslaju')
212
+                ->where('courier_quotes.1.delivery', 'About 3 days')
213
+                ->where('courier_quotes.1.note', 'Pickup needs at least 3 parcels')));
214
+
215
+        Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations')
216
+            && $request->hasHeader('Authorization', 'Bearer access-1')
217
+            && $request['shipment'][0]['sender'] === ['postcode' => '11950', 'subdivision_code' => 'MY-07', 'country' => 'MY']
218
+            && $request['shipment'][0]['receiver'] === ['postcode' => '40000', 'subdivision_code' => 'MY-10', 'country' => 'MY']
219
+            && $request['shipment'][0]['weight'] === 1.2);
220
+    }
221
+
222
+    public function test_booking_a_courier_saves_the_label_and_emails_the_shopper()
223
+    {
224
+        $this->connectStore();
225
+        $this->addPickup();
226
+        $order = $this->paidOrder();
227
+
228
+        Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
229
+            'order_details' => ['order_number' => 'EI-2611-AAAAA'],
230
+            'shipments' => [[
231
+                'status' => 'success', 'shipment_number' => 'ES-2611-BBBBB', 'courier' => 'J&T Express',
232
+                'awb_number' => '630012345678', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-BBBBB',
233
+                'tracking_url' => 'https://app.easyparcel.com/tools/easytrack/details?awb=630012345678',
234
+                'pricing_breakdown' => ['total_paid_amount' => '6.80'],
235
+            ]],
236
+        ]]])]);
237
+
238
+        $this->book($order)->assertRedirect(route('stores.orders.show', [$this->store->slug, $order->id]));
239
+
240
+        $order->refresh();
241
+        $this->assertSame('ES-2611-BBBBB', $order->shipment_number);
242
+        $this->assertSame('EI-2611-AAAAA', $order->shipment_order_number);
243
+        $this->assertSame(680, $order->shipment_cost);
244
+        $this->assertSame('J&T Express', $order->shipping_courier);
245
+        $this->assertSame('630012345678', $order->tracking_number);
246
+        $this->assertSame('https://app.easyparcel.com/label/ES-2611-BBBBB', $order->label_url);
247
+        $this->assertNotNull($order->shipped_at);
248
+        Mail::assertSent(OrderShipped::class, fn (OrderShipped $mail) => $mail->hasTo('aminah@example.com'));
249
+
250
+        Http::assertSent(function (Request $request) {
251
+            $shipment = $request['shipment'][0];
252
+
253
+            return $shipment['service_id'] === 'EP-CS0J1'
254
+                && $shipment['sender']['phone_number'] === '123456789'
255
+                && $shipment['sender']['subdivision_code'] === 'MY-07'
256
+                && $shipment['sender']['email'] === 'owner@example.com'
257
+                && $shipment['receiver']['name'] === 'Aminah binti Ali'
258
+                && $shipment['receiver']['subdivision_code'] === 'MY-10'
259
+                && $shipment['item'][0]['content'] === 'Sambal Hijau 250g'
260
+                && $shipment['item'][0]['quantity'] === 2
261
+                && $shipment['reference'] === 'Kedai Ali #1042';
262
+        });
263
+
264
+        // A second booking is refused.
265
+        $this->book($order);
266
+        Http::assertSentCount(1);
267
+    }
268
+
269
+    public function test_a_label_that_comes_later_is_fetched_and_the_shopper_emailed_then()
270
+    {
271
+        $this->connectStore();
272
+        $this->addPickup();
273
+        $order = $this->paidOrder();
274
+
275
+        Http::fake([
276
+            self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
277
+                'shipments' => [['status' => 'success', 'shipment_number' => 'ES-2611-CCCCC', 'courier' => 'Aramex', 'awb_number' => null, 'awb_url' => '', 'tracking_url' => null]],
278
+            ]]]),
279
+            self::API.'shipment/details' => Http::response(['status_code' => 200, 'data' => [[
280
+                'shipment_details' => ['awb_number' => '7028021894', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-CCCCC', 'tracking_url' => 'https://app.easyparcel.com/track/7028021894'],
281
+            ]]]),
282
+        ]);
283
+
284
+        $this->book($order);
285
+        $order->refresh();
286
+        $this->assertSame('ES-2611-CCCCC', $order->shipment_number);
287
+        $this->assertNull($order->tracking_number);
288
+        $this->assertNull($order->shipped_at);
289
+        Mail::assertNothingSent();
290
+
291
+        $this->post(route('stores.orders.label', [$this->store->slug, $order->id]))->assertSessionHasNoErrors();
292
+
293
+        $order->refresh();
294
+        $this->assertSame('7028021894', $order->tracking_number);
295
+        $this->assertSame('https://app.easyparcel.com/label/ES-2611-CCCCC', $order->label_url);
296
+        $this->assertNotNull($order->shipped_at);
297
+        Mail::assertSent(OrderShipped::class, 1);
298
+    }
299
+
300
+    public function test_an_easyparcel_error_is_shown_and_nothing_is_saved()
301
+    {
302
+        $this->connectStore();
303
+        $this->addPickup();
304
+        $order = $this->paidOrder();
305
+
306
+        Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
307
+            'status' => 'error', 'errors' => ['The receiver postcode field is required.'],
308
+        ]]])]);
309
+
310
+        $this->book($order)->assertSessionHasErrors(['booking' => 'EasyParcel: The receiver postcode field is required.']);
311
+
312
+        $this->assertNull($order->fresh()->shipment_number);
313
+        Mail::assertNothingSent();
314
+    }
315
+
316
+    public function test_the_price_shown_leaves_out_extras_we_do_not_book()
317
+    {
318
+        $this->connectStore();
319
+        $this->addPickup();
320
+        $order = $this->paidOrder();
321
+
322
+        // As the sandbox sent it for Pos MELPlus: RM 7.63 in total, of which RM 0.60 is tracking extras. Booking cost RM 7.03.
323
+        Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
324
+            'status' => 'success',
325
+            'quotations' => [[
326
+                'courier' => ['service_id' => 'EP-CS09E', 'service_name' => 'Pos MELPlus (Pick Up) (From Door to Door)', 'courier_name' => 'Pos Malaysia Berhad (Melplus)', 'is_pickup' => true, 'is_dropoff' => false, 'is_deliver_to_point' => false, 'delivery_duration' => null],
327
+                'pricing' => ['total_amount' => 7.63, 'shipment_price' => 6.63, 'shipment_tax' => 0.4, 'total_features_price' => 0.57, 'total_features_tax' => 0.03],
328
+            ]],
329
+        ]]])]);
330
+
331
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
332
+            ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
333
+                ->where('courier_quotes.0.courier', 'Pos MELPlus')
334
+                ->where('courier_quotes.0.price', 7.03)));
335
+    }
336
+
337
+    public function test_not_enough_credit_says_how_much_the_parcel_needs()
338
+    {
339
+        $this->connectStore();
340
+        $this->addPickup();
341
+        $order = $this->paidOrder();
342
+
343
+        // The shape the EasyParcel sandbox really sends: the error list is wrapped in another list.
344
+        Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
345
+            'order_details' => ['account_id' => '11043151'],
346
+            'shipments' => [[
347
+                'status' => 'error',
348
+                'errors' => [[['message' => 'Insufficient Credit Balance', 'code' => 'InsufficientCreditBalance', 'data' => ['current_balance' => 0, 'total_amount' => 7.03]]]],
349
+            ]],
350
+        ]]])]);
351
+
352
+        $this->book($order)->assertSessionHasErrors(['booking' => 'Not enough EasyParcel credit: this parcel needs RM 7.03. Top up your EasyParcel account and try again.']);
353
+        $this->assertNull($order->fresh()->shipment_number);
354
+    }
355
+
356
+    public function test_an_expired_token_is_renewed_and_the_call_tried_again()
357
+    {
358
+        $this->connectStore(['expires_at' => now()->subMinute()]);
359
+        $this->addPickup();
360
+        $order = $this->paidOrder();
361
+
362
+        Http::fake([
363
+            'api.easyparcel.com/oauth/token' => Http::response(['access_token' => 'access-2', 'expires_in' => 36000]),
364
+            self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [['status' => 'success', 'quotations' => []]]]),
365
+        ]);
366
+
367
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
368
+            ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload->where('courier_quotes', [])));
369
+
370
+        $account = $this->store->easyparcel()->first();
371
+        $this->assertSame('access-2', $account->access_token);
372
+        // EasyParcel sent no new refresh token, so the old one is kept.
373
+        $this->assertSame('refresh-1', $account->refresh_token);
374
+        Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token' && $request['grant_type'] === 'refresh_token' && $request['refresh_token'] === 'refresh-1');
375
+        Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations') && $request->hasHeader('Authorization', 'Bearer access-2'));
376
+    }
377
+
378
+    public function test_a_revoked_connection_asks_the_merchant_to_connect_again()
379
+    {
380
+        $this->connectStore();
381
+        $this->addPickup();
382
+        $order = $this->paidOrder();
383
+
384
+        Http::fake([
385
+            'api.easyparcel.com/oauth/token' => Http::response(['error' => 'invalid_grant'], 400),
386
+            self::API.'*' => Http::response(['message' => 'Unauthorized'], 401),
387
+        ]);
388
+
389
+        $this->book($order)->assertSessionHasErrors(['booking' => 'Your EasyParcel connection has expired. Connect EasyParcel again in Settings.']);
390
+    }
391
+
392
+    public function test_unpaid_orders_and_other_merchants_cannot_book()
393
+    {
394
+        $this->connectStore();
395
+        $this->addPickup();
396
+        Http::fake();
397
+
398
+        $unpaid = Order::factory()->for($this->store)->create();
399
+        $this->book($unpaid)->assertNotFound();
400
+
401
+        $order = $this->paidOrder();
402
+        $this->actingAs(User::factory()->create());
403
+        $this->book($order)->assertNotFound();
404
+
405
+        Http::assertNothingSent();
406
+    }
407
+
408
+    public function test_disconnecting_removes_the_account()
409
+    {
410
+        $this->connectStore();
411
+
412
+        $this->delete(route('stores.easyparcel.disconnect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
413
+
414
+        $this->assertNull($this->store->fresh()->easyparcel);
415
+    }
416
+
417
+    public function test_without_the_app_keys_connecting_explains_instead()
418
+    {
419
+        config(['services.easyparcel.client_id' => null]);
420
+
421
+        $this->post(route('stores.easyparcel.connect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
422
+        $this->get(route('stores.settings', $this->store->slug))->assertInertia(fn (Assert $page) => $page->where('easyparcel.available', false));
423
+    }
424
+}

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