소스 검색

- "Get paid" card in Settings: connect Stripe, finish setup, Stripe checking, connected with payouts status

- Payment pages and discount coupons are made in the merchant's own Stripe account; we take no cut
- Checkout is closed ("not taking orders yet") until Stripe approves the store
- FPX is requested and switched on for shoppers once the merchant finishes Stripe's form
- Second webhook for payments on merchants' accounts (STRIPE_CONNECT_WEBHOOK_SECRET)
- Overview: "Connect Stripe" step and a warning for live stores that cannot take payments
- Terms and privacy pages say how merchants are paid
- New stripe_accounts table and orders.payment_account (run php artisan migrate)
EOF
- Store "Email for shoppers" in Settings: order emails come under the store's name, replies go to the store
feature/stripe-connect
fahmisaad 1 일 전
부모
커밋
0b75851b8b
54개의 변경된 파일과 2217개의 추가작업 그리고 185개의 파일을 삭제
  1. 2
    0
      .env
  2. 74
    57
      PROGRESS.md
  3. 2
    0
      app/Commerce/Payments/CheckoutLink.php
  4. 18
    0
      app/Commerce/Payments/MerchantAccountStatus.php
  5. 39
    0
      app/Commerce/Payments/MerchantAccounts.php
  6. 10
    3
      app/Commerce/Payments/PaymentGateway.php
  7. 2
    0
      app/Commerce/Payments/PaymentStatus.php
  8. 114
    0
      app/Commerce/Payments/StripeConnect.php
  9. 44
    12
      app/Commerce/Payments/StripeGateway.php
  10. 101
    0
      app/Commerce/Payments/StripeMerchantAccounts.php
  11. 17
    2
      app/Dashboard/OverviewStats.php
  12. 9
    2
      app/Http/Controllers/CheckoutController.php
  13. 22
    2
      app/Http/Controllers/StoreSettingsController.php
  14. 109
    0
      app/Http/Controllers/StripeConnectController.php
  15. 39
    0
      app/Http/Controllers/StripeConnectWebhookController.php
  16. 14
    4
      app/Mail/OrderConfirmation.php
  17. 14
    3
      app/Mail/OrderShipped.php
  18. 172
    0
      app/Mail/StoreBrand.php
  19. 1
    0
      app/Models/Order.php
  20. 11
    0
      app/Models/Store.php
  21. 49
    0
      app/Models/StripeAccount.php
  22. 4
    0
      app/Providers/AppServiceProvider.php
  23. 2
    0
      app/Storefront/StorefrontText.php
  24. 1
    1
      bootstrap/app.php
  25. 1
    1
      config/legal.php
  26. 2
    0
      config/services.php
  27. 39
    0
      database/migrations/2026_11_30_000001_add_stripe_connect.php
  28. 23
    0
      database/migrations/2026_11_30_000002_add_contact_email_to_stores.php
  29. 5
    0
      resources/js/components/overview/format.ts
  30. 17
    1
      resources/js/components/overview/sections.tsx
  31. 205
    0
      resources/js/components/stores/get-paid-setup.tsx
  32. 3
    2
      resources/js/pages/legal/privacy.tsx
  33. 14
    2
      resources/js/pages/legal/terms.tsx
  34. 90
    29
      resources/js/pages/stores/settings.tsx
  35. 12
    1
      resources/js/storefront/pages/checkout.tsx
  36. 1
    0
      resources/js/storefront/renderer.tsx
  37. 4
    0
      resources/js/storefront/text.ts
  38. 2
    0
      resources/js/storefront/types.ts
  39. 2
    1
      resources/js/types/overview.ts
  40. 5
    0
      resources/views/components/mail/store-button.blade.php
  41. 61
    0
      resources/views/components/mail/store.blade.php
  42. 35
    0
      resources/views/mail/orders/confirmation-text.blade.php
  43. 84
    24
      resources/views/mail/orders/confirmation.blade.php
  44. 35
    0
      resources/views/mail/orders/shipped-text.blade.php
  45. 68
    26
      resources/views/mail/orders/shipped.blade.php
  46. 8
    0
      routes/web.php
  47. 1
    1
      tests/Feature/LegalPagesTest.php
  48. 3
    3
      tests/Feature/Malaysia/ShippingTest.php
  49. 2
    2
      tests/Feature/Stores/CheckoutTest.php
  50. 182
    0
      tests/Feature/Stores/OrderEmailTest.php
  51. 332
    0
      tests/Feature/Stores/StripeConnectTest.php
  52. 27
    6
      tests/Support/FakeGateway.php
  53. 81
    0
      tests/Support/FakeMerchantAccounts.php
  54. 3
    0
      tests/TestCase.php

+ 2
- 0
.env 파일 보기

98
 DB_QUEUE_RETRY_AFTER=600
98
 DB_QUEUE_RETRY_AFTER=600
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
+# Optional. The same for payments on merchants' own Stripe accounts ("Connected accounts" events). Starts with whsec_.
102
+STRIPE_CONNECT_WEBHOOK_SECRET=
101
 
103
 
102
 # EasyParcel app from developer.easyparcel.com. Put the real values in .env.local, never here.
104
 # 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.
105
 # Its redirect address must be <APP_URL>/easyparcel/callback.

+ 74
- 57
PROGRESS.md 파일 보기

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-30
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
7
+**Current step:** Step 10: Stripe Connect built on branch `feature/stripe-connect` (not committed yet) and tested for real in Stripe test mode: Luna Skin is connected, and a card payment and an FPX payment both landed in its own account. EasyParcel courier booking is done on branch `feature/easyparcel` (not committed yet). Step 9 part 8 on hold
8
+**Next action:** Commit, then merge `feature/easyparcel` and `feature/stripe-connect` into `main` (run `php artisan migrate`). 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
 
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.
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.
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.
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.
131
+- Stripe only accepts its newer accounts API for this ("Accounts v2": `$stripe->v2->core->accounts` and `accountLinks`; our `stripe/stripe-php` 23 has it). The older one was refused on 2026-11-30. The account is made with `dashboard: full`, country `my`, currency `myr`, the `merchant` configuration with card payments, and Stripe collecting fees and covering losses. FPX cannot be asked for when the account is made (Stripe first needs the business type), so it is asked for after the merchant finishes Stripe's sign-up. Found in the real test: the v2 update refuses Malaysian sole proprietors, so FPX is asked for with the older capability call; and an approved FPX still starts switched off in the merchant's payment method settings, so we switch it on there too (otherwise shoppers only see cards).
132
+- Stripe's test sign-up asks for a password and two-step sign-in (the merchant does these), then business, person, bank ("Use test account") and public details. Its page went blank once; our `resume` link opened a fresh one.
133
+- One Stripe account per store, like EasyParcel. Code: `app/Commerce/Payments/` (`StripeConnect`, `MerchantAccounts`, `StripeMerchantAccounts`), `StripeConnectController`, `StripeConnectWebhookController`.
134
+- Orders paid before Stripe Connect (into our own account) have no `payment_account` and are still checked in our own account.
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.
135
 - 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.
136
 - 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.
137
 - Discount coupons are made on the merchant's Stripe account, because the payment page lives there.
152
 - WhatsApp numbers are saved as digits with country code (`60123456789`). Only Malaysian numbers are accepted. `MalaysianPhone` does the cleaning.
155
 - WhatsApp numbers are saved as digits with country code (`60123456789`). Only Malaysian numbers are accepted. `MalaysianPhone` does the cleaning.
153
 - Messages the server shows to shoppers live in `App\Storefront\StorefrontText`; words drawn in the browser live in `resources/js/storefront/text.ts`.
156
 - Messages the server shows to shoppers live in `App\Storefront\StorefrontText`; words drawn in the browser live in `resources/js/storefront/text.ts`.
154
 
157
 
158
+### Shopper emails (restyled 2026-11-30)
159
+
160
+- The "order paid" and "order shipped" emails are in the store's own look, not ours: its name (from its header), colours, heading and body fonts (with a safe fallback of the same kind, since email apps rarely load web fonts) and corner rounding, from the design shoppers see. Our app's name is not shown.
161
+- Built with `App\Mail\StoreBrand` and the Blade components `x-mail.store` (frame) and `x-mail.store-button`, tables and inline styles only. Each email also has a plain-text version.
162
+- Buttons: "View your order" (the live store's order page, or the merchant's preview when the store is not live), "Ask on WhatsApp" when the store has a number (a text link in the shipped email), and "Track your parcel" when the courier gave a tracking link. Buttons stack on phones.
163
+- Links are built from `APP_URL`, because the paid email can be sent from the webhook, where there is no shopper visit.
164
+- Sender and replies (added 2026-11-30): the emails come from our address (so they are delivered) but under the store's name, such as "Luna Skin <hello@…>". Replies go to the store's "Email for shoppers" (`stores.contact_email`), set in Settings under "How shoppers reach you" next to WhatsApp, with a one-click "Use <account email>". It is also shown at the bottom of the emails. When empty, there is no reply address. The account email is never used unless the merchant saves it.
165
+
155
 ### How discount codes work (added in Step 8)
166
 ### How discount codes work (added in Step 8)
156
 
167
 
157
 - Codes live in the `discount_codes` table, per store, saved in capital letters. Shoppers may type them in any case.
168
 - Codes live in the `discount_codes` table, per store, saved in capital letters. Shoppers may type them in any case.
502
 
513
 
503
 - [x] Overview dashboard with stats, store tree in the sidebar and daily AI note (done 2026-11-22, branch `feature/dashboard`)
514
 - [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"):
515
 - [ ] 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
516
+    - [x] You: switch on Connect in the Stripe dashboard in **test mode** (done 2026-11-30). "Activate products" and "Create your Stripe profile" in Stripe's setup guide are for live mode only, so they wait until launch
517
+    - [x] Checked 2026-11-30 with the test key: Stripe made a Malaysian merchant account, gave a Stripe sign-up link for it, and made a payment page on it. Plan B is not needed
518
+    - [x] Branch `feature/stripe-connect` (made from `feature/easyparcel`, because EasyParcel is not merged into `main` yet): table `stripe_accounts` for each store's Stripe account (account id, can take payments, payouts on, form finished, FPX asked), and `payment_account` on each order
519
+    - [x] Settings: a "Get paid" card at the top with what to have ready, "Connect Stripe", "Finish setup" if they stopped halfway, "Stripe is checking your details", and a connected view (payouts on or paused, link to their Stripe Dashboard)
520
+    - [x] Checkout: the payment page is made on the store's Stripe account (coupons too). Checkout is closed until the store can take payments ("This store is not taking orders yet", in English and Malay)
521
+    - [x] Return page checks the payment in the merchant's account; a second webhook `/stripe/connect-webhook` (secret `STRIPE_CONNECT_WEBHOOK_SECRET`) only marks an order paid when the payment is in that order's merchant account. `account.updated` was left out: the account is re-checked when the merchant comes back from Stripe, and at most once a minute from Settings or checkout
522
+    - [x] Overview: "Connect Stripe to get paid" is a getting-started step, and a live store that cannot take payments shows in "Needs attention"
523
+    - [x] Terms page says how merchants are paid (straight to their own Stripe account, Stripe's Connected Account Agreement, no cut); privacy page says shoppers' payments go to the merchant's Stripe account; "last changed" is now 2026-11-30
524
+    - [x] Tests with a pretend Stripe (`FakeMerchantAccounts`): 15 new tests, 341 in all pass
525
+    - [x] Real test on 2026-11-30: Luna Skin signed up on Stripe's test form (sole proprietorship, Stripe's test values and test bank), came back "Connected", then order #1008 (Gentle Gel Cleanser RM 42 + RM 8 shipping) was paid with Stripe's test card. Stripe's page said "Pay Luna Skin Enterprise"; RM 50.00 landed in Luna Skin's own test account (RM 47.00 after Stripe's fee), nothing in ours, no cut. Order marked paid, email sent. Payouts turned on a minute later
526
+    - [x] FPX test on 2026-11-30: order #1009 (Light Water-Gel Moisturiser 50ml RM 39 + RM 8 shipping) paid with FPX (Maybank2E, Stripe's test bank page). RM 47.00 landed in Luna Skin's own account (RM 44.59 after Stripe's fee), nothing in ours. Order marked paid on the return page
515
     - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
527
     - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
516
 - [ ] Choose hosting and deploy
528
 - [ ] Choose hosting and deploy
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)
529
 - [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)
647
 
659
 
648
 Add one line per work session: date, what was done, what is next.
660
 Add one line per work session: date, what was done, what is next.
649
 
661
 
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` |
662
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | Next                                                            |
663
+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
664
+| 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) |
665
+| 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                   |
666
+| 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                 |
667
+| 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                 |
668
+| 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                    |
669
+| 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                                       |
670
+| 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                        |
671
+| 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             |
672
+| 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                |
673
+| 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                      |
674
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Step 5: publishing                                              |
675
+| 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                                              |
676
+| 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                                              |
677
+| 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                                    |
678
+| 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                                  |
679
+| 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                             |
680
+| 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               |
681
+| 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                    |
682
+| 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                                    |
683
+| 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                               |
684
+| 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                                       |
685
+| 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        |
686
+| 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                             |
687
+| 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                             |
688
+| 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                                     |
689
+| 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                                              |
690
+| 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                             |
691
+| 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                             |
692
+| 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                             |
693
+| 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                             |
694
+| 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                                    |
695
+| 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                             |
696
+| 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                                      |
697
+| 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                                                |
698
+| 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                                        |
699
+| 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                               |
700
+| 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                                        |
701
+| 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                                |
702
+| 2026-11-26 | Decided to use the new design: merged `feature/dashboard` into `main`, old design kept as tag `old-design`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | EasyParcel demo key                                             |
703
+| 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                     |
704
+| 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                                                |
705
+| 2026-11-30 | Planned how merchants get paid: Stripe Connect with each merchant's own Stripe account, direct charges, no cut for us. Connect switched on in Stripe test mode; a test made a Malaysian merchant account, its sign-up link and a payment page on it (newer Accounts v2 needed). Plan and tasks written in Step 10.                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit EasyParcel; build `feature/stripe-connect`               |
706
+| 2026-11-30 | Built Stripe Connect on branch `feature/stripe-connect`: "Get paid" card in Settings, merchant Stripe accounts (Accounts v2), payment pages and coupons in the merchant's account, checkout closed until Stripe approves, second webhook, overview step and warning, terms and privacy wording. 341 tests pass; Stripe's test sign-up page opened from Settings.                                                                                                                                                                                                                                                                                                                                                                                         | Test sign-up and test payment, then commit and merge            |
707
+| 2026-11-30 | Stripe Connect tested for real (test mode): Luna Skin signed up and connected; order #1008 (RM 50) paid into Luna Skin's own Stripe account, none in ours. Fixed FPX: asked for with the older capability call and switched on in the merchant's payment settings, so FPX now shows to shoppers. 341 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                         | Commit and merge                                                |
708
+| 2026-11-30 | FPX test passed: order #1009 (RM 47) paid with FPX (Maybank2E test bank) into Luna Skin's own Stripe account.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | Commit and merge                                                |
709
+| 2026-11-30 | Restyled the shopper emails (order paid, order shipped) in each store's own colours, fonts and corners, with View order, WhatsApp and Track parcel buttons and plain-text versions. Checked on desktop and phone width for Luna Skin, Sambal Nenek (Malay, serif) and Crunch & Co. 349 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit and merge                                                |
710
+| 2026-11-30 | Store contact email: "How shoppers reach you" card in Settings (WhatsApp + email for shoppers); order emails are sent under the store's name with replies to that email, shown in the footer. 352 tests pass; saved and checked for Luna Skin.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Commit and merge                                                |

+ 2
- 0
app/Commerce/Payments/CheckoutLink.php 파일 보기

12
         public string $id,
12
         public string $id,
13
         /** Where to send the shopper to pay. */
13
         /** Where to send the shopper to pay. */
14
         public string $url,
14
         public string $url,
15
+        /** The merchant's account the page was made in. Null for our own account. */
16
+        public ?string $account = null,
15
     ) {}
17
     ) {}
16
 }
18
 }

+ 18
- 0
app/Commerce/Payments/MerchantAccountStatus.php 파일 보기

1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+/**
6
+ * What the provider says about a merchant's account.
7
+ */
8
+final readonly class MerchantAccountStatus
9
+{
10
+    public function __construct(
11
+        /** Shoppers can pay into the account. */
12
+        public bool $chargesEnabled,
13
+        /** The money is paid out to the merchant's bank. */
14
+        public bool $payoutsEnabled,
15
+        /** The merchant finished the sign-up form. */
16
+        public bool $detailsSubmitted,
17
+    ) {}
18
+}

+ 39
- 0
app/Commerce/Payments/MerchantAccounts.php 파일 보기

1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Models\Store;
6
+
7
+/**
8
+ * Merchants' own payment accounts (Stripe Connect). Shoppers pay straight into them, never into ours.
9
+ */
10
+interface MerchantAccounts
11
+{
12
+    /**
13
+     * Open a new account for the store. Returns the provider's account id.
14
+     *
15
+     * @throws PaymentException
16
+     */
17
+    public function create(Store $store, string $email): string;
18
+
19
+    /**
20
+     * A one-time link to the provider's own sign-up form for the account.
21
+     * The merchant comes back to $returnUrl, or to $refreshUrl when the link has expired.
22
+     *
23
+     * @throws PaymentException
24
+     */
25
+    public function setupLink(string $accountId, string $returnUrl, string $refreshUrl): string;
26
+
27
+    /**
28
+     * @throws PaymentException
29
+     */
30
+    public function status(string $accountId): MerchantAccountStatus;
31
+
32
+    /**
33
+     * Ask the provider to switch on FPX (online banking) for the account, and show it to shoppers.
34
+     * Only possible once the merchant has finished the sign-up form.
35
+     *
36
+     * @throws PaymentException
37
+     */
38
+    public function requestFpx(string $accountId): void;
39
+}

+ 10
- 3
app/Commerce/Payments/PaymentGateway.php 파일 보기

3
 namespace App\Commerce\Payments;
3
 namespace App\Commerce\Payments;
4
 
4
 
5
 use App\Models\Order;
5
 use App\Models\Order;
6
+use App\Models\Store;
6
 
7
 
7
 /**
8
 /**
8
  * The one interface the app uses to take payments.
9
  * The one interface the app uses to take payments.
13
     /** The name saved on the order, such as "stripe". */
14
     /** The name saved on the order, such as "stripe". */
14
     public function name(): string;
15
     public function name(): string;
15
 
16
 
17
+    /**
18
+     * Whether shoppers can pay this store now (with Stripe: the merchant connected their own account and Stripe approved it).
19
+     */
20
+    public function canTakePayments(Store $store): bool;
21
+
16
     /**
22
     /**
17
      * Create a payment page for the order and say where to send the shopper.
23
      * Create a payment page for the order and say where to send the shopper.
18
      *
24
      *
21
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink;
27
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink;
22
 
28
 
23
     /**
29
     /**
24
-     * Ask the provider about a payment page we created earlier.
30
+     * Ask the provider about the order's payment page, in the account it was made in.
25
      *
31
      *
26
      * @throws PaymentException
32
      * @throws PaymentException
27
      */
33
      */
28
-    public function checkPayment(string $checkoutId): PaymentStatus;
34
+    public function checkPayment(Order $order): PaymentStatus;
29
 
35
 
30
     /**
36
     /**
31
      * Read a message the provider sent to our webhook address.
37
      * Read a message the provider sent to our webhook address.
38
+     * $fromMerchants is true for the address that hears about payments on merchants' own accounts.
32
      * Returns null when the message is about something we do not handle.
39
      * Returns null when the message is about something we do not handle.
33
      *
40
      *
34
      * @throws PaymentException When the message is not genuine.
41
      * @throws PaymentException When the message is not genuine.
35
      */
42
      */
36
-    public function readWebhook(string $payload, string $signature): ?PaymentStatus;
43
+    public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus;
37
 }
44
 }

+ 2
- 0
app/Commerce/Payments/PaymentStatus.php 파일 보기

14
         public ?string $reference = null,
14
         public ?string $reference = null,
15
         /** The amount the provider collected, in sen. */
15
         /** The amount the provider collected, in sen. */
16
         public ?int $amount = null,
16
         public ?int $amount = null,
17
+        /** The merchant's account the payment was made in, when the provider says. */
18
+        public ?string $account = null,
17
     ) {}
19
     ) {}
18
 }
20
 }

+ 114
- 0
app/Commerce/Payments/StripeConnect.php 파일 보기

1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Models\Store;
6
+use App\Models\StripeAccount;
7
+
8
+/**
9
+ * Getting a store ready to take payments into the merchant's own Stripe account.
10
+ *
11
+ * We keep a copy of what Stripe says about the account. While the account is not fully set up, the copy is
12
+ * refreshed when the merchant comes back from Stripe, and at most once a minute when Settings opens or a
13
+ * shopper reaches checkout.
14
+ */
15
+class StripeConnect
16
+{
17
+    /** How long a "not ready" answer is trusted before we ask Stripe again. */
18
+    private const int RECHECK_SECONDS = 60;
19
+
20
+    public function __construct(private readonly MerchantAccounts $accounts) {}
21
+
22
+    public function isConfigured(): bool
23
+    {
24
+        return (string) config('services.stripe.secret') !== '';
25
+    }
26
+
27
+    /**
28
+     * Where to send the merchant to fill in Stripe's sign-up form. Opens the account the first time.
29
+     *
30
+     * @throws PaymentException
31
+     */
32
+    public function setupUrl(Store $store, string $email, string $returnUrl, string $refreshUrl): string
33
+    {
34
+        $account = $store->stripeAccount;
35
+
36
+        if ($account === null) {
37
+            $account = $store->stripeAccount()->create(['account_id' => $this->accounts->create($store, $email)]);
38
+            $store->setRelation('stripeAccount', $account);
39
+        }
40
+
41
+        return $this->accounts->setupLink($account->account_id, $returnUrl, $refreshUrl);
42
+    }
43
+
44
+    /**
45
+     * Ask Stripe about the store's account and save the answer.
46
+     * The first time the sign-up form is finished, FPX is asked for too.
47
+     *
48
+     * @throws PaymentException
49
+     */
50
+    public function refresh(Store $store): ?StripeAccount
51
+    {
52
+        $account = $store->stripeAccount;
53
+
54
+        if ($account === null) {
55
+            return null;
56
+        }
57
+
58
+        $status = $this->accounts->status($account->account_id);
59
+
60
+        $account->fill([
61
+            'charges_enabled' => $status->chargesEnabled,
62
+            'payouts_enabled' => $status->payoutsEnabled,
63
+            'details_submitted' => $status->detailsSubmitted,
64
+            'checked_at' => now(),
65
+        ]);
66
+
67
+        if ($status->detailsSubmitted && ! $account->fpx_requested) {
68
+            try {
69
+                $this->accounts->requestFpx($account->account_id);
70
+                $account->fpx_requested = true;
71
+            } catch (PaymentException $e) {
72
+                // Cards still work. We try again next time.
73
+                report($e);
74
+            }
75
+        }
76
+
77
+        $account->save();
78
+
79
+        return $account;
80
+    }
81
+
82
+    /**
83
+     * The store's account, refreshed from Stripe when it is not fully set up and was not checked in the last minute.
84
+     * A store that is fully set up is not asked about again here.
85
+     */
86
+    public function current(Store $store): ?StripeAccount
87
+    {
88
+        $account = $store->stripeAccount;
89
+
90
+        if ($account === null || ($account->charges_enabled && $account->payouts_enabled)) {
91
+            return $account;
92
+        }
93
+
94
+        if ($account->checked_at !== null && $account->checked_at->diffInSeconds(now()) < self::RECHECK_SECONDS) {
95
+            return $account;
96
+        }
97
+
98
+        try {
99
+            return $this->refresh($store);
100
+        } catch (PaymentException $e) {
101
+            report($e);
102
+
103
+            return $account;
104
+        }
105
+    }
106
+
107
+    /**
108
+     * Whether shoppers can pay this store now.
109
+     */
110
+    public function canTakePayments(Store $store): bool
111
+    {
112
+        return (bool) $this->current($store)?->charges_enabled;
113
+    }
114
+}

+ 44
- 12
app/Commerce/Payments/StripeGateway.php 파일 보기

4
 
4
 
5
 use App\Models\Order;
5
 use App\Models\Order;
6
 use App\Models\OrderItem;
6
 use App\Models\OrderItem;
7
+use App\Models\Store;
7
 use Stripe\Checkout\Session;
8
 use Stripe\Checkout\Session;
8
 use Stripe\Exception\ApiErrorException;
9
 use Stripe\Exception\ApiErrorException;
9
 use Stripe\Exception\SignatureVerificationException;
10
 use Stripe\Exception\SignatureVerificationException;
14
 /**
15
 /**
15
  * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
16
  * Payments through Stripe Checkout: Stripe hosts the payment page, so card details never touch our server.
16
  *
17
  *
18
+ * The page is made in the merchant's own Stripe account (Stripe Connect "direct charges"), so the money goes
19
+ * straight to them and they are the seller on the shopper's receipt. We take no cut.
20
+ *
17
  * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
21
  * No payment method list is sent, so Stripe shows whatever is switched on in the Stripe dashboard
18
  * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
22
  * for Malaysian Ringgit (cards, FPX, GrabPay and so on).
19
  */
23
  */
20
 final class StripeGateway implements PaymentGateway
24
 final class StripeGateway implements PaymentGateway
21
 {
25
 {
26
+    public function __construct(private readonly StripeConnect $connect) {}
27
+
22
     public function name(): string
28
     public function name(): string
23
     {
29
     {
24
         return 'stripe';
30
         return 'stripe';
25
     }
31
     }
26
 
32
 
33
+    public function canTakePayments(Store $store): bool
34
+    {
35
+        return $this->connect->canTakePayments($store);
36
+    }
37
+
27
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
38
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
28
     {
39
     {
40
+        $account = $order->store->stripeAccount?->account_id;
41
+
42
+        if ($account === null) {
43
+            throw new PaymentException('The store has not connected its Stripe account.');
44
+        }
45
+
46
+        // Everything for this payment is made in the merchant's account.
47
+        $in = ['stripe_account' => $account];
48
+
29
         try {
49
         try {
30
             $session = $this->client()->checkout->sessions->create([
50
             $session = $this->client()->checkout->sessions->create([
31
                 'mode' => 'payment',
51
                 'mode' => 'payment',
41
                     ],
61
                     ],
42
                 ])->values()->all(),
62
                 ])->values()->all(),
43
                 // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
63
                 // A one-off Stripe coupon for exactly the discount, so Stripe's page shows the code and the saving.
44
-                ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order)]]] : []),
64
+                ...($order->discount_total > 0 ? ['discounts' => [['coupon' => $this->couponFor($order, $in)]]] : []),
45
                 // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
65
                 // Shipping is shown on Stripe's page as its own line, so the shopper sees what they pay for.
46
                 'shipping_options' => [[
66
                 'shipping_options' => [[
47
                     'shipping_rate_data' => [
67
                     'shipping_rate_data' => [
53
                 // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
73
                 // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
54
                 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
74
                 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
55
                 'cancel_url' => $cancelUrl,
75
                 'cancel_url' => $cancelUrl,
56
-            ]);
76
+            ], $in);
57
         } catch (ApiErrorException $e) {
77
         } catch (ApiErrorException $e) {
58
             throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
78
             throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
59
         }
79
         }
62
             throw new PaymentException('Stripe did not return a payment page address.');
82
             throw new PaymentException('Stripe did not return a payment page address.');
63
         }
83
         }
64
 
84
 
65
-        return new CheckoutLink($session->id, $session->url);
85
+        return new CheckoutLink($session->id, $session->url, $account);
66
     }
86
     }
67
 
87
 
68
     /**
88
     /**
69
      * A coupon that can be used once, worth exactly this order's discount.
89
      * A coupon that can be used once, worth exactly this order's discount.
70
      * Stripe takes it off the products only, never off shipping, which matches our own rule.
90
      * Stripe takes it off the products only, never off shipping, which matches our own rule.
71
      *
91
      *
92
+     * @param  array{stripe_account: string}  $in
93
+     *
72
      * @throws ApiErrorException
94
      * @throws ApiErrorException
73
      */
95
      */
74
-    private function couponFor(Order $order): string
96
+    private function couponFor(Order $order, array $in): string
75
     {
97
     {
76
         return $this->client()->coupons->create([
98
         return $this->client()->coupons->create([
77
             'amount_off' => $order->discount_total,
99
             'amount_off' => $order->discount_total,
81
             // The code, or the automatic discount's name, such as "Raya Sale".
103
             // The code, or the automatic discount's name, such as "Raya Sale".
82
             'name' => $order->discount_code ?? $order->discount_name ?? 'Discount',
104
             'name' => $order->discount_code ?? $order->discount_name ?? 'Discount',
83
             'metadata' => ['order_id' => (string) $order->id],
105
             'metadata' => ['order_id' => (string) $order->id],
84
-        ])->id;
106
+        ], $in)->id;
85
     }
107
     }
86
 
108
 
87
     private function shippingLabel(Order $order): string
109
     private function shippingLabel(Order $order): string
95
         return $malay ? 'Penghantaran' : 'Shipping';
117
         return $malay ? 'Penghantaran' : 'Shipping';
96
     }
118
     }
97
 
119
 
98
-    public function checkPayment(string $checkoutId): PaymentStatus
120
+    public function checkPayment(Order $order): PaymentStatus
99
     {
121
     {
122
+        if ($order->payment_checkout_id === null) {
123
+            throw new PaymentException('The order has no payment page.');
124
+        }
125
+
126
+        // Older test orders were paid into our own account and have no merchant account.
127
+        $in = $order->payment_account !== null ? ['stripe_account' => $order->payment_account] : [];
128
+
100
         try {
129
         try {
101
-            return $this->status($this->client()->checkout->sessions->retrieve($checkoutId));
130
+            return $this->status($this->client()->checkout->sessions->retrieve($order->payment_checkout_id, [], $in));
102
         } catch (ApiErrorException $e) {
131
         } catch (ApiErrorException $e) {
103
             throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
132
             throw new PaymentException('Stripe could not find the payment: '.$e->getMessage(), 0, $e);
104
         }
133
         }
105
     }
134
     }
106
 
135
 
107
-    public function readWebhook(string $payload, string $signature): ?PaymentStatus
136
+    public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
108
     {
137
     {
109
-        $secret = (string) config('services.stripe.webhook_secret');
138
+        // Stripe signs messages about merchants' accounts with a different secret.
139
+        $name = $fromMerchants ? 'connect_webhook_secret' : 'webhook_secret';
140
+        $secret = (string) config('services.stripe.'.$name);
110
 
141
 
111
         if ($secret === '') {
142
         if ($secret === '') {
112
-            throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
143
+            throw new PaymentException('services.stripe.'.$name.' is not set.');
113
         }
144
         }
114
 
145
 
115
         try {
146
         try {
126
             return null;
157
             return null;
127
         }
158
         }
128
 
159
 
129
-        return $this->status($session);
160
+        return $this->status($session, is_string($event->account ?? null) ? $event->account : null);
130
     }
161
     }
131
 
162
 
132
-    private function status(Session $session): PaymentStatus
163
+    private function status(Session $session, ?string $account = null): PaymentStatus
133
     {
164
     {
134
         return new PaymentStatus(
165
         return new PaymentStatus(
135
             checkoutId: $session->id,
166
             checkoutId: $session->id,
136
             paid: $session->payment_status === 'paid',
167
             paid: $session->payment_status === 'paid',
137
             reference: is_string($session->payment_intent) ? $session->payment_intent : null,
168
             reference: is_string($session->payment_intent) ? $session->payment_intent : null,
138
             amount: $session->amount_total,
169
             amount: $session->amount_total,
170
+            account: $account,
139
         );
171
         );
140
     }
172
     }
141
 
173
 

+ 101
- 0
app/Commerce/Payments/StripeMerchantAccounts.php 파일 보기

1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Models\Store;
6
+use Stripe\Exception\ApiErrorException;
7
+use Stripe\StripeClient;
8
+
9
+/**
10
+ * Merchants' own Stripe accounts, through Stripe Connect.
11
+ *
12
+ * Stripe only accepts its newer accounts API (v2) for new platforms. Each account gets the full Stripe Dashboard,
13
+ * pays Stripe's fees itself, and Stripe covers losses, so the merchant is the seller in every way.
14
+ */
15
+final class StripeMerchantAccounts implements MerchantAccounts
16
+{
17
+    public function create(Store $store, string $email): string
18
+    {
19
+        try {
20
+            return $this->client()->v2->core->accounts->create([
21
+                'contact_email' => $email,
22
+                'display_name' => $store->name,
23
+                'dashboard' => 'full',
24
+                'identity' => ['country' => 'my'],
25
+                // FPX cannot be asked for yet: Stripe first needs the business type from the sign-up form.
26
+                'configuration' => ['merchant' => ['capabilities' => ['card_payments' => ['requested' => true]]]],
27
+                'defaults' => [
28
+                    'currency' => 'myr',
29
+                    'responsibilities' => ['fees_collector' => 'stripe', 'losses_collector' => 'stripe'],
30
+                ],
31
+                'metadata' => ['store_id' => (string) $store->id],
32
+            ])->id;
33
+        } catch (ApiErrorException $e) {
34
+            throw new PaymentException('Stripe could not open an account: '.$e->getMessage(), 0, $e);
35
+        }
36
+    }
37
+
38
+    public function setupLink(string $accountId, string $returnUrl, string $refreshUrl): string
39
+    {
40
+        try {
41
+            return $this->client()->v2->core->accountLinks->create([
42
+                'account' => $accountId,
43
+                'use_case' => [
44
+                    'type' => 'account_onboarding',
45
+                    'account_onboarding' => [
46
+                        'return_url' => $returnUrl,
47
+                        'refresh_url' => $refreshUrl,
48
+                    ],
49
+                ],
50
+            ])->url;
51
+        } catch (ApiErrorException $e) {
52
+            throw new PaymentException('Stripe could not open its sign-up form: '.$e->getMessage(), 0, $e);
53
+        }
54
+    }
55
+
56
+    public function status(string $accountId): MerchantAccountStatus
57
+    {
58
+        try {
59
+            // The older accounts API still reads v2 accounts, and says plainly what we need.
60
+            $account = $this->client()->accounts->retrieve($accountId);
61
+        } catch (ApiErrorException $e) {
62
+            throw new PaymentException('Stripe could not find the account: '.$e->getMessage(), 0, $e);
63
+        }
64
+
65
+        return new MerchantAccountStatus(
66
+            chargesEnabled: (bool) $account->charges_enabled,
67
+            payoutsEnabled: (bool) $account->payouts_enabled,
68
+            detailsSubmitted: (bool) $account->details_submitted,
69
+        );
70
+    }
71
+
72
+    public function requestFpx(string $accountId): void
73
+    {
74
+        try {
75
+            // The older capability call. The v2 update refuses Malaysian sole proprietors
76
+            // ("sole_proprietorship is not supported for entity type company"), found on 2026-11-30.
77
+            $client = $this->client();
78
+            $in = ['stripe_account' => $accountId];
79
+            $client->accounts->updateCapability($accountId, 'fpx_payments', ['requested' => true]);
80
+
81
+            // Approved is not enough: FPX also starts switched off in the account's payment method
82
+            // settings, so shoppers would only see cards. Switch it on there too.
83
+            foreach ($client->paymentMethodConfigurations->all(['limit' => 10], $in)->data as $configuration) {
84
+                $client->paymentMethodConfigurations->update($configuration->id, ['fpx' => ['display_preference' => ['preference' => 'on']]], $in);
85
+            }
86
+        } catch (ApiErrorException $e) {
87
+            throw new PaymentException('Stripe could not switch on FPX: '.$e->getMessage(), 0, $e);
88
+        }
89
+    }
90
+
91
+    private function client(): StripeClient
92
+    {
93
+        $secret = (string) config('services.stripe.secret');
94
+
95
+        if ($secret === '') {
96
+            throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
97
+        }
98
+
99
+        return new StripeClient($secret);
100
+    }
101
+}

+ 17
- 2
app/Dashboard/OverviewStats.php 파일 보기

117
      */
117
      */
118
     public function gettingStarted(User $user): array
118
     public function gettingStarted(User $user): array
119
     {
119
     {
120
-        $stores = $user->stores()->orderBy('created_at')->get();
120
+        $stores = $user->stores()->with('stripeAccount')->orderBy('created_at')->get();
121
         $first = $stores->first();
121
         $first = $stores->first();
122
 
122
 
123
         return [
123
         return [
126
                 'create' => $stores->isNotEmpty(),
126
                 'create' => $stores->isNotEmpty(),
127
                 'design' => $stores->contains(fn (Store $store) => $store->plan !== null),
127
                 'design' => $stores->contains(fn (Store $store) => $store->plan !== null),
128
                 'products' => Product::query()->whereIn('store_id', $stores->pluck('id'))->where('status', ProductStatus::Active)->exists(),
128
                 'products' => Product::query()->whereIn('store_id', $stores->pluck('id'))->where('status', ProductStatus::Active)->exists(),
129
+                // The merchant's own Stripe account is ready, so shoppers can pay.
130
+                'payments' => $stores->contains(fn (Store $store) => (bool) $store->stripeAccount?->charges_enabled),
129
                 'publish' => $stores->contains(fn (Store $store) => $store->isPublished()),
131
                 'publish' => $stores->contains(fn (Store $store) => $store->isPublished()),
130
             ],
132
             ],
131
         ];
133
         ];
258
 
260
 
259
     /**
261
     /**
260
      * What the merchant should look at now, most urgent first: orders to ship, products running out,
262
      * What the merchant should look at now, most urgent first: orders to ship, products running out,
261
-     * designs waiting to be published, and the plan.
263
+     * live stores that cannot take payments, designs waiting to be published, and the plan.
262
      *
264
      *
263
      * @param  Collection<int, Store>  $stores
265
      * @param  Collection<int, Store>  $stores
264
      * @param  list<int>  $storeIds
266
      * @param  list<int>  $storeIds
308
             ];
310
             ];
309
         }
311
         }
310
 
312
 
313
+        // A live store that cannot take payments loses every order, so this comes before design work.
314
+        foreach ($shown->loadMissing('stripeAccount') as $store) {
315
+            if ($store->isPublished() && ! $store->stripeAccount?->charges_enabled) {
316
+                $items[] = [
317
+                    'kind' => 'payments',
318
+                    'tone' => 'danger',
319
+                    'title' => 'Can’t take payments yet',
320
+                    'note' => 'Connect Stripe so shoppers can pay',
321
+                    'store' => ['name' => $store->name, 'slug' => $store->slug],
322
+                ];
323
+            }
324
+        }
325
+
311
         foreach ($shown as $store) {
326
         foreach ($shown as $store) {
312
             if ($store->hasUnpublishedChanges()) {
327
             if ($store->hasUnpublishedChanges()) {
313
                 $items[] = [
328
                 $items[] = [

+ 9
- 2
app/Http/Controllers/CheckoutController.php 파일 보기

28
     /**
28
     /**
29
      * The form for the shopper's contact details and delivery address.
29
      * The form for the shopper's contact details and delivery address.
30
      */
30
      */
31
-    public function show(Request $request, ShippingProvider $shipping): Response|RedirectResponse
31
+    public function show(Request $request, ShippingProvider $shipping, PaymentGateway $gateway): Response|RedirectResponse
32
     {
32
     {
33
         $storefront = $this->storefront($request);
33
         $storefront = $this->storefront($request);
34
         $lines = $this->cart($request, $storefront->store)->lines();
34
         $lines = $this->cart($request, $storefront->store)->lines();
46
         return $this->renderStorefront($request, $storefront, [
46
         return $this->renderStorefront($request, $storefront, [
47
             'type' => 'checkout',
47
             'type' => 'checkout',
48
             'states' => MalaysianStates::ALL,
48
             'states' => MalaysianStates::ALL,
49
+            // False until the merchant connects their own Stripe account and Stripe approves it.
50
+            'takingOrders' => $gateway->canTakePayments($storefront->store),
49
             // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
51
             // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
50
             'shippingByState' => collect(MalaysianStates::ALL)
52
             'shippingByState' => collect(MalaysianStates::ALL)
51
                 ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $afterDiscount, $state) / 100])
53
                 ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $afterDiscount, $state) / 100])
72
             'state' => ['required', Rule::in(MalaysianStates::ALL)],
74
             'state' => ['required', Rule::in(MalaysianStates::ALL)],
73
         ], StorefrontText::checkoutMessages($store->language->value), StorefrontText::checkoutFields($store->language->value));
75
         ], StorefrontText::checkoutMessages($store->language->value), StorefrontText::checkoutFields($store->language->value));
74
 
76
 
77
+        if (! $gateway->canTakePayments($store)) {
78
+            throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'not_taking_orders')]);
79
+        }
80
+
75
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
81
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
76
 
82
 
77
         try {
83
         try {
91
 
97
 
92
         $order->payment_provider = $gateway->name();
98
         $order->payment_provider = $gateway->name();
93
         $order->payment_checkout_id = $link->id;
99
         $order->payment_checkout_id = $link->id;
100
+        $order->payment_account = $link->account;
94
         $order->save();
101
         $order->save();
95
 
102
 
96
         // The payment page is on another website, so this is a full browser redirect.
103
         // The payment page is on another website, so this is a full browser redirect.
111
         // Ask the payment provider directly. Nothing in the web address is trusted.
118
         // Ask the payment provider directly. Nothing in the web address is trusted.
112
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
119
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
113
             try {
120
             try {
114
-                $checkout->markPaid($order, $gateway->checkPayment($order->payment_checkout_id));
121
+                $checkout->markPaid($order, $gateway->checkPayment($order));
115
             } catch (PaymentException $e) {
122
             } catch (PaymentException $e) {
116
                 report($e);
123
                 report($e);
117
             }
124
             }

+ 22
- 2
app/Http/Controllers/StoreSettingsController.php 파일 보기

3
 namespace App\Http\Controllers;
3
 namespace App\Http\Controllers;
4
 
4
 
5
 use App\Commerce\MalaysianStates;
5
 use App\Commerce\MalaysianStates;
6
+use App\Commerce\Payments\StripeConnect;
6
 use App\Commerce\Shipping\EasyParcel\EasyParcel;
7
 use App\Commerce\Shipping\EasyParcel\EasyParcel;
7
 use App\Commerce\Shipping\EasyParcel\EasyParcelException;
8
 use App\Commerce\Shipping\EasyParcel\EasyParcelException;
8
 use App\Models\EasyParcelAccount;
9
 use App\Models\EasyParcelAccount;
17
 use Inertia\Response;
18
 use Inertia\Response;
18
 
19
 
19
 /**
20
 /**
20
- * Store-wide settings that are not part of the design: WhatsApp number, shipping fees, EasyParcel and the announcement bar.
21
+ * Store-wide settings that are not part of the design: getting paid, WhatsApp number, contact email, shipping fees, EasyParcel and the announcement bar.
21
  */
22
  */
22
 class StoreSettingsController extends Controller
23
 class StoreSettingsController extends Controller
23
 {
24
 {
24
-    public function edit(Request $request, string $slug, EasyParcel $easyparcel): Response
25
+    public function edit(Request $request, string $slug, EasyParcel $easyparcel, StripeConnect $stripe): Response
25
     {
26
     {
26
         $store = $this->ownedStore($request, $slug);
27
         $store = $this->ownedStore($request, $slug);
28
+        $payments = $stripe->current($store);
27
         $account = $store->easyparcel;
29
         $account = $store->easyparcel;
28
         $pickup = $store->pickup_address;
30
         $pickup = $store->pickup_address;
29
         $size = $store->parcel_size ?? OrderController::DEFAULT_SIZE;
31
         $size = $store->parcel_size ?? OrderController::DEFAULT_SIZE;
32
             'store' => ['name' => $store->name, 'slug' => $store->slug],
34
             'store' => ['name' => $store->name, 'slug' => $store->slug],
33
             'settings' => [
35
             'settings' => [
34
                 'whatsapp_number' => $store->whatsapp_number,
36
                 'whatsapp_number' => $store->whatsapp_number,
37
+                'contact_email' => $store->contact_email,
35
                 'shipping_west' => self::ringgit($store->shipping_west),
38
                 'shipping_west' => self::ringgit($store->shipping_west),
36
                 'shipping_east' => self::ringgit($store->shipping_east),
39
                 'shipping_east' => self::ringgit($store->shipping_east),
37
                 'free_shipping_over' => $store->free_shipping_over !== null ? self::ringgit($store->free_shipping_over) : null,
40
                 'free_shipping_over' => $store->free_shipping_over !== null ? self::ringgit($store->free_shipping_over) : null,
53
                 'parcel_height' => (string) $size['height'],
56
                 'parcel_height' => (string) $size['height'],
54
             ],
57
             ],
55
             'states' => MalaysianStates::ALL,
58
             'states' => MalaysianStates::ALL,
59
+            // Suggested for the contact email, never used unless the merchant saves it.
60
+            'accountEmail' => $request->user()->email,
61
+            // The merchant's own Stripe account, where shoppers' payments go.
62
+            'payments' => [
63
+                'available' => $stripe->isConfigured(),
64
+                'connected' => $payments !== null,
65
+                'details_submitted' => (bool) $payments?->details_submitted,
66
+                'can_take_payments' => (bool) $payments?->charges_enabled,
67
+                'payouts_enabled' => (bool) $payments?->payouts_enabled,
68
+            ],
56
             'easyparcel' => [
69
             'easyparcel' => [
57
                 // False until the app's own EasyParcel keys are in .env.local.
70
                 // False until the app's own EasyParcel keys are in .env.local.
58
                 'available' => $easyparcel->isConfigured(),
71
                 'available' => $easyparcel->isConfigured(),
73
 
86
 
74
         $validated = $request->validate([
87
         $validated = $request->validate([
75
             'whatsapp_number' => ['nullable', 'string', 'max:30'],
88
             'whatsapp_number' => ['nullable', 'string', 'max:30'],
89
+            'contact_email' => ['nullable', 'email', 'max:160'],
76
             'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
90
             'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
77
             'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
91
             'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
78
             'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
92
             'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
145
         }
159
         }
146
 
160
 
147
         $store->whatsapp_number = $whatsapp;
161
         $store->whatsapp_number = $whatsapp;
162
+
163
+        // Left as it was when the form does not send it.
164
+        if (array_key_exists('contact_email', $validated)) {
165
+            $store->contact_email = filled($validated['contact_email']) ? mb_strtolower(trim($validated['contact_email'])) : null;
166
+        }
167
+
148
         $store->shipping_west = self::sen($validated['shipping_west']);
168
         $store->shipping_west = self::sen($validated['shipping_west']);
149
         $store->shipping_east = self::sen($validated['shipping_east']);
169
         $store->shipping_east = self::sen($validated['shipping_east']);
150
         $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
170
         $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;

+ 109
- 0
app/Http/Controllers/StripeConnectController.php 파일 보기

1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Payments\PaymentException;
6
+use App\Commerce\Payments\StripeConnect;
7
+use App\Models\Store;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Inertia\Inertia;
11
+use Symfony\Component\HttpFoundation\Response;
12
+
13
+/**
14
+ * Getting paid: the merchant fills in Stripe's own sign-up form for their store's Stripe account, then comes back.
15
+ * Stripe checks their identity, business and bank. We never see those details.
16
+ */
17
+class StripeConnectController extends Controller
18
+{
19
+    public function connect(Request $request, string $slug, StripeConnect $connect): Response
20
+    {
21
+        $store = $this->ownedStore($request, $slug);
22
+
23
+        if (! $connect->isConfigured()) {
24
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('Stripe is not set up on this app yet.')]);
25
+
26
+            return to_route('stores.settings', $store->slug);
27
+        }
28
+
29
+        try {
30
+            $url = $this->setupUrl($request, $store, $connect);
31
+        } catch (PaymentException $e) {
32
+            report($e);
33
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('Stripe could not be reached. Please try again in a moment.')]);
34
+
35
+            return to_route('stores.settings', $store->slug);
36
+        }
37
+
38
+        // A full page visit to Stripe, not an Inertia one.
39
+        return Inertia::location($url);
40
+    }
41
+
42
+    /**
43
+     * Stripe sends the merchant back here when they finish or leave the form.
44
+     */
45
+    public function return(Request $request, string $slug, StripeConnect $connect): RedirectResponse
46
+    {
47
+        $store = $this->ownedStore($request, $slug);
48
+
49
+        try {
50
+            $account = $connect->refresh($store);
51
+        } catch (PaymentException $e) {
52
+            report($e);
53
+            $account = $store->stripeAccount;
54
+        }
55
+
56
+        $message = match (true) {
57
+            $account === null => null,
58
+            $account->charges_enabled => ['type' => 'success', 'message' => __('Stripe is connected. Your store can take payments.')],
59
+            $account->details_submitted => ['type' => 'success', 'message' => __('Thank you. Stripe is checking your details, which usually takes a few minutes.')],
60
+            default => ['type' => 'error', 'message' => __('Stripe sign-up is not finished yet. Click Finish setup to carry on.')],
61
+        };
62
+
63
+        if ($message !== null) {
64
+            Inertia::flash('toast', $message);
65
+        }
66
+
67
+        return to_route('stores.settings', $store->slug);
68
+    }
69
+
70
+    /**
71
+     * Stripe's sign-up link only works once and for a short time. When it expired, Stripe sends the
72
+     * merchant here, and we open a fresh one.
73
+     */
74
+    public function resume(Request $request, string $slug, StripeConnect $connect): RedirectResponse
75
+    {
76
+        $store = $this->ownedStore($request, $slug);
77
+
78
+        if ($store->stripeAccount === null) {
79
+            return to_route('stores.settings', $store->slug);
80
+        }
81
+
82
+        try {
83
+            return redirect()->away($this->setupUrl($request, $store, $connect));
84
+        } catch (PaymentException $e) {
85
+            report($e);
86
+            Inertia::flash('toast', ['type' => 'error', 'message' => __('Stripe could not be reached. Please try again in a moment.')]);
87
+
88
+            return to_route('stores.settings', $store->slug);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * @throws PaymentException
94
+     */
95
+    private function setupUrl(Request $request, Store $store, StripeConnect $connect): string
96
+    {
97
+        return $connect->setupUrl(
98
+            $store,
99
+            (string) $request->user()->email,
100
+            returnUrl: route('stores.payments.return', $store->slug),
101
+            refreshUrl: route('stores.payments.resume', $store->slug),
102
+        );
103
+    }
104
+
105
+    private function ownedStore(Request $request, string $slug): Store
106
+    {
107
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
108
+    }
109
+}

+ 39
- 0
app/Http/Controllers/StripeConnectWebhookController.php 파일 보기

1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Checkout;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Commerce\Payments\PaymentGateway;
8
+use App\Models\Order;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Http\Response;
11
+
12
+/**
13
+ * Stripe calls this address about payments made in merchants' own Stripe accounts ("Connected accounts" events).
14
+ *
15
+ * It is the safety net for shoppers who pay but close the browser before coming back to the store.
16
+ * Messages are signed with their own secret (STRIPE_CONNECT_WEBHOOK_SECRET) and checked before anything is done.
17
+ */
18
+class StripeConnectWebhookController extends Controller
19
+{
20
+    public function __invoke(Request $request, PaymentGateway $gateway, Checkout $checkout): Response
21
+    {
22
+        try {
23
+            $payment = $gateway->readWebhook($request->getContent(), (string) $request->header('Stripe-Signature'), fromMerchants: true);
24
+        } catch (PaymentException) {
25
+            return response('Invalid webhook.', 400);
26
+        }
27
+
28
+        if ($payment !== null) {
29
+            $order = Order::query()->where('payment_checkout_id', $payment->checkoutId)->first();
30
+
31
+            // The payment must be in the same merchant account the order's payment page was made in.
32
+            if ($order !== null && $payment->account !== null && $payment->account === $order->payment_account) {
33
+                $checkout->markPaid($order, $payment);
34
+            }
35
+        }
36
+
37
+        return response('OK');
38
+    }
39
+}

+ 14
- 4
app/Mail/OrderConfirmation.php 파일 보기

5
 use App\Models\Order;
5
 use App\Models\Order;
6
 use Illuminate\Bus\Queueable;
6
 use Illuminate\Bus\Queueable;
7
 use Illuminate\Mail\Mailable;
7
 use Illuminate\Mail\Mailable;
8
+use Illuminate\Mail\Mailables\Address;
8
 use Illuminate\Mail\Mailables\Content;
9
 use Illuminate\Mail\Mailables\Content;
9
 use Illuminate\Mail\Mailables\Envelope;
10
 use Illuminate\Mail\Mailables\Envelope;
10
 use Illuminate\Queue\SerializesModels;
11
 use Illuminate\Queue\SerializesModels;
23
         $store = $this->order->store;
24
         $store = $this->order->store;
24
 
25
 
25
         return new Envelope(
26
         return new Envelope(
27
+            // Sent from our address (so it is delivered), but under the store's name, with replies going to the store.
28
+            from: new Address((string) config('mail.from.address'), $store->name),
29
+            replyTo: $store->contact_email !== null ? [new Address($store->contact_email, $store->name)] : [],
26
             subject: $store->language->value === 'ms'
30
             subject: $store->language->value === 'ms'
27
                 ? "Pesanan #{$this->order->number} disahkan - {$store->name}"
31
                 ? "Pesanan #{$this->order->number} disahkan - {$store->name}"
28
                 : "Order #{$this->order->number} confirmed - {$store->name}",
32
                 : "Order #{$this->order->number} confirmed - {$store->name}",
31
 
35
 
32
     public function content(): Content
36
     public function content(): Content
33
     {
37
     {
38
+        $store = $this->order->store;
39
+        $brand = StoreBrand::for($store);
40
+
34
         return new Content(
41
         return new Content(
35
-            markdown: 'mail.orders.confirmation',
42
+            // In the store's own colours, fonts and corners, so shoppers see the shop they bought from.
43
+            view: 'mail.orders.confirmation',
44
+            text: 'mail.orders.confirmation-text',
36
             with: [
45
             with: [
37
                 'order' => $this->order->loadMissing('items'),
46
                 'order' => $this->order->loadMissing('items'),
38
-                'store' => $this->order->store,
39
-                'malay' => $this->order->store->language->value === 'ms',
40
-                'money' => fn (int $sen): string => 'RM '.number_format($sen / 100, 2),
47
+                'store' => $store,
48
+                'brand' => $brand,
49
+                'orderUrl' => $brand->orderUrl($this->order),
50
+                'whatsappUrl' => $brand->whatsappUrl($this->order),
41
             ],
51
             ],
42
         );
52
         );
43
     }
53
     }

+ 14
- 3
app/Mail/OrderShipped.php 파일 보기

5
 use App\Models\Order;
5
 use App\Models\Order;
6
 use Illuminate\Bus\Queueable;
6
 use Illuminate\Bus\Queueable;
7
 use Illuminate\Mail\Mailable;
7
 use Illuminate\Mail\Mailable;
8
+use Illuminate\Mail\Mailables\Address;
8
 use Illuminate\Mail\Mailables\Content;
9
 use Illuminate\Mail\Mailables\Content;
9
 use Illuminate\Mail\Mailables\Envelope;
10
 use Illuminate\Mail\Mailables\Envelope;
10
 use Illuminate\Queue\SerializesModels;
11
 use Illuminate\Queue\SerializesModels;
23
         $store = $this->order->store;
24
         $store = $this->order->store;
24
 
25
 
25
         return new Envelope(
26
         return new Envelope(
27
+            // Sent from our address (so it is delivered), but under the store's name, with replies going to the store.
28
+            from: new Address((string) config('mail.from.address'), $store->name),
29
+            replyTo: $store->contact_email !== null ? [new Address($store->contact_email, $store->name)] : [],
26
             subject: $store->language->value === 'ms'
30
             subject: $store->language->value === 'ms'
27
                 ? "Pesanan #{$this->order->number} telah dihantar - {$store->name}"
31
                 ? "Pesanan #{$this->order->number} telah dihantar - {$store->name}"
28
                 : "Order #{$this->order->number} is on its way - {$store->name}",
32
                 : "Order #{$this->order->number} is on its way - {$store->name}",
31
 
35
 
32
     public function content(): Content
36
     public function content(): Content
33
     {
37
     {
38
+        $store = $this->order->store;
39
+        $brand = StoreBrand::for($store);
40
+
34
         return new Content(
41
         return new Content(
35
-            markdown: 'mail.orders.shipped',
42
+            // In the store's own colours, fonts and corners, so shoppers see the shop they bought from.
43
+            view: 'mail.orders.shipped',
44
+            text: 'mail.orders.shipped-text',
36
             with: [
45
             with: [
37
                 'order' => $this->order->loadMissing('items'),
46
                 'order' => $this->order->loadMissing('items'),
38
-                'store' => $this->order->store,
39
-                'malay' => $this->order->store->language->value === 'ms',
47
+                'store' => $store,
48
+                'brand' => $brand,
49
+                'orderUrl' => $brand->orderUrl($this->order),
50
+                'whatsappUrl' => $brand->whatsappUrl($this->order),
40
             ],
51
             ],
41
         );
52
         );
42
     }
53
     }

+ 172
- 0
app/Mail/StoreBrand.php 파일 보기

1
+<?php
2
+
3
+namespace App\Mail;
4
+
5
+use App\Models\Order;
6
+use App\Models\Store;
7
+use App\StorePlan\PlanSchema;
8
+use App\Support\MalaysianPhone;
9
+
10
+/**
11
+ * How a store looks in the emails its shoppers get: its name, colours, fonts and corners,
12
+ * taken from the design shoppers see. Plus the links the emails need.
13
+ *
14
+ * Emails cannot load the store's web fonts reliably, so each font comes with a safe fallback
15
+ * of the same kind (serif or sans-serif).
16
+ */
17
+final readonly class StoreBrand
18
+{
19
+    /** Used when a store has no design yet. Calm and neutral. */
20
+    private const array DEFAULT_COLORS = [
21
+        'background' => '#F6F5F2',
22
+        'surface' => '#FFFFFF',
23
+        'foreground' => '#1F1F1F',
24
+        'muted' => '#6B6B6B',
25
+        'primary' => '#1F1F1F',
26
+        'primaryForeground' => '#FFFFFF',
27
+        'accent' => '#C9A227',
28
+        'border' => '#E4E1DA',
29
+    ];
30
+
31
+    private const array SERIF_FONTS = ['playfair-display', 'lora', 'fraunces', 'cormorant-garamond', 'dm-serif-display', 'libre-baskerville'];
32
+
33
+    /**
34
+     * @param  array<string, string>  $colors
35
+     */
36
+    private function __construct(
37
+        public Store $store,
38
+        public string $name,
39
+        public array $colors,
40
+        public string $headingFont,
41
+        public string $bodyFont,
42
+        /** Corner rounding for cards, in pixels. */
43
+        public int $radius,
44
+        /** Corner rounding for buttons, in pixels. */
45
+        public int $buttonRadius,
46
+        public bool $malay,
47
+    ) {}
48
+
49
+    public static function for(Store $store): self
50
+    {
51
+        // What shoppers see: the published design, or the draft while the store is not live yet.
52
+        $plan = $store->published_plan ?? $store->plan ?? [];
53
+        $theme = $plan['theme'] ?? [];
54
+
55
+        $colors = self::DEFAULT_COLORS;
56
+
57
+        foreach (PlanSchema::COLORS as $key) {
58
+            $value = $theme['colors'][$key] ?? null;
59
+
60
+            if (is_string($value) && preg_match('/^#[0-9A-Fa-f]{6}$/', $value) === 1) {
61
+                $colors[$key] = $value;
62
+            }
63
+        }
64
+
65
+        $radius = match ($theme['radius'] ?? 'medium') {
66
+            'none' => 0,
67
+            'small' => 4,
68
+            'large' => 16,
69
+            'full' => 20,
70
+            default => 8,
71
+        };
72
+
73
+        return new self(
74
+            store: $store,
75
+            name: self::logoText($plan) ?? $store->name,
76
+            colors: $colors,
77
+            headingFont: self::fontStack($theme['fonts']['heading'] ?? null),
78
+            bodyFont: self::fontStack($theme['fonts']['body'] ?? null),
79
+            radius: $radius,
80
+            buttonRadius: ($theme['radius'] ?? null) === 'full' ? 999 : $radius,
81
+            malay: $store->language->value === 'ms',
82
+        );
83
+    }
84
+
85
+    /**
86
+     * The email address shoppers can write to, when the merchant set one.
87
+     */
88
+    public function contactEmail(): ?string
89
+    {
90
+        return $this->store->contact_email;
91
+    }
92
+
93
+    public function color(string $key): string
94
+    {
95
+        return $this->colors[$key];
96
+    }
97
+
98
+    /**
99
+     * The shopper's order page. A live store's page is on the store's own address; a store that is not
100
+     * published yet only has the merchant's preview, so the link opens that.
101
+     */
102
+    public function orderUrl(Order $order): string
103
+    {
104
+        if (! $this->store->isPublished()) {
105
+            return route('stores.preview.order', [$this->store->slug, $order->public_id]);
106
+        }
107
+
108
+        return $this->storeUrl().'/orders/'.$order->public_id;
109
+    }
110
+
111
+    /**
112
+     * The store's own home page.
113
+     */
114
+    public function storeUrl(): string
115
+    {
116
+        if (! $this->store->isPublished()) {
117
+            return route('stores.preview', $this->store->slug);
118
+        }
119
+
120
+        // Built from APP_URL, because emails are also sent from the webhook, where there is no shopper's visit.
121
+        $app = parse_url((string) config('app.url'));
122
+        $scheme = $app['scheme'] ?? 'https';
123
+        $port = isset($app['port']) ? ':'.$app['port'] : '';
124
+
125
+        return $scheme.'://'.$this->store->slug.'.'.config('storefront.domain').$port;
126
+    }
127
+
128
+    /**
129
+     * A WhatsApp chat with the store about this order, or null when the store has no WhatsApp number.
130
+     */
131
+    public function whatsappUrl(Order $order): ?string
132
+    {
133
+        if ($this->store->whatsapp_number === null || $this->store->whatsapp_number === '') {
134
+            return null;
135
+        }
136
+
137
+        $text = $this->malay
138
+            ? "Hai {$this->store->name}, saya ada soalan tentang pesanan saya #{$order->number}."
139
+            : "Hi {$this->store->name}, I have a question about my order #{$order->number}.";
140
+
141
+        return MalaysianPhone::whatsappLink($this->store->whatsapp_number, $text);
142
+    }
143
+
144
+    public function money(int $sen): string
145
+    {
146
+        return 'RM '.number_format($sen / 100, 2);
147
+    }
148
+
149
+    /**
150
+     * The words shown in the header, from the store's own header section when it has one.
151
+     *
152
+     * @param  array<string, mixed>  $plan
153
+     */
154
+    private static function logoText(array $plan): ?string
155
+    {
156
+        // Version 2 plans keep one shared header; older ones have it among the sections.
157
+        $header = $plan['header'] ?? collect($plan['sections'] ?? [])->firstWhere('type', 'header');
158
+        $text = trim((string) ($header['content']['logoText'] ?? ''));
159
+
160
+        return $text !== '' ? $text : null;
161
+    }
162
+
163
+    private static function fontStack(?string $key): string
164
+    {
165
+        $family = PlanSchema::FONTS[$key] ?? null;
166
+        $fallback = in_array($key, self::SERIF_FONTS, true)
167
+            ? "Georgia, 'Times New Roman', serif"
168
+            : 'Helvetica, Arial, sans-serif';
169
+
170
+        return $family !== null ? "'{$family}', {$fallback}" : $fallback;
171
+    }
172
+}

+ 1
- 0
app/Models/Order.php 파일 보기

35
  * @property string $currency
35
  * @property string $currency
36
  * @property string|null $payment_provider
36
  * @property string|null $payment_provider
37
  * @property string|null $payment_checkout_id
37
  * @property string|null $payment_checkout_id
38
+ * @property string|null $payment_account The merchant's Stripe account the order was paid into (null: our own account)
38
  * @property string|null $payment_reference
39
  * @property string|null $payment_reference
39
  * @property CarbonInterface|null $paid_at
40
  * @property CarbonInterface|null $paid_at
40
  * @property CarbonInterface|null $shipped_at
41
  * @property CarbonInterface|null $shipped_at

+ 11
- 0
app/Models/Store.php 파일 보기

30
  * @property StoreStatus $status
30
  * @property StoreStatus $status
31
  * @property array<string, mixed>|null $plan
31
  * @property array<string, mixed>|null $plan
32
  * @property string|null $whatsapp_number
32
  * @property string|null $whatsapp_number
33
+ * @property string|null $contact_email Where shoppers' replies to the store's emails go
33
  * @property int $shipping_west
34
  * @property int $shipping_west
34
  * @property int $shipping_east
35
  * @property int $shipping_east
35
  * @property int|null $free_shipping_over
36
  * @property int|null $free_shipping_over
187
         return $this->hasOne(EasyParcelAccount::class);
188
         return $this->hasOne(EasyParcelAccount::class);
188
     }
189
     }
189
 
190
 
191
+    /**
192
+     * The merchant's own Stripe account, where shoppers' payments go.
193
+     *
194
+     * @return HasOne<StripeAccount, $this>
195
+     */
196
+    public function stripeAccount(): HasOne
197
+    {
198
+        return $this->hasOne(StripeAccount::class);
199
+    }
200
+
190
     /**
201
     /**
191
      * @return HasMany<Order, $this>
202
      * @return HasMany<Order, $this>
192
      */
203
      */

+ 49
- 0
app/Models/StripeAccount.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 own Stripe account (Stripe Connect). Shoppers' payments go straight into it.
12
+ *
13
+ * @property int $id
14
+ * @property int $store_id
15
+ * @property string $account_id Stripe's id, such as acct_1Abc...
16
+ * @property bool $charges_enabled Stripe lets the account take payments
17
+ * @property bool $payouts_enabled Stripe pays the money into the merchant's bank
18
+ * @property bool $details_submitted The merchant finished Stripe's sign-up form
19
+ * @property bool $fpx_requested
20
+ * @property CarbonInterface|null $checked_at When we last asked Stripe
21
+ * @property CarbonInterface|null $created_at
22
+ * @property CarbonInterface|null $updated_at
23
+ * @property-read Store $store
24
+ */
25
+#[Fillable(['account_id', 'charges_enabled', 'payouts_enabled', 'details_submitted', 'fpx_requested', 'checked_at'])]
26
+class StripeAccount extends Model
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
+            'charges_enabled' => 'boolean',
43
+            'payouts_enabled' => 'boolean',
44
+            'details_submitted' => 'boolean',
45
+            'fpx_requested' => 'boolean',
46
+            'checked_at' => 'datetime',
47
+        ];
48
+    }
49
+}

+ 4
- 0
app/Providers/AppServiceProvider.php 파일 보기

4
 
4
 
5
 use App\Billing\StripeSubscriptionGateway;
5
 use App\Billing\StripeSubscriptionGateway;
6
 use App\Billing\SubscriptionGateway;
6
 use App\Billing\SubscriptionGateway;
7
+use App\Commerce\Payments\MerchantAccounts;
7
 use App\Commerce\Payments\PaymentGateway;
8
 use App\Commerce\Payments\PaymentGateway;
8
 use App\Commerce\Payments\StripeGateway;
9
 use App\Commerce\Payments\StripeGateway;
10
+use App\Commerce\Payments\StripeMerchantAccounts;
9
 use App\Commerce\Shipping\EasyParcel\EasyParcel;
11
 use App\Commerce\Shipping\EasyParcel\EasyParcel;
10
 use App\Commerce\Shipping\FlatRateShipping;
12
 use App\Commerce\Shipping\FlatRateShipping;
11
 use App\Commerce\Shipping\ShippingProvider;
13
 use App\Commerce\Shipping\ShippingProvider;
24
     {
26
     {
25
         // Payments go through one interface, so the provider can be changed in one place.
27
         // Payments go through one interface, so the provider can be changed in one place.
26
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
28
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
29
+        // Merchants' own Stripe accounts (Stripe Connect), where shoppers' payments go.
30
+        $this->app->bind(MerchantAccounts::class, StripeMerchantAccounts::class);
27
         $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
31
         $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
28
         $this->app->bind(ShippingProvider::class, FlatRateShipping::class);
32
         $this->app->bind(ShippingProvider::class, FlatRateShipping::class);
29
         $this->app->bind(EasyParcel::class, fn () => EasyParcel::fromConfig());
33
         $this->app->bind(EasyParcel::class, fn () => EasyParcel::fromConfig());

+ 2
- 0
app/Storefront/StorefrontText.php 파일 보기

16
             'sold_out' => 'This product is sold out.',
16
             'sold_out' => 'This product is sold out.',
17
             'choose_option' => 'Please choose an option first.',
17
             'choose_option' => 'Please choose an option first.',
18
             'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
18
             'payment_unavailable' => 'We could not start the payment. Please try again in a moment.',
19
+            'not_taking_orders' => 'This store is not taking orders yet. Please check back soon.',
19
             'discount_invalid' => 'This code is not valid.',
20
             'discount_invalid' => 'This code is not valid.',
20
             'discount_not_started' => 'This code cannot be used yet.',
21
             'discount_not_started' => 'This code cannot be used yet.',
21
             'discount_expired' => 'This code has expired.',
22
             'discount_expired' => 'This code has expired.',
36
             'sold_out' => 'Produk ini telah habis dijual.',
37
             'sold_out' => 'Produk ini telah habis dijual.',
37
             'choose_option' => 'Sila pilih satu pilihan dahulu.',
38
             'choose_option' => 'Sila pilih satu pilihan dahulu.',
38
             'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',
39
             'payment_unavailable' => 'Kami tidak dapat memulakan pembayaran. Sila cuba sebentar lagi.',
40
+            'not_taking_orders' => 'Kedai ini belum menerima pesanan. Sila datang semula nanti.',
39
             'discount_invalid' => 'Kod ini tidak sah.',
41
             'discount_invalid' => 'Kod ini tidak sah.',
40
             'discount_not_started' => 'Kod ini belum boleh digunakan.',
42
             'discount_not_started' => 'Kod ini belum boleh digunakan.',
41
             'discount_expired' => 'Kod ini telah tamat tempoh.',
43
             'discount_expired' => 'Kod ini telah tamat tempoh.',

+ 1
- 1
bootstrap/app.php 파일 보기

18
         $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
18
         $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
19
 
19
 
20
         // Stripe cannot send our form-protection token. Its messages are checked by signature instead.
20
         // Stripe cannot send our form-protection token. Its messages are checked by signature instead.
21
-        $middleware->validateCsrfTokens(except: ['stripe/webhook']);
21
+        $middleware->validateCsrfTokens(except: ['stripe/webhook', 'stripe/connect-webhook']);
22
 
22
 
23
         $middleware->web(append: [
23
         $middleware->web(append: [
24
             HandleAppearance::class,
24
             HandleAppearance::class,

+ 1
- 1
config/legal.php 파일 보기

25
     'address' => env('LEGAL_ADDRESS') ?: null,
25
     'address' => env('LEGAL_ADDRESS') ?: null,
26
 
26
 
27
     // Change this date whenever the wording of either page changes.
27
     // Change this date whenever the wording of either page changes.
28
-    'updated' => '2026-11-22',
28
+    'updated' => '2026-11-30',
29
 
29
 
30
     /*
30
     /*
31
      * The company behind each AI provider in config/ai.php, and where it is based. The pages name the
31
      * The company behind each AI provider in config/ai.php, and where it is based. The pages name the

+ 2
- 0
config/services.php 파일 보기

42
         'secret' => env('STRIPE_SECRET'),
42
         'secret' => env('STRIPE_SECRET'),
43
         // Signing secret for the webhook (whsec_...). Optional on a local machine.
43
         // Signing secret for the webhook (whsec_...). Optional on a local machine.
44
         'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
44
         'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
45
+        // Signing secret for the second webhook, which hears about payments on merchants' own Stripe accounts.
46
+        'connect_webhook_secret' => env('STRIPE_CONNECT_WEBHOOK_SECRET'),
45
     ],
47
     ],
46
 
48
 
47
     'easyparcel' => [
49
     'easyparcel' => [

+ 39
- 0
database/migrations/2026_11_30_000001_add_stripe_connect.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
+    public function up(): void
10
+    {
11
+        // The merchant's own Stripe account for each store. Shopper payments go straight into it.
12
+        Schema::create('stripe_accounts', function (Blueprint $table) {
13
+            $table->id();
14
+            $table->foreignId('store_id')->unique()->constrained()->cascadeOnDelete();
15
+            $table->string('account_id')->unique();
16
+            // Copies of what Stripe says, refreshed now and then. Stripe is the source of truth.
17
+            $table->boolean('charges_enabled')->default(false);
18
+            $table->boolean('payouts_enabled')->default(false);
19
+            $table->boolean('details_submitted')->default(false);
20
+            $table->boolean('fpx_requested')->default(false);
21
+            $table->timestamp('checked_at')->nullable();
22
+            $table->timestamps();
23
+        });
24
+
25
+        Schema::table('orders', function (Blueprint $table) {
26
+            // The Stripe account the order was paid into. Null for orders paid into our own account.
27
+            $table->string('payment_account')->nullable()->after('payment_checkout_id');
28
+        });
29
+    }
30
+
31
+    public function down(): void
32
+    {
33
+        Schema::table('orders', function (Blueprint $table) {
34
+            $table->dropColumn('payment_account');
35
+        });
36
+
37
+        Schema::dropIfExists('stripe_accounts');
38
+    }
39
+};

+ 23
- 0
database/migrations/2026_11_30_000002_add_contact_email_to_stores.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
+    public function up(): void
10
+    {
11
+        Schema::table('stores', function (Blueprint $table) {
12
+            // Where shoppers' replies to the store's emails go. Shown to shoppers, so it is the merchant's choice.
13
+            $table->string('contact_email')->nullable()->after('whatsapp_number');
14
+        });
15
+    }
16
+
17
+    public function down(): void
18
+    {
19
+        Schema::table('stores', function (Blueprint $table) {
20
+            $table->dropColumn('contact_email');
21
+        });
22
+    }
23
+};

+ 5
- 0
resources/js/components/overview/format.ts 파일 보기

2
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
2
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
3
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
3
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
4
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5
+import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
5
 
6
 
6
 /** "RM 12,480" or, with cents, "RM 87.90". */
7
 /** "RM 12,480" or, with cents, "RM 87.90". */
7
 export function ringgit(amount: number, cents = false): string {
8
 export function ringgit(amount: number, cents = false): string {
79
         return ProductController.index.url(storeSlug);
80
         return ProductController.index.url(storeSlug);
80
     }
81
     }
81
 
82
 
83
+    if (kind === 'payments') {
84
+        return `${StoreSettingsController.edit.url(storeSlug)}#payments`;
85
+    }
86
+
82
     return StoreController.show.url(storeSlug);
87
     return StoreController.show.url(storeSlug);
83
 }
88
 }
84
 
89
 

+ 17
- 1
resources/js/components/overview/sections.tsx 파일 보기

8
     Store as StoreIcon,
8
     Store as StoreIcon,
9
     Truck,
9
     Truck,
10
     UploadCloud,
10
     UploadCloud,
11
+    Wallet,
11
 } from 'lucide-react';
12
 } from 'lucide-react';
12
 import type { ReactNode } from 'react';
13
 import type { ReactNode } from 'react';
13
 import { useEffect, useState } from 'react';
14
 import { useEffect, useState } from 'react';
14
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
15
 import OrderController from '@/actions/App/Http/Controllers/OrderController';
15
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
16
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
16
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
17
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
18
+import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
17
 import { actionHref, ringgit, when } from '@/components/overview/format';
19
 import { actionHref, ringgit, when } from '@/components/overview/format';
18
 import { cn } from '@/lib/utils';
20
 import { cn } from '@/lib/utils';
19
 import { create } from '@/routes/stores';
21
 import { create } from '@/routes/stores';
65
     ({
67
     ({
66
         ship: Truck,
68
         ship: Truck,
67
         restock: item.title.includes('out of stock') ? PackageX : AlertTriangle,
69
         restock: item.title.includes('out of stock') ? PackageX : AlertTriangle,
70
+        payments: Wallet,
68
         publish: UploadCloud,
71
         publish: UploadCloud,
69
         plan: CreditCard,
72
         plan: CreditCard,
70
     })[item.kind];
73
     })[item.kind];
72
 const attentionButton = {
75
 const attentionButton = {
73
     ship: 'Ship',
76
     ship: 'Ship',
74
     restock: 'Restock',
77
     restock: 'Restock',
78
+    payments: 'Connect',
75
     publish: 'Open',
79
     publish: 'Open',
76
     plan: 'Choose plan',
80
     plan: 'Choose plan',
77
 };
81
 };
394
     );
398
     );
395
 }
399
 }
396
 
400
 
397
-/** Until the first sale: the four steps to get there, each with a button. */
401
+/** Until the first sale: the five steps to get there, each with a button. */
398
 export function GettingStartedCard({ data }: { data: GettingStarted }) {
402
 export function GettingStartedCard({ data }: { data: GettingStarted }) {
399
     const slug = data.store?.slug;
403
     const slug = data.store?.slug;
400
     const steps = [
404
     const steps = [
431
                   }
435
                   }
432
                 : null,
436
                 : null,
433
         },
437
         },
438
+        {
439
+            key: 'payments',
440
+            title: 'Connect Stripe to get paid',
441
+            note: 'Payments go straight to your bank.',
442
+            done: data.steps.payments,
443
+            action: slug
444
+                ? {
445
+                      label: 'Connect Stripe',
446
+                      href: `${StoreSettingsController.edit.url(slug)}#payments`,
447
+                  }
448
+                : null,
449
+        },
434
         {
450
         {
435
             key: 'publish',
451
             key: 'publish',
436
             title: 'Publish your store',
452
             title: 'Publish your store',

+ 205
- 0
resources/js/components/stores/get-paid-setup.tsx 파일 보기

1
+import { router } from '@inertiajs/react';
2
+import { AlertTriangle, Check, Clock, ExternalLink, Link2 } from 'lucide-react';
3
+import { useState } from 'react';
4
+import StripeConnectController from '@/actions/App/Http/Controllers/StripeConnectController';
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 { Spinner } from '@/components/ui/spinner';
15
+import type { StoreSummary } from '@/types';
16
+
17
+export type PaymentSettings = {
18
+    /** False until the app's own Stripe key is set. */
19
+    available: boolean;
20
+    /** A Stripe account was opened for the store (the form may not be finished). */
21
+    connected: boolean;
22
+    details_submitted: boolean;
23
+    can_take_payments: boolean;
24
+    payouts_enabled: boolean;
25
+};
26
+
27
+const STRIPE_DASHBOARD_URL = 'https://dashboard.stripe.com';
28
+
29
+/**
30
+ * Getting paid: the store's own Stripe account, where shoppers' payments go.
31
+ * It sits inside the Settings form, so its buttons never submit that form.
32
+ */
33
+export function GetPaidSetup({
34
+    store,
35
+    payments,
36
+}: {
37
+    store: StoreSummary;
38
+    payments: PaymentSettings;
39
+}) {
40
+    const [busy, setBusy] = useState(false);
41
+
42
+    const openStripe = () => {
43
+        setBusy(true);
44
+        // Stripe's own sign-up form opens in this tab, then brings the merchant back here.
45
+        router.post(
46
+            StripeConnectController.connect.url(store.slug),
47
+            {},
48
+            { onFinish: () => setBusy(false) },
49
+        );
50
+    };
51
+
52
+    const stripeButton = (label: string, variant: 'default' | 'outline') => (
53
+        <Button
54
+            type="button"
55
+            variant={variant}
56
+            onClick={openStripe}
57
+            disabled={busy}
58
+            data-test="stripe-connect"
59
+        >
60
+            {busy ? <Spinner /> : <Link2 />}
61
+            {label}
62
+        </Button>
63
+    );
64
+
65
+    return (
66
+        <Card id="payments" data-test="get-paid">
67
+            <CardHeader>
68
+                <CardTitle className="flex flex-wrap items-center gap-2">
69
+                    Get paid
70
+                    {payments.can_take_payments && (
71
+                        <Badge className="bg-emerald-600 text-white hover:bg-emerald-600">
72
+                            <Check className="size-3" />
73
+                            Connected
74
+                        </Badge>
75
+                    )}
76
+                </CardTitle>
77
+                <CardDescription>
78
+                    Shoppers pay into your own Stripe account, and Stripe pays
79
+                    it into your bank. We take no cut. You only pay Stripe’s
80
+                    fees.
81
+                </CardDescription>
82
+            </CardHeader>
83
+            <CardContent>
84
+                {!payments.available ? (
85
+                    <p
86
+                        className="rounded-md bg-muted p-3 text-xs"
87
+                        data-test="stripe-unavailable"
88
+                    >
89
+                        Stripe is not switched on for this app yet. The app
90
+                        owner adds STRIPE_SECRET to .env.local.
91
+                    </p>
92
+                ) : payments.can_take_payments ? (
93
+                    <div className="space-y-4">
94
+                        <ul className="space-y-2 rounded-lg border p-4 text-sm">
95
+                            <li className="flex items-center gap-2">
96
+                                <Check className="size-4 text-emerald-600" />
97
+                                Your store can take payments
98
+                            </li>
99
+                            <li
100
+                                className="flex items-center gap-2"
101
+                                data-test="payouts-status"
102
+                            >
103
+                                {payments.payouts_enabled ? (
104
+                                    <>
105
+                                        <Check className="size-4 text-emerald-600" />
106
+                                        Payouts to your bank are on
107
+                                    </>
108
+                                ) : (
109
+                                    <>
110
+                                        <AlertTriangle className="size-4 text-amber-600" />
111
+                                        Payouts are paused: Stripe needs a few
112
+                                        more details
113
+                                    </>
114
+                                )}
115
+                            </li>
116
+                        </ul>
117
+                        <div className="flex flex-wrap gap-2">
118
+                            <Button type="button" variant="outline" asChild>
119
+                                <a
120
+                                    href={STRIPE_DASHBOARD_URL}
121
+                                    target="_blank"
122
+                                    rel="noreferrer"
123
+                                >
124
+                                    <ExternalLink />
125
+                                    Open Stripe Dashboard
126
+                                </a>
127
+                            </Button>
128
+                            {!payments.payouts_enabled &&
129
+                                stripeButton('Update details', 'default')}
130
+                        </div>
131
+                        <p className="text-xs text-muted-foreground">
132
+                            Refunds, payouts and payment methods (such as FPX)
133
+                            are managed in your Stripe Dashboard.
134
+                        </p>
135
+                    </div>
136
+                ) : payments.details_submitted ? (
137
+                    <div className="space-y-4">
138
+                        <p
139
+                            className="flex items-start gap-2 text-sm"
140
+                            data-test="stripe-checking"
141
+                        >
142
+                            <Clock className="mt-0.5 size-4 shrink-0 text-amber-600" />
143
+                            Thank you. Stripe is checking your details. This
144
+                            usually takes a few minutes, sometimes a day. Your
145
+                            store takes orders as soon as Stripe says yes.
146
+                        </p>
147
+                        <div className="flex flex-wrap gap-2">
148
+                            <Button
149
+                                type="button"
150
+                                variant="outline"
151
+                                onClick={() =>
152
+                                    router.reload({ only: ['payments'] })
153
+                                }
154
+                            >
155
+                                Check again
156
+                            </Button>
157
+                            {stripeButton('Update details', 'outline')}
158
+                        </div>
159
+                    </div>
160
+                ) : payments.connected ? (
161
+                    <div className="space-y-4">
162
+                        <p
163
+                            className="flex items-start gap-2 text-sm text-amber-700 dark:text-amber-400"
164
+                            data-test="stripe-unfinished"
165
+                        >
166
+                            <AlertTriangle className="mt-0.5 size-4 shrink-0" />
167
+                            Your Stripe sign-up is not finished. Your store
168
+                            cannot take orders until it is.
169
+                        </p>
170
+                        {stripeButton('Finish setup', 'default')}
171
+                    </div>
172
+                ) : (
173
+                    <div className="space-y-4 text-sm">
174
+                        <p
175
+                            className="flex items-start gap-2 text-amber-700 dark:text-amber-400"
176
+                            data-test="stripe-not-connected"
177
+                        >
178
+                            <AlertTriangle className="mt-0.5 size-4 shrink-0" />
179
+                            Your store cannot take orders until you connect
180
+                            Stripe.
181
+                        </p>
182
+                        <div className="text-muted-foreground">
183
+                            <p className="font-medium text-foreground">
184
+                                Have these ready (about 10 minutes):
185
+                            </p>
186
+                            <ul className="mt-1 list-disc space-y-1 pl-5">
187
+                                <li>Your IC or passport</li>
188
+                                <li>
189
+                                    Your SSM registration number, if you have
190
+                                    one (needed for FPX online banking)
191
+                                </li>
192
+                                <li>The bank account to receive your money</li>
193
+                            </ul>
194
+                        </div>
195
+                        <p className="text-muted-foreground">
196
+                            You fill these in on Stripe’s own page, not ours.
197
+                            Already use Stripe? You can sign in there.
198
+                        </p>
199
+                        {stripeButton('Connect Stripe', 'default')}
200
+                    </div>
201
+                )}
202
+            </CardContent>
203
+        </Card>
204
+    );
205
+}

+ 3
- 2
resources/js/pages/legal/privacy.tsx 파일 보기

168
                     <List
168
                     <List
169
                         items={[
169
                         items={[
170
                             <>
170
                             <>
171
-                                <strong>Stripe</strong>, for payments from
172
-                                shoppers and for merchants’ plans.
171
+                                <strong>Stripe</strong>, for merchants’ plans,
172
+                                and for shoppers’ payments, which go to the
173
+                                merchant’s own Stripe account.
173
                             </>,
174
                             </>,
174
                             <>
175
                             <>
175
                                 <strong>Our AI companies</strong>, as explained
176
                                 <strong>Our AI companies</strong>, as explained

+ 14
- 2
resources/js/pages/legal/terms.tsx 파일 보기

90
                         ]}
90
                         ]}
91
                     />
91
                     />
92
                     <p>
92
                     <p>
93
-                        Shoppers pay through Stripe. To receive payments you may
94
-                        need to accept Stripe’s own terms.
93
+                        Shoppers pay straight into your own Stripe account,
94
+                        which you connect in your store’s Settings. Your store
95
+                        cannot take orders until you do. Stripe pays the money
96
+                        into your bank account. We never hold your money and we
97
+                        take no cut of your sales; you pay only Stripe’s own
98
+                        fees.
99
+                    </p>
100
+                    <p>
101
+                        Your Stripe account is between you and Stripe, under
102
+                        Stripe’s own terms (the Stripe Connected Account
103
+                        Agreement). Stripe checks your identity and business,
104
+                        and decides which payment methods you can use. Refunds,
105
+                        chargebacks and payouts are handled in your Stripe
106
+                        account, and are your responsibility as the seller.
95
                     </p>
107
                     </p>
96
                 </>
108
                 </>
97
             ),
109
             ),

+ 90
- 29
resources/js/pages/stores/settings.tsx 파일 보기

1
 import { Form, Head } from '@inertiajs/react';
1
 import { Form, Head } from '@inertiajs/react';
2
+import { useState } from 'react';
2
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
3
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
3
 import { BackButton } from '@/components/back-button';
4
 import { BackButton } from '@/components/back-button';
4
 import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
5
 import StoreSettingsController from '@/actions/App/Http/Controllers/StoreSettingsController';
5
 import InputError from '@/components/input-error';
6
 import InputError from '@/components/input-error';
6
 import type { EasyParcelSettings } from '@/components/stores/easyparcel-setup';
7
 import type { EasyParcelSettings } from '@/components/stores/easyparcel-setup';
7
 import { EasyParcelSetup } from '@/components/stores/easyparcel-setup';
8
 import { EasyParcelSetup } from '@/components/stores/easyparcel-setup';
9
+import type { PaymentSettings } from '@/components/stores/get-paid-setup';
10
+import { GetPaidSetup } from '@/components/stores/get-paid-setup';
8
 import StoreNav from '@/components/stores/store-nav';
11
 import StoreNav from '@/components/stores/store-nav';
9
 import { Button } from '@/components/ui/button';
12
 import { Button } from '@/components/ui/button';
10
 import { Checkbox } from '@/components/ui/checkbox';
13
 import { Checkbox } from '@/components/ui/checkbox';
22
 
25
 
23
 type Settings = {
26
 type Settings = {
24
     whatsapp_number: string | null;
27
     whatsapp_number: string | null;
28
+    contact_email: string | null;
25
     shipping_west: string;
29
     shipping_west: string;
26
     shipping_east: string;
30
     shipping_east: string;
27
     free_shipping_over: string | null;
31
     free_shipping_over: string | null;
48
     settings,
52
     settings,
49
     automaticAnnouncements,
53
     automaticAnnouncements,
50
     states,
54
     states,
55
+    accountEmail,
56
+    payments,
51
     easyparcel,
57
     easyparcel,
52
     easyparcelBalance,
58
     easyparcelBalance,
53
 }: {
59
 }: {
55
     settings: Settings;
61
     settings: Settings;
56
     automaticAnnouncements: string[];
62
     automaticAnnouncements: string[];
57
     states: string[];
63
     states: string[];
64
+    /** The merchant's sign-in email, offered as a quick fill for the contact email. */
65
+    accountEmail: string;
66
+    payments: PaymentSettings;
58
     easyparcel: EasyParcelSettings;
67
     easyparcel: EasyParcelSettings;
59
     /** Loaded after the page shows. Null when EasyParcel is not connected. */
68
     /** Loaded after the page shows. Null when EasyParcel is not connected. */
60
     easyparcelBalance?: { amount: number | null; error: string | null } | null;
69
     easyparcelBalance?: { amount: number | null; error: string | null } | null;
80
                 >
89
                 >
81
                     {({ processing, errors }) => (
90
                     {({ processing, errors }) => (
82
                         <>
91
                         <>
83
-                            <Card>
84
-                                <CardHeader>
85
-                                    <CardTitle>WhatsApp</CardTitle>
86
-                                    <CardDescription>
87
-                                        Shoppers see a WhatsApp chat button on
88
-                                        every page of your store, and on their
89
-                                        order page. Leave empty to hide it.
90
-                                    </CardDescription>
91
-                                </CardHeader>
92
-                                <CardContent className="grid gap-2">
93
-                                    <Label htmlFor="whatsapp_number">
94
-                                        WhatsApp number
95
-                                    </Label>
96
-                                    <Input
97
-                                        id="whatsapp_number"
98
-                                        name="whatsapp_number"
99
-                                        type="tel"
100
-                                        inputMode="tel"
101
-                                        maxLength={30}
102
-                                        defaultValue={
103
-                                            settings.whatsapp_number ?? ''
104
-                                        }
105
-                                        placeholder="012-345 6789"
106
-                                    />
107
-                                    <InputError
108
-                                        message={errors.whatsapp_number}
109
-                                    />
110
-                                </CardContent>
111
-                            </Card>
92
+                            <GetPaidSetup store={store} payments={payments} />
93
+
94
+                            <ContactCard
95
+                                settings={settings}
96
+                                accountEmail={accountEmail}
97
+                                errors={errors}
98
+                            />
112
 
99
 
113
                             <Card>
100
                             <Card>
114
                                 <CardHeader>
101
                                 <CardHeader>
464
         { title: 'Settings', href: '#' },
451
         { title: 'Settings', href: '#' },
465
     ],
452
     ],
466
 };
453
 };
454
+
455
+/**
456
+ * How shoppers reach the store: the WhatsApp button and the email address their replies go to.
457
+ */
458
+function ContactCard({
459
+    settings,
460
+    accountEmail,
461
+    errors,
462
+}: {
463
+    settings: Settings;
464
+    accountEmail: string;
465
+    errors: Record<string, string | undefined>;
466
+}) {
467
+    const [email, setEmail] = useState(settings.contact_email ?? '');
468
+
469
+    return (
470
+        <Card id="contact">
471
+            <CardHeader>
472
+                <CardTitle>How shoppers reach you</CardTitle>
473
+                <CardDescription>
474
+                    How shoppers contact you about their orders.
475
+                </CardDescription>
476
+            </CardHeader>
477
+            <CardContent className="space-y-5">
478
+                <div className="grid gap-2">
479
+                    <Label htmlFor="whatsapp_number">WhatsApp number</Label>
480
+                    <Input
481
+                        id="whatsapp_number"
482
+                        name="whatsapp_number"
483
+                        type="tel"
484
+                        inputMode="tel"
485
+                        maxLength={30}
486
+                        defaultValue={settings.whatsapp_number ?? ''}
487
+                        placeholder="012-345 6789"
488
+                    />
489
+                    <p className="text-xs text-muted-foreground">
490
+                        Adds a WhatsApp chat button to every page, the order
491
+                        page and the order emails. Leave empty to hide it.
492
+                    </p>
493
+                    <InputError message={errors.whatsapp_number} />
494
+                </div>
495
+
496
+                <div className="grid gap-2">
497
+                    <Label htmlFor="contact_email">Email for shoppers</Label>
498
+                    <Input
499
+                        id="contact_email"
500
+                        name="contact_email"
501
+                        type="email"
502
+                        maxLength={160}
503
+                        value={email}
504
+                        onChange={(event) => setEmail(event.target.value)}
505
+                        placeholder="hello@yourstore.com"
506
+                    />
507
+                    <p className="text-xs text-muted-foreground">
508
+                        When a shopper replies to an order email, it comes here.
509
+                        It is also shown at the bottom of those emails. Leave
510
+                        empty and shoppers cannot reply by email.
511
+                    </p>
512
+                    {email === '' && accountEmail !== '' && (
513
+                        <button
514
+                            type="button"
515
+                            onClick={() => setEmail(accountEmail)}
516
+                            className="w-fit text-xs font-medium text-foreground underline underline-offset-2"
517
+                            data-test="use-account-email"
518
+                        >
519
+                            Use {accountEmail}
520
+                        </button>
521
+                    )}
522
+                    <InputError message={errors.contact_email} />
523
+                </div>
524
+            </CardContent>
525
+        </Card>
526
+    );
527
+}

+ 12
- 1
resources/js/storefront/pages/checkout.tsx 파일 보기

38
 export function CheckoutPage({
38
 export function CheckoutPage({
39
     states,
39
     states,
40
     shippingByState,
40
     shippingByState,
41
+    takingOrders,
41
 }: {
42
 }: {
42
     states: string[];
43
     states: string[];
43
     shippingByState: Record<string, number>;
44
     shippingByState: Record<string, number>;
45
+    takingOrders: boolean;
44
 }) {
46
 }) {
45
     const { cart, language, baseUrl } = useStorefront();
47
     const { cart, language, baseUrl } = useStorefront();
46
     const t = storefrontText(language);
48
     const t = storefrontText(language);
105
 
107
 
106
                 <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_360px] lg:gap-14">
108
                 <div className="mt-10 grid gap-10 lg:grid-cols-[1fr_360px] lg:gap-14">
107
                     <form onSubmit={submit} className="space-y-10" noValidate>
109
                     <form onSubmit={submit} className="space-y-10" noValidate>
110
+                        {!takingOrders && !errors.cart && (
111
+                            <p
112
+                                role="status"
113
+                                data-test="not-taking-orders"
114
+                                className="rounded-(--sf-radius-card) border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900"
115
+                            >
116
+                                {t.notTakingOrders}
117
+                            </p>
118
+                        )}
108
                         {errors.cart && (
119
                         {errors.cart && (
109
                             <p
120
                             <p
110
                                 role="alert"
121
                                 role="alert"
196
                         <div>
207
                         <div>
197
                             <button
208
                             <button
198
                                 type="submit"
209
                                 type="submit"
199
-                                disabled={form.processing}
210
+                                disabled={form.processing || !takingOrders}
200
                                 className="sf-btn-primary inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
211
                                 className="sf-btn-primary inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
201
                             >
212
                             >
202
                                 {t.payNow}
213
                                 {t.payNow}

+ 1
- 0
resources/js/storefront/renderer.tsx 파일 보기

94
             <CheckoutPage
94
             <CheckoutPage
95
                 states={view.states}
95
                 states={view.states}
96
                 shippingByState={view.shippingByState}
96
                 shippingByState={view.shippingByState}
97
+                takingOrders={view.takingOrders}
97
             />
98
             />
98
         );
99
         );
99
     }
100
     }

+ 4
- 0
resources/js/storefront/text.ts 파일 보기

73
         total: 'Total',
73
         total: 'Total',
74
         payNow: 'Continue to payment',
74
         payNow: 'Continue to payment',
75
         paySecure: 'You will pay on a secure Stripe page.',
75
         paySecure: 'You will pay on a secure Stripe page.',
76
+        notTakingOrders:
77
+            'This store is not taking orders yet. Please check back soon.',
76
         backToCart: 'Back to cart',
78
         backToCart: 'Back to cart',
77
         thankYou: 'Thank you for your order',
79
         thankYou: 'Thank you for your order',
78
         orderPaid: (number: number, email: string) =>
80
         orderPaid: (number: number, email: string) =>
182
         total: 'Jumlah',
184
         total: 'Jumlah',
183
         payNow: 'Teruskan ke pembayaran',
185
         payNow: 'Teruskan ke pembayaran',
184
         paySecure: 'Anda akan membayar di halaman Stripe yang selamat.',
186
         paySecure: 'Anda akan membayar di halaman Stripe yang selamat.',
187
+        notTakingOrders:
188
+            'Kedai ini belum menerima pesanan. Sila datang semula nanti.',
185
         backToCart: 'Kembali ke troli',
189
         backToCart: 'Kembali ke troli',
186
         thankYou: 'Terima kasih atas pesanan anda',
190
         thankYou: 'Terima kasih atas pesanan anda',
187
         orderPaid: (number: number, email: string) =>
191
         orderPaid: (number: number, email: string) =>

+ 2
- 0
resources/js/storefront/types.ts 파일 보기

389
           states: string[];
389
           states: string[];
390
           /** Shipping fee in ringgit for each state. */
390
           /** Shipping fee in ringgit for each state. */
391
           shippingByState: Record<string, number>;
391
           shippingByState: Record<string, number>;
392
+          /** False until the merchant has connected Stripe, so shoppers cannot pay yet. */
393
+          takingOrders: boolean;
392
       }
394
       }
393
     | { type: 'order'; order: StoreOrder }
395
     | { type: 'order'; order: StoreOrder }
394
     | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }
396
     | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }

+ 2
- 1
resources/js/types/overview.ts 파일 보기

5
 
5
 
6
 /** One thing in "Needs attention", most urgent first. */
6
 /** One thing in "Needs attention", most urgent first. */
7
 export type AttentionItem = {
7
 export type AttentionItem = {
8
-    kind: 'ship' | 'restock' | 'publish' | 'plan';
8
+    kind: 'ship' | 'restock' | 'payments' | 'publish' | 'plan';
9
     tone: 'warning' | 'danger' | 'brand';
9
     tone: 'warning' | 'danger' | 'brand';
10
     title: string;
10
     title: string;
11
     note: string;
11
     note: string;
84
         create: boolean;
84
         create: boolean;
85
         design: boolean;
85
         design: boolean;
86
         products: boolean;
86
         products: boolean;
87
+        payments: boolean;
87
         publish: boolean;
88
         publish: boolean;
88
     };
89
     };
89
 };
90
 };

+ 5
- 0
resources/views/components/mail/store-button.blade.php 파일 보기

1
+@props(['brand', 'href', 'outline' => false])
2
+{{-- A button that works in every email app: a link styled as a button. --}}
3
+<a href="{{ $href }}" class="sf-button" target="_blank" style="display: inline-block; padding: 13px 24px; border-radius: {{ $brand->buttonRadius }}px; font-family: {{ $brand->bodyFont }}; font-size: 15px; font-weight: 600; line-height: 1.2; text-align: center; text-decoration: none; white-space: nowrap; {{ $outline
4
+    ? 'background-color: transparent; color: '.$brand->color('foreground').'; border: 1px solid '.$brand->color('border').';'
5
+    : 'background-color: '.$brand->color('primary').'; color: '.$brand->color('primaryForeground').'; border: 1px solid '.$brand->color('primary').';' }}">{{ $slot }}</a>

+ 61
- 0
resources/views/components/mail/store.blade.php 파일 보기

1
+@props(['brand', 'preheader' => ''])
2
+{{--
3
+    The frame of every email a store sends its shoppers, in the store's own colours, fonts and corners.
4
+    Tables and inline styles only, because many email apps ignore anything else.
5
+--}}
6
+<!DOCTYPE html>
7
+<html lang="{{ $brand->malay ? 'ms' : 'en' }}">
8
+<head>
9
+<meta charset="utf-8">
10
+<meta name="viewport" content="width=device-width, initial-scale=1">
11
+<meta name="color-scheme" content="light">
12
+<meta name="supported-color-schemes" content="light">
13
+<title>{{ $brand->name }}</title>
14
+<style>
15
+    @media only screen and (max-width: 600px) {
16
+        .sf-card { padding: 24px 20px !important; }
17
+        .sf-cell { display: block !important; width: 100% !important; }
18
+        .sf-button { display: block !important; box-sizing: border-box; }
19
+        .sf-gap { display: block !important; height: 10px !important; width: auto !important; }
20
+    }
21
+</style>
22
+</head>
23
+<body style="margin: 0; padding: 0; background-color: {{ $brand->color('background') }}; -webkit-text-size-adjust: 100%;">
24
+{{-- The short line inboxes show next to the subject. Hidden in the email itself. --}}
25
+<div style="display: none; max-height: 0; overflow: hidden; opacity: 0; color: transparent;">{{ $preheader }}</div>
26
+
27
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: {{ $brand->color('background') }};">
28
+    <tr>
29
+        <td align="center" style="padding: 32px 12px;">
30
+            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width: 560px;">
31
+                {{-- Store name --}}
32
+                <tr>
33
+                    <td align="center" style="padding: 0 0 24px;">
34
+                        <a href="{{ $brand->storeUrl() }}" style="font-family: {{ $brand->headingFont }}; font-size: 24px; font-weight: 700; letter-spacing: -0.01em; color: {{ $brand->color('foreground') }}; text-decoration: none;">{{ $brand->name }}</a>
35
+                    </td>
36
+                </tr>
37
+
38
+                {{-- The message --}}
39
+                <tr>
40
+                    <td class="sf-card" style="background-color: {{ $brand->color('surface') }}; border: 1px solid {{ $brand->color('border') }}; border-top: 4px solid {{ $brand->color('primary') }}; border-radius: {{ $brand->radius }}px; padding: 36px 36px; font-family: {{ $brand->bodyFont }}; font-size: 15px; line-height: 1.6; color: {{ $brand->color('foreground') }};">
41
+                        {{ $slot }}
42
+                    </td>
43
+                </tr>
44
+
45
+                {{-- Footer --}}
46
+                <tr>
47
+                    <td align="center" style="padding: 24px 16px 0; font-family: {{ $brand->bodyFont }}; font-size: 12px; line-height: 1.6; color: {{ $brand->color('muted') }};">
48
+                        @if ($brand->contactEmail())
49
+                            {{ $brand->malay ? 'Ada soalan? Balas e-mel ini atau tulis kepada' : 'Questions? Reply to this email or write to' }}
50
+                            <a href="mailto:{{ $brand->contactEmail() }}" style="color: {{ $brand->color('foreground') }}; text-decoration: underline;">{{ $brand->contactEmail() }}</a>.<br>
51
+                        @endif
52
+                        {{ $brand->malay ? 'Anda menerima e-mel ini kerana anda membuat pesanan di' : 'You are getting this email because you ordered from' }}
53
+                        <a href="{{ $brand->storeUrl() }}" style="color: {{ $brand->color('muted') }}; text-decoration: underline;">{{ $brand->name }}</a>{{ str_ends_with($brand->name, '.') ? '' : '.' }}
54
+                    </td>
55
+                </tr>
56
+            </table>
57
+        </td>
58
+    </tr>
59
+</table>
60
+</body>
61
+</html>

+ 35
- 0
resources/views/mail/orders/confirmation-text.blade.php 파일 보기

1
+@php($m = $brand->malay)
2
+{!! $m ? 'Terima kasih atas pesanan anda' : 'Thank you for your order' !!}
3
+
4
+{!! $m ? 'Hai' : 'Hi' !!} {!! $order->customer_name !!},
5
+
6
+{!! $m ? "Kami telah menerima bayaran anda. Ini ringkasan pesanan #{$order->number} daripada ".rtrim($store->name, '.')."." : "We have received your payment. Here is a summary of order #{$order->number} from ".rtrim($store->name, '.')."." !!}
7
+
8
+@foreach ($order->items as $item)
9
+- {!! $item->name !!} × {!! $item->quantity !!}: {!! $brand->money($item->line_total) !!}
10
+@endforeach
11
+
12
+{!! $m ? 'Jumlah kecil' : 'Subtotal' !!}: {!! $brand->money($order->subtotal) !!}
13
+@if ($order->discount_total > 0)
14
+{!! $m ? 'Diskaun' : 'Discount' !!}@if ($order->discount_code ?? $order->discount_name) ({!! $order->discount_code ?? $order->discount_name !!})@endif: -{!! $brand->money($order->discount_total) !!}
15
+@endif
16
+{!! $m ? 'Penghantaran' : 'Shipping' !!}: {!! $order->shipping_total === 0 ? ($m ? 'Percuma' : 'Free') : $brand->money($order->shipping_total) !!}
17
+{!! $m ? 'Jumlah dibayar' : 'Total paid' !!}: {!! $brand->money($order->total) !!}
18
+
19
+{!! $m ? 'Alamat penghantaran' : 'Delivery address' !!}:
20
+{!! $order->customer_name !!}
21
+{!! $order->shipping_address['line1'] !!}@if ($order->shipping_address['line2'] ?? null), {!! $order->shipping_address['line2'] !!}@endif
22
+
23
+{!! $order->shipping_address['postcode'] !!} {!! $order->shipping_address['city'] !!}, {!! $order->shipping_address['state'] !!}
24
+
25
+{!! $m ? 'Lihat pesanan anda' : 'View your order' !!}: {!! $orderUrl !!}
26
+@if ($whatsappUrl)
27
+{!! $m ? 'Tanya di WhatsApp' : 'Ask on WhatsApp' !!}: {!! $whatsappUrl !!}
28
+@endif
29
+
30
+{!! $m ? 'Terima kasih,' : 'Thanks,' !!}
31
+{!! $store->name !!}
32
+@if ($brand->contactEmail())
33
+
34
+{!! $m ? 'Ada soalan? Balas e-mel ini atau tulis kepada' : 'Questions? Reply to this email or write to' !!} {!! $brand->contactEmail() !!}
35
+@endif

+ 84
- 24
resources/views/mail/orders/confirmation.blade.php 파일 보기

1
-<x-mail::message>
2
-# {{ $malay ? 'Terima kasih atas pesanan anda' : 'Thank you for your order' }}
1
+@php
2
+    $m = $brand->malay;
3
+    $label = 'font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: '.$brand->color('muted').';';
4
+    $line = 'border-bottom: 1px solid '.$brand->color('border').';';
5
+    $address = $order->shipping_address;
6
+@endphp
7
+<x-mail.store :brand="$brand" :preheader="$m ? 'Bayaran diterima. Pesanan #'.$order->number.', '.$brand->money($order->total).'.' : 'Payment received. Order #'.$order->number.', '.$brand->money($order->total).'.'">
8
+    <h1 style="margin: 0 0 16px; font-family: {{ $brand->headingFont }}; font-size: 26px; line-height: 1.25; font-weight: 700; color: {{ $brand->color('foreground') }};">
9
+        {{ $m ? 'Terima kasih atas pesanan anda' : 'Thank you for your order' }}
10
+    </h1>
11
+    <p style="margin: 0 0 12px;">{{ $m ? 'Hai' : 'Hi' }} {{ $order->customer_name }},</p>
12
+    <p style="margin: 0 0 24px;">
13
+        {{ $m
14
+            ? "Kami telah menerima bayaran anda. Ini ringkasan pesanan #{$order->number} daripada ".rtrim($store->name, '.')."."
15
+            : "We have received your payment. Here is a summary of order #{$order->number} from ".rtrim($store->name, '.')."." }}
16
+    </p>
3
 
17
 
4
-{{ $malay ? 'Hai' : 'Hi' }} {{ $order->customer_name }},
18
+    {{-- Order number and date --}}
19
+    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 24px;">
20
+        <tr>
21
+            <td style="{{ $label }} padding-bottom: 4px;">{{ $m ? 'Pesanan' : 'Order' }}</td>
22
+            <td align="right" style="{{ $label }} padding-bottom: 4px;">{{ $m ? 'Dibayar pada' : 'Paid on' }}</td>
23
+        </tr>
24
+        <tr>
25
+            <td style="font-weight: 600;">#{{ $order->number }}</td>
26
+            <td align="right" style="font-weight: 600;">{{ ($order->paid_at ?? now())->timezone('Asia/Kuala_Lumpur')->locale($m ? 'ms' : 'en')->translatedFormat('j F Y') }}</td>
27
+        </tr>
28
+    </table>
5
 
29
 
6
-{{ $malay
7
-    ? "Kami telah menerima bayaran anda. Ini ringkasan pesanan #{$order->number} daripada {$store->name}."
8
-    : "We have received your payment. Here is a summary of order #{$order->number} from {$store->name}." }}
30
+    {{-- What was bought --}}
31
+    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-top: 1px solid {{ $brand->color('border') }};">
32
+        @foreach ($order->items as $item)
33
+            <tr>
34
+                <td style="{{ $line }} padding: 12px 12px 12px 0; vertical-align: top;">
35
+                    <div style="font-weight: 600;">{{ $item->name }}</div>
36
+                    <div style="font-size: 13px; color: {{ $brand->color('muted') }};">{{ $item->quantity }} × {{ $brand->money($item->unit_price) }}</div>
37
+                </td>
38
+                <td align="right" style="{{ $line }} padding: 12px 0; vertical-align: top; white-space: nowrap;">{{ $brand->money($item->line_total) }}</td>
39
+            </tr>
40
+        @endforeach
41
+    </table>
9
 
42
 
10
-<x-mail::table>
11
-| {{ $malay ? 'Produk' : 'Item' }} | {{ $malay ? 'Kuantiti' : 'Qty' }} | {{ $malay ? 'Jumlah' : 'Total' }} |
12
-| :--- | :---: | ---: |
13
-@foreach ($order->items as $item)
14
-| {{ $item->name }} | {{ $item->quantity }} | {{ $money($item->line_total) }} |
15
-@endforeach
16
-@if ($order->discount_total > 0)
17
-| {{ $malay ? 'Diskaun' : 'Discount' }}{{ ($order->discount_code ?? $order->discount_name) ? ' ('.($order->discount_code ?? $order->discount_name).')' : '' }} | | -{{ $money($order->discount_total) }} |
18
-@endif
19
-| {{ $malay ? 'Penghantaran' : 'Shipping' }} | | {{ $order->shipping_total === 0 ? ($malay ? 'Percuma' : 'Free') : $money($order->shipping_total) }} |
20
-| **{{ $malay ? 'Jumlah dibayar' : 'Total paid' }}** | | **{{ $money($order->total) }}** |
21
-</x-mail::table>
43
+    {{-- Totals --}}
44
+    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 28px;">
45
+        <tr>
46
+            <td style="padding: 12px 0 4px; color: {{ $brand->color('muted') }};">{{ $m ? 'Jumlah kecil' : 'Subtotal' }}</td>
47
+            <td align="right" style="padding: 12px 0 4px;">{{ $brand->money($order->subtotal) }}</td>
48
+        </tr>
49
+        @if ($order->discount_total > 0)
50
+            <tr>
51
+                <td style="padding: 4px 0; color: {{ $brand->color('muted') }};">
52
+                    {{ $m ? 'Diskaun' : 'Discount' }}@if ($order->discount_code ?? $order->discount_name) ({{ $order->discount_code ?? $order->discount_name }})@endif
53
+                </td>
54
+                <td align="right" style="padding: 4px 0;">-{{ $brand->money($order->discount_total) }}</td>
55
+            </tr>
56
+        @endif
57
+        <tr>
58
+            <td style="padding: 4px 0 12px; color: {{ $brand->color('muted') }}; {{ $line }}">{{ $m ? 'Penghantaran' : 'Shipping' }}</td>
59
+            <td align="right" style="padding: 4px 0 12px; {{ $line }}">{{ $order->shipping_total === 0 ? ($m ? 'Percuma' : 'Free') : $brand->money($order->shipping_total) }}</td>
60
+        </tr>
61
+        <tr>
62
+            <td style="padding: 14px 0 0; font-family: {{ $brand->headingFont }}; font-size: 17px; font-weight: 700;">{{ $m ? 'Jumlah dibayar' : 'Total paid' }}</td>
63
+            <td align="right" style="padding: 14px 0 0; font-family: {{ $brand->headingFont }}; font-size: 17px; font-weight: 700; white-space: nowrap;">{{ $brand->money($order->total) }}</td>
64
+        </tr>
65
+    </table>
22
 
66
 
23
-**{{ $malay ? 'Alamat penghantaran' : 'Delivery address' }}**
67
+    {{-- Where it goes --}}
68
+    <div style="{{ $label }} margin: 0 0 6px;">{{ $m ? 'Alamat penghantaran' : 'Delivery address' }}</div>
69
+    <p style="margin: 0 0 28px;">
70
+        {{ $order->customer_name }}<br>
71
+        {{ $address['line1'] }}@if ($address['line2'] ?? null), {{ $address['line2'] }}@endif<br>
72
+        {{ $address['postcode'] }} {{ $address['city'] }}, {{ $address['state'] }}
73
+    </p>
24
 
74
 
25
-{{ $order->shipping_address['line1'] }}@if ($order->shipping_address['line2']), {{ $order->shipping_address['line2'] }}@endif<br>
26
-{{ $order->shipping_address['postcode'] }} {{ $order->shipping_address['city'] }}, {{ $order->shipping_address['state'] }}
75
+    {{-- Buttons --}}
76
+    <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 28px;">
77
+        <tr>
78
+            <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$orderUrl">{{ $m ? 'Lihat pesanan anda' : 'View your order' }}</x-mail.store-button></td>
79
+            @if ($whatsappUrl)
80
+                <td class="sf-gap" style="width: 10px;"></td>
81
+                <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$whatsappUrl" outline>{{ $m ? 'Tanya di WhatsApp' : 'Ask on WhatsApp' }}</x-mail.store-button></td>
82
+            @endif
83
+        </tr>
84
+    </table>
27
 
85
 
28
-{{ $malay ? 'Terima kasih,' : 'Thanks,' }}<br>
29
-{{ $store->name }}
30
-</x-mail::message>
86
+    <p style="margin: 0 0 20px; color: {{ $brand->color('muted') }};">
87
+        {{ $m ? 'Kami akan e-mel anda lagi apabila pesanan anda dihantar.' : 'We will email you again when your order is on its way.' }}
88
+    </p>
89
+    <p style="margin: 0;">{{ $m ? 'Terima kasih,' : 'Thanks,' }}<br><strong>{{ $store->name }}</strong></p>
90
+</x-mail.store>

+ 35
- 0
resources/views/mail/orders/shipped-text.blade.php 파일 보기

1
+@php($m = $brand->malay)
2
+{!! $m ? 'Pesanan anda dalam perjalanan' : 'Your order is on its way' !!}
3
+
4
+{!! $m ? 'Hai' : 'Hi' !!} {!! $order->customer_name !!},
5
+
6
+{!! $m ? "Pesanan #{$order->number} daripada {$store->name} telah dihantar melalui {$order->shipping_courier}." : "Order #{$order->number} from {$store->name} has been sent with {$order->shipping_courier}." !!}
7
+
8
+@if ($order->tracking_number)
9
+{!! $m ? 'Nombor penjejakan' : 'Tracking number' !!}: {!! $order->tracking_number !!}
10
+@endif
11
+@if ($order->tracking_url)
12
+{!! $m ? 'Jejak bungkusan anda' : 'Track your parcel' !!}: {!! $order->tracking_url !!}
13
+@endif
14
+
15
+@foreach ($order->items as $item)
16
+- {!! $item->name !!} × {!! $item->quantity !!}
17
+@endforeach
18
+
19
+{!! $m ? 'Dihantar ke' : 'Delivering to' !!}:
20
+{!! $order->customer_name !!}
21
+{!! $order->shipping_address['line1'] !!}@if ($order->shipping_address['line2'] ?? null), {!! $order->shipping_address['line2'] !!}@endif
22
+
23
+{!! $order->shipping_address['postcode'] !!} {!! $order->shipping_address['city'] !!}, {!! $order->shipping_address['state'] !!}
24
+
25
+{!! $m ? 'Lihat pesanan anda' : 'View your order' !!}: {!! $orderUrl !!}
26
+@if ($whatsappUrl)
27
+{!! $m ? 'Tanya di WhatsApp' : 'Ask on WhatsApp' !!}: {!! $whatsappUrl !!}
28
+@endif
29
+
30
+{!! $m ? 'Terima kasih,' : 'Thanks,' !!}
31
+{!! $store->name !!}
32
+@if ($brand->contactEmail())
33
+
34
+{!! $m ? 'Ada soalan? Balas e-mel ini atau tulis kepada' : 'Questions? Reply to this email or write to' !!} {!! $brand->contactEmail() !!}
35
+@endif

+ 68
- 26
resources/views/mail/orders/shipped.blade.php 파일 보기

1
-<x-mail::message>
2
-# {{ $malay ? 'Pesanan anda dalam perjalanan' : 'Your order is on its way' }}
1
+@php
2
+    $m = $brand->malay;
3
+    $label = 'font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: '.$brand->color('muted').';';
4
+    $line = 'border-bottom: 1px solid '.$brand->color('border').';';
5
+    $address = $order->shipping_address;
6
+@endphp
7
+<x-mail.store :brand="$brand" :preheader="$m ? 'Pesanan #'.$order->number.' telah dihantar melalui '.$order->shipping_courier.'.' : 'Order #'.$order->number.' was sent with '.$order->shipping_courier.'.'">
8
+    <h1 style="margin: 0 0 16px; font-family: {{ $brand->headingFont }}; font-size: 26px; line-height: 1.25; font-weight: 700; color: {{ $brand->color('foreground') }};">
9
+        {{ $m ? 'Pesanan anda dalam perjalanan' : 'Your order is on its way' }}
10
+    </h1>
11
+    <p style="margin: 0 0 12px;">{{ $m ? 'Hai' : 'Hi' }} {{ $order->customer_name }},</p>
12
+    <p style="margin: 0 0 24px;">
13
+        {{ $m
14
+            ? "Pesanan #{$order->number} daripada {$store->name} telah dihantar melalui {$order->shipping_courier}."
15
+            : "Order #{$order->number} from {$store->name} has been sent with {$order->shipping_courier}." }}
16
+    </p>
3
 
17
 
4
-{{ $malay ? 'Hai' : 'Hi' }} {{ $order->customer_name }},
18
+    @if ($order->tracking_number)
19
+        {{-- The tracking number, easy to copy --}}
20
+        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 24px;">
21
+            <tr>
22
+                <td style="background-color: {{ $brand->color('background') }}; border: 1px solid {{ $brand->color('border') }}; border-radius: {{ $brand->radius }}px; padding: 16px 18px;">
23
+                    <div style="{{ $label }} margin-bottom: 4px;">{{ $m ? 'Nombor penjejakan' : 'Tracking number' }} · {{ $order->shipping_courier }}</div>
24
+                    <div style="font-family: 'Courier New', Courier, monospace; font-size: 18px; font-weight: 700; letter-spacing: 0.04em;">{{ $order->tracking_number }}</div>
25
+                </td>
26
+            </tr>
27
+        </table>
28
+    @endif
5
 
29
 
6
-{{ $malay
7
-    ? "Pesanan #{$order->number} daripada {$store->name} telah dihantar melalui {$order->shipping_courier}."
8
-    : "Order #{$order->number} from {$store->name} has been sent with {$order->shipping_courier}." }}
30
+    {{-- Buttons --}}
31
+    <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 28px;">
32
+        <tr>
33
+            @if ($order->tracking_url)
34
+                <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$order->tracking_url">{{ $m ? 'Jejak bungkusan anda' : 'Track your parcel' }}</x-mail.store-button></td>
35
+                <td class="sf-gap" style="width: 10px;"></td>
36
+                <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$orderUrl" outline>{{ $m ? 'Lihat pesanan anda' : 'View your order' }}</x-mail.store-button></td>
37
+            @else
38
+                <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$orderUrl">{{ $m ? 'Lihat pesanan anda' : 'View your order' }}</x-mail.store-button></td>
39
+            @endif
40
+        </tr>
41
+    </table>
42
+    @if ($order->tracking_number && ! $order->tracking_url)
43
+        <p style="margin: -12px 0 28px; font-size: 13px; color: {{ $brand->color('muted') }};">
44
+            {{ $m ? 'Gunakan nombor penjejakan di laman web kurier untuk menjejak bungkusan anda.' : "Use the tracking number on the courier's website to follow your parcel." }}
45
+        </p>
46
+    @endif
9
 
47
 
10
-@if ($order->tracking_number)
11
-**{{ $malay ? 'Nombor penjejakan' : 'Tracking number' }}:** {{ $order->tracking_number }}
48
+    {{-- What is in the parcel --}}
49
+    <div style="{{ $label }} margin: 0 0 6px;">{{ $m ? 'Dalam bungkusan' : 'In this parcel' }}</div>
50
+    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 24px; border-top: 1px solid {{ $brand->color('border') }};">
51
+        @foreach ($order->items as $item)
52
+            <tr>
53
+                <td style="{{ $line }} padding: 10px 12px 10px 0;">{{ $item->name }}</td>
54
+                <td align="right" style="{{ $line }} padding: 10px 0; white-space: nowrap; color: {{ $brand->color('muted') }};">× {{ $item->quantity }}</td>
55
+            </tr>
56
+        @endforeach
57
+    </table>
12
 
58
 
13
-{{ $malay ? 'Gunakan nombor ini di laman web kurier untuk menjejak bungkusan anda.' : "Use this number on the courier's website to follow your parcel." }}
14
-@endif
59
+    <div style="{{ $label }} margin: 0 0 6px;">{{ $m ? 'Dihantar ke' : 'Delivering to' }}</div>
60
+    <p style="margin: 0 0 28px;">
61
+        {{ $order->customer_name }}<br>
62
+        {{ $address['line1'] }}@if ($address['line2'] ?? null), {{ $address['line2'] }}@endif<br>
63
+        {{ $address['postcode'] }} {{ $address['city'] }}, {{ $address['state'] }}
64
+    </p>
15
 
65
 
16
-<x-mail::table>
17
-| {{ $malay ? 'Produk' : 'Item' }} | {{ $malay ? 'Kuantiti' : 'Qty' }} |
18
-| :--- | :---: |
19
-@foreach ($order->items as $item)
20
-| {{ $item->name }} | {{ $item->quantity }} |
21
-@endforeach
22
-</x-mail::table>
23
-
24
-**{{ $malay ? 'Dihantar ke' : 'Delivering to' }}**
25
-
26
-{{ $order->shipping_address['line1'] }}@if ($order->shipping_address['line2']), {{ $order->shipping_address['line2'] }}@endif<br>
27
-{{ $order->shipping_address['postcode'] }} {{ $order->shipping_address['city'] }}, {{ $order->shipping_address['state'] }}
28
-
29
-{{ $malay ? 'Terima kasih,' : 'Thanks,' }}<br>
30
-{{ $store->name }}
31
-</x-mail::message>
66
+    @if ($whatsappUrl)
67
+        <p style="margin: 0 0 20px; color: {{ $brand->color('muted') }};">
68
+            {{ $m ? 'Ada soalan?' : 'Any questions?' }}
69
+            <a href="{{ $whatsappUrl }}" style="color: {{ $brand->color('foreground') }}; font-weight: 600; text-decoration: underline;">{{ $m ? 'Tanya kami di WhatsApp' : 'Ask us on WhatsApp' }}</a>
70
+        </p>
71
+    @endif
72
+    <p style="margin: 0;">{{ $m ? 'Terima kasih,' : 'Thanks,' }}<br><strong>{{ $store->name }}</strong></p>
73
+</x-mail.store>

+ 8
- 0
routes/web.php 파일 보기

22
 use App\Http\Controllers\StorePublishController;
22
 use App\Http\Controllers\StorePublishController;
23
 use App\Http\Controllers\StoreSettingsController;
23
 use App\Http\Controllers\StoreSettingsController;
24
 use App\Http\Controllers\StoreStyleController;
24
 use App\Http\Controllers\StoreStyleController;
25
+use App\Http\Controllers\StripeConnectController;
26
+use App\Http\Controllers\StripeConnectWebhookController;
25
 use App\Http\Controllers\StripeWebhookController;
27
 use App\Http\Controllers\StripeWebhookController;
26
 use App\Http\Controllers\VideoSectionController;
28
 use App\Http\Controllers\VideoSectionController;
27
 use Illuminate\Support\Facades\Route;
29
 use Illuminate\Support\Facades\Route;
69
 
71
 
70
 // Called by Stripe, not by a browser, so it has no login. Each message is checked with a signing secret.
72
 // Called by Stripe, not by a browser, so it has no login. Each message is checked with a signing secret.
71
 Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
73
 Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
74
+// Payments made in merchants' own Stripe accounts. A second webhook in Stripe, listening to "Connected accounts".
75
+Route::post('stripe/connect-webhook', StripeConnectWebhookController::class)->name('stripe.connect-webhook');
72
 
76
 
73
 Route::middleware(['auth', 'verified'])->group(function () {
77
 Route::middleware(['auth', 'verified'])->group(function () {
74
     Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard');
78
     Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard');
126
     Route::post('stores/{slug}/orders/{order}/label', [OrderController::class, 'refreshLabel'])->middleware('throttle:20,1')->name('stores.orders.label')->whereNumber('order');
130
     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');
131
     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');
132
     Route::delete('stores/{slug}/easyparcel', [EasyParcelController::class, 'disconnect'])->name('stores.easyparcel.disconnect');
133
+    // Getting paid: the merchant's own Stripe account. Stripe sends them back to "return", or to "resume" when its link expired.
134
+    Route::post('stores/{slug}/payments/connect', [StripeConnectController::class, 'connect'])->middleware('throttle:10,1')->name('stores.payments.connect');
135
+    Route::get('stores/{slug}/payments/return', [StripeConnectController::class, 'return'])->name('stores.payments.return');
136
+    Route::get('stores/{slug}/payments/resume', [StripeConnectController::class, 'resume'])->middleware('throttle:10,1')->name('stores.payments.resume');
129
     // EasyParcel sends the merchant back here after they click Allow. One address for every store (the store is kept in the session).
137
     // 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');
138
     Route::get('easyparcel/callback', [EasyParcelController::class, 'callback'])->name('easyparcel.callback');
131
 
139
 

+ 1
- 1
tests/Feature/LegalPagesTest.php 파일 보기

23
                 ->where('operator', 'Mirfalah Sdn Bhd')
23
                 ->where('operator', 'Mirfalah Sdn Bhd')
24
                 ->where('registration', '202601234567')
24
                 ->where('registration', '202601234567')
25
                 ->where('email', 'privacy@example.com')
25
                 ->where('email', 'privacy@example.com')
26
-                ->where('updated', '22 November 2026')
26
+                ->where('updated', '30 November 2026')
27
                 ->has('aiCompanies'));
27
                 ->has('aiCompanies'));
28
     }
28
     }
29
 
29
 

+ 3
- 3
tests/Feature/Malaysia/ShippingTest.php 파일 보기

308
         $order = Order::factory()->for($this->store)->create(['shipping_total' => 1500]);
308
         $order = Order::factory()->for($this->store)->create(['shipping_total' => 1500]);
309
         $method = new \ReflectionMethod(StripeGateway::class, 'shippingLabel');
309
         $method = new \ReflectionMethod(StripeGateway::class, 'shippingLabel');
310
 
310
 
311
-        $this->assertSame('Shipping', $method->invoke(new StripeGateway, $order));
312
-        $this->assertSame('Free shipping', $method->invoke(new StripeGateway, $order->replicate()->fill([])->forceFill(['shipping_total' => 0])));
311
+        $this->assertSame('Shipping', $method->invoke(app(StripeGateway::class), $order));
312
+        $this->assertSame('Free shipping', $method->invoke(app(StripeGateway::class), $order->replicate()->fill([])->forceFill(['shipping_total' => 0])));
313
 
313
 
314
         $this->store->update(['language' => 'ms']);
314
         $this->store->update(['language' => 'ms']);
315
-        $this->assertSame('Penghantaran', $method->invoke(new StripeGateway, $order->fresh()));
315
+        $this->assertSame('Penghantaran', $method->invoke(app(StripeGateway::class), $order->fresh()));
316
     }
316
     }
317
 }
317
 }

+ 2
- 2
tests/Feature/Stores/CheckoutTest.php 파일 보기

316
         $time = time();
316
         $time = time();
317
         $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
317
         $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
318
 
318
 
319
-        $status = (new StripeGateway)->readWebhook($payload, $sign('whsec_test_secret'));
319
+        $status = app(StripeGateway::class)->readWebhook($payload, $sign('whsec_test_secret'));
320
 
320
 
321
         $this->assertSame('cs_test_123', $status->checkoutId);
321
         $this->assertSame('cs_test_123', $status->checkoutId);
322
         $this->assertTrue($status->paid);
322
         $this->assertTrue($status->paid);
324
         $this->assertSame(2580, $status->amount);
324
         $this->assertSame(2580, $status->amount);
325
 
325
 
326
         $this->expectException(PaymentException::class);
326
         $this->expectException(PaymentException::class);
327
-        (new StripeGateway)->readWebhook($payload, $sign('whsec_someone_else'));
327
+        app(StripeGateway::class)->readWebhook($payload, $sign('whsec_someone_else'));
328
     }
328
     }
329
 
329
 
330
     public function test_the_confirmation_email_lists_the_order_in_the_store_language()
330
     public function test_the_confirmation_email_lists_the_order_in_the_store_language()

+ 182
- 0
tests/Feature/Stores/OrderEmailTest.php 파일 보기

1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Enums\StoreStatus;
6
+use App\Mail\OrderConfirmation;
7
+use App\Mail\OrderShipped;
8
+use App\Models\Order;
9
+use App\Models\Store;
10
+use App\Models\User;
11
+use App\StorePlan\SamplePlan;
12
+use Illuminate\Foundation\Testing\RefreshDatabase;
13
+use Tests\TestCase;
14
+
15
+/**
16
+ * The emails shoppers get are in the store's own look, with links back to their order.
17
+ */
18
+class OrderEmailTest extends TestCase
19
+{
20
+    use RefreshDatabase;
21
+
22
+    private Store $store;
23
+
24
+    private Order $order;
25
+
26
+    protected function setUp(): void
27
+    {
28
+        parent::setUp();
29
+
30
+        config(['app.url' => 'https://aicommerce.test', 'storefront.domain' => 'shops.test']);
31
+
32
+        $this->store = Store::factory()->for(User::factory())->create(['name' => 'Kedai Ali', 'slug' => 'kedai-ali', 'whatsapp_number' => '60123456789']);
33
+        $plan = SamplePlan::for($this->store);
34
+        $plan['theme']['colors']['primary'] = '#123456';
35
+        $plan['theme']['colors']['primaryForeground'] = '#FEDCBA';
36
+        $plan['theme']['fonts']['heading'] = 'fraunces';
37
+        $plan['theme']['radius'] = 'large';
38
+        $this->store->plan = $plan;
39
+        $this->store->save();
40
+
41
+        $this->order = Order::factory()->for($this->store)->paid()->create(['number' => 1042, 'subtotal' => 2580, 'shipping_total' => 800, 'total' => 3380]);
42
+        $this->order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
43
+    }
44
+
45
+    private function publish(): void
46
+    {
47
+        $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
48
+    }
49
+
50
+    public function test_the_paid_email_uses_the_stores_colours_fonts_and_corners()
51
+    {
52
+        $mail = new OrderConfirmation($this->order->fresh());
53
+
54
+        $mail->assertSeeInHtml('background-color: #123456; color: #FEDCBA', false);
55
+        $mail->assertSeeInHtml('&#039;Fraunces&#039;, Georgia', false);
56
+        $mail->assertSeeInHtml('border-radius: 16px', false);
57
+        $mail->assertSeeInHtml('Sambal Hijau');
58
+        $mail->assertSeeInHtml('2 × RM 12.90');
59
+        $mail->assertSeeInHtml('RM 33.80');
60
+        // Our app's name is not shown to shoppers: they bought from the store.
61
+        $mail->assertDontSeeInHtml(config('app.name'));
62
+    }
63
+
64
+    public function test_the_paid_email_links_to_the_order_page_and_whatsapp()
65
+    {
66
+        $this->publish();
67
+        $mail = new OrderConfirmation($this->order->fresh());
68
+
69
+        $mail->assertSeeInHtml('https://kedai-ali.shops.test/orders/'.$this->order->public_id, false);
70
+        $mail->assertSeeInHtml('https://wa.me/60123456789?text='.rawurlencode('Hi Kedai Ali, I have a question about my order #1042.'), false);
71
+        $mail->assertSeeInText('View your order: https://kedai-ali.shops.test/orders/'.$this->order->public_id);
72
+        $mail->assertSeeInText('Total paid: RM 33.80');
73
+    }
74
+
75
+    public function test_a_store_that_is_not_live_links_to_its_preview_and_hides_whatsapp_when_there_is_no_number()
76
+    {
77
+        $this->store->forceFill(['whatsapp_number' => null])->save();
78
+        $mail = new OrderConfirmation($this->order->fresh());
79
+
80
+        $mail->assertSeeInHtml(route('stores.preview.order', ['kedai-ali', $this->order->public_id]), false);
81
+        $mail->assertDontSeeInHtml('wa.me', false);
82
+    }
83
+
84
+    public function test_the_store_name_comes_from_its_header()
85
+    {
86
+        $plan = $this->store->plan;
87
+        $plan['header']['content']['logoText'] = 'KEDAI ALI & CO';
88
+        $this->store->forceFill(['plan' => $plan])->save();
89
+
90
+        (new OrderConfirmation($this->order->fresh()))->assertSeeInHtml('KEDAI ALI &amp; CO', false);
91
+    }
92
+
93
+    public function test_the_paid_email_is_in_malay_for_a_malay_store()
94
+    {
95
+        $this->store->update(['language' => 'ms']);
96
+        $mail = new OrderConfirmation($this->order->fresh());
97
+
98
+        $mail->assertSeeInHtml('Terima kasih atas pesanan anda');
99
+        $mail->assertSeeInHtml('Lihat pesanan anda');
100
+        $mail->assertSeeInHtml('Jumlah dibayar');
101
+        $mail->assertSeeInHtml(rawurlencode('Hai Kedai Ali, saya ada soalan tentang pesanan saya #1042.'), false);
102
+    }
103
+
104
+    public function test_the_shipped_email_has_a_tracking_button_when_the_courier_gives_a_link()
105
+    {
106
+        $this->order->forceFill(['shipped_at' => now(), 'shipping_courier' => 'J&T Express', 'tracking_number' => 'JT630012345678', 'tracking_url' => 'https://track.example.com/JT630012345678'])->save();
107
+        $mail = new OrderShipped($this->order->fresh());
108
+
109
+        $mail->assertSeeInHtml('Track your parcel');
110
+        $mail->assertSeeInHtml('https://track.example.com/JT630012345678', false);
111
+        $mail->assertSeeInHtml('JT630012345678');
112
+        $mail->assertSeeInHtml('background-color: #123456; color: #FEDCBA', false);
113
+        $mail->assertSeeInText('Tracking number: JT630012345678');
114
+        $mail->assertSeeInText('J&T Express');
115
+    }
116
+
117
+    public function test_without_a_tracking_link_the_shipped_email_explains_how_to_track()
118
+    {
119
+        $this->order->forceFill(['shipped_at' => now(), 'shipping_courier' => 'Pos Laju', 'tracking_number' => 'EP123MY'])->save();
120
+        $mail = new OrderShipped($this->order->fresh());
121
+
122
+        $mail->assertDontSeeInHtml('Track your parcel');
123
+        $mail->assertSeeInHtml('View your order');
124
+        $mail->assertSeeInHtml("Use the tracking number on the courier's website");
125
+    }
126
+
127
+    public function test_a_store_without_a_design_still_gets_a_tidy_email()
128
+    {
129
+        $this->store->forceFill(['plan' => null])->save();
130
+
131
+        (new OrderConfirmation($this->order->fresh()))
132
+            ->assertSeeInHtml('Kedai Ali')
133
+            ->assertSeeInHtml('background-color: #1F1F1F', false);
134
+    }
135
+
136
+    public function test_emails_come_under_the_stores_name_and_replies_go_to_its_contact_email()
137
+    {
138
+        config(['mail.from.address' => 'orders@aicommerce.test']);
139
+        $this->store->forceFill(['contact_email' => 'hello@kedaiali.my'])->save();
140
+
141
+        foreach ([new OrderConfirmation($this->order->fresh()), new OrderShipped($this->order->fresh())] as $mail) {
142
+            $mail->assertFrom('orders@aicommerce.test', 'Kedai Ali');
143
+            $mail->assertHasReplyTo('hello@kedaiali.my', 'Kedai Ali');
144
+            $mail->assertSeeInHtml('mailto:hello@kedaiali.my', false);
145
+            $mail->assertSeeInText('Questions? Reply to this email or write to hello@kedaiali.my');
146
+        }
147
+    }
148
+
149
+    public function test_without_a_contact_email_there_is_no_reply_address()
150
+    {
151
+        $mail = new OrderConfirmation($this->order->fresh());
152
+
153
+        $this->assertSame([], $mail->envelope()->replyTo);
154
+        $mail->assertDontSeeInHtml('mailto:', false);
155
+    }
156
+
157
+    public function test_the_merchant_sets_the_contact_email_in_settings()
158
+    {
159
+        $this->actingAs($this->store->user);
160
+        $save = fn (array $data) => $this->put(route('stores.settings.update', $this->store->slug), [
161
+            'shipping_west' => '8.00',
162
+            'shipping_east' => '15.00',
163
+            ...$data,
164
+        ]);
165
+
166
+        $this->get(route('stores.settings', $this->store->slug))
167
+            ->assertInertia(fn ($page) => $page
168
+                ->where('settings.contact_email', null)
169
+                ->where('accountEmail', $this->store->user->email));
170
+
171
+        $save(['contact_email' => 'not-an-email'])->assertSessionHasErrors('contact_email');
172
+
173
+        $save(['contact_email' => ' Hello@KedaiAli.my '])->assertSessionHasNoErrors();
174
+        $this->assertSame('hello@kedaiali.my', $this->store->fresh()->contact_email);
175
+
176
+        // Saving a form without the field keeps it; clearing it removes it.
177
+        $save([])->assertSessionHasNoErrors();
178
+        $this->assertSame('hello@kedaiali.my', $this->store->fresh()->contact_email);
179
+        $save(['contact_email' => ''])->assertSessionHasNoErrors();
180
+        $this->assertNull($this->store->fresh()->contact_email);
181
+    }
182
+}

+ 332
- 0
tests/Feature/Stores/StripeConnectTest.php 파일 보기

1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\MerchantAccounts;
6
+use App\Commerce\Payments\MerchantAccountStatus;
7
+use App\Commerce\Payments\PaymentException;
8
+use App\Commerce\Payments\PaymentGateway;
9
+use App\Commerce\Payments\StripeConnect;
10
+use App\Commerce\Payments\StripeGateway;
11
+use App\Enums\OrderStatus;
12
+use App\Enums\StoreStatus;
13
+use App\Mail\OrderConfirmation;
14
+use App\Models\Order;
15
+use App\Models\Product;
16
+use App\Models\Store;
17
+use App\Models\StripeAccount;
18
+use App\Models\User;
19
+use App\StorePlan\SamplePlan;
20
+use Illuminate\Foundation\Testing\RefreshDatabase;
21
+use Illuminate\Support\Facades\Mail;
22
+use Inertia\Testing\AssertableInertia as Assert;
23
+use Tests\Support\FakeGateway;
24
+use Tests\Support\FakeMerchantAccounts;
25
+use Tests\TestCase;
26
+
27
+/**
28
+ * Merchants get paid into their own Stripe account (Stripe Connect).
29
+ */
30
+class StripeConnectTest extends TestCase
31
+{
32
+    use RefreshDatabase;
33
+
34
+    private User $user;
35
+
36
+    private Store $store;
37
+
38
+    private FakeMerchantAccounts $accounts;
39
+
40
+    protected function setUp(): void
41
+    {
42
+        parent::setUp();
43
+
44
+        Mail::fake();
45
+        config(['services.stripe.secret' => 'sk_test_fake']);
46
+
47
+        $this->accounts = new FakeMerchantAccounts;
48
+        $this->app->instance(MerchantAccounts::class, $this->accounts);
49
+
50
+        $this->user = User::factory()->create(['email' => 'ali@example.com']);
51
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali', 'plan' => null]);
52
+        $this->store->plan = SamplePlan::for($this->store);
53
+        $this->store->save();
54
+        $this->actingAs($this->user);
55
+    }
56
+
57
+    private function connect()
58
+    {
59
+        return $this->post(route('stores.payments.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
60
+    }
61
+
62
+    private function connectedAccount(bool $ready = true): StripeAccount
63
+    {
64
+        $account = $this->store->stripeAccount()->create([
65
+            'account_id' => 'acct_fake_'.$this->store->id,
66
+            'charges_enabled' => $ready,
67
+            'payouts_enabled' => $ready,
68
+            'details_submitted' => $ready,
69
+            'checked_at' => now(),
70
+        ]);
71
+        $this->accounts->statuses[$account->account_id] = new MerchantAccountStatus($ready, $ready, $ready);
72
+
73
+        return $account;
74
+    }
75
+
76
+    public function test_settings_show_that_the_store_cannot_take_orders_until_stripe_is_connected()
77
+    {
78
+        $this->get(route('stores.settings', $this->store->slug))
79
+            ->assertInertia(fn (Assert $page) => $page
80
+                ->where('payments.available', true)
81
+                ->where('payments.connected', false)
82
+                ->where('payments.can_take_payments', false));
83
+    }
84
+
85
+    public function test_connecting_opens_a_stripe_account_and_sends_the_merchant_to_stripes_form()
86
+    {
87
+        $response = $this->connect();
88
+
89
+        $response->assertStatus(409);
90
+        $this->assertSame('https://connect.stripe.test/setup/acct_fake_'.$this->store->id, $response->headers->get('X-Inertia-Location'));
91
+        $this->assertSame('acct_fake_'.$this->store->id, $this->store->stripeAccount()->firstOrFail()->account_id);
92
+        $this->assertSame(route('stores.payments.return', $this->store->slug), $this->accounts->links[0]['return']);
93
+        $this->assertSame(route('stores.payments.resume', $this->store->slug), $this->accounts->links[0]['refresh']);
94
+
95
+        // Clicking again (such as "Finish setup") uses the same account.
96
+        $this->connect()->assertStatus(409);
97
+        $this->assertCount(1, $this->accounts->created);
98
+        $this->assertCount(2, $this->accounts->links);
99
+        $this->assertSame(1, StripeAccount::count());
100
+    }
101
+
102
+    public function test_coming_back_unfinished_says_so()
103
+    {
104
+        $this->connect();
105
+
106
+        $this->get(route('stores.payments.return', $this->store->slug))
107
+            ->assertRedirect(route('stores.settings', $this->store->slug))
108
+            ->assertInertiaFlash('toast.type', 'error');
109
+
110
+        $this->get(route('stores.settings', $this->store->slug))
111
+            ->assertInertia(fn (Assert $page) => $page
112
+                ->where('payments.connected', true)
113
+                ->where('payments.details_submitted', false)
114
+                ->where('payments.can_take_payments', false));
115
+        $this->assertSame([], $this->accounts->fpxRequested);
116
+    }
117
+
118
+    public function test_coming_back_finished_saves_the_account_and_asks_for_fpx_once()
119
+    {
120
+        $this->connect();
121
+        $this->accounts->approve('acct_fake_'.$this->store->id);
122
+
123
+        $this->get(route('stores.payments.return', $this->store->slug))
124
+            ->assertRedirect(route('stores.settings', $this->store->slug))
125
+            ->assertInertiaFlash('toast.type', 'success');
126
+
127
+        $account = $this->store->stripeAccount()->firstOrFail();
128
+        $this->assertTrue($account->charges_enabled);
129
+        $this->assertTrue($account->payouts_enabled);
130
+        $this->assertTrue($account->fpx_requested);
131
+
132
+        $this->get(route('stores.payments.return', $this->store->slug));
133
+        $this->assertCount(1, $this->accounts->fpxRequested);
134
+
135
+        $this->get(route('stores.settings', $this->store->slug))
136
+            ->assertInertia(fn (Assert $page) => $page
137
+                ->where('payments.can_take_payments', true)
138
+                ->where('payments.payouts_enabled', true));
139
+    }
140
+
141
+    public function test_an_expired_stripe_link_is_replaced_with_a_fresh_one()
142
+    {
143
+        $this->connectedAccount(ready: false);
144
+
145
+        $this->get(route('stores.payments.resume', $this->store->slug))
146
+            ->assertRedirect('https://connect.stripe.test/setup/acct_fake_'.$this->store->id);
147
+    }
148
+
149
+    public function test_stripe_being_down_shows_a_message_instead_of_an_error_page()
150
+    {
151
+        $this->accounts->down = true;
152
+
153
+        $this->connect()
154
+            ->assertRedirect(route('stores.settings', $this->store->slug))
155
+            ->assertInertiaFlash('toast.type', 'error');
156
+        $this->assertNull($this->store->stripeAccount()->first());
157
+    }
158
+
159
+    public function test_without_the_apps_stripe_key_connecting_is_not_offered()
160
+    {
161
+        config(['services.stripe.secret' => '']);
162
+
163
+        $this->get(route('stores.settings', $this->store->slug))
164
+            ->assertInertia(fn (Assert $page) => $page->where('payments.available', false));
165
+        $this->connect()->assertRedirect(route('stores.settings', $this->store->slug));
166
+        $this->assertSame([], $this->accounts->created);
167
+    }
168
+
169
+    public function test_another_merchants_store_cannot_be_connected()
170
+    {
171
+        $other = Store::factory()->create();
172
+
173
+        $this->post(route('stores.payments.connect', $other->slug))->assertNotFound();
174
+        $this->get(route('stores.payments.return', $other->slug))->assertNotFound();
175
+        $this->get(route('stores.payments.resume', $other->slug))->assertNotFound();
176
+    }
177
+
178
+    public function test_a_store_takes_payments_only_once_stripe_approves_and_stripe_is_asked_at_most_once_a_minute()
179
+    {
180
+        $connect = app(StripeConnect::class);
181
+        $this->assertFalse($connect->canTakePayments($this->store));
182
+
183
+        $this->connectedAccount(ready: false);
184
+        $this->store->refresh();
185
+
186
+        // Checked just now, so Stripe is not asked again yet.
187
+        $this->assertFalse($connect->canTakePayments($this->store));
188
+        $this->assertSame(0, $this->accounts->statusCalls);
189
+
190
+        $this->accounts->approve('acct_fake_'.$this->store->id);
191
+        $this->travel(2)->minutes();
192
+
193
+        $this->assertTrue($connect->canTakePayments($this->store->refresh()));
194
+        $this->assertSame(1, $this->accounts->statusCalls);
195
+
196
+        // A fully set up store is not asked about again.
197
+        $this->travel(2)->minutes();
198
+        $this->assertTrue($connect->canTakePayments($this->store->refresh()));
199
+        $this->assertSame(1, $this->accounts->statusCalls);
200
+    }
201
+
202
+    public function test_the_real_gateway_will_not_open_a_payment_page_for_a_store_without_stripe()
203
+    {
204
+        $order = Order::factory()->for($this->store)->create();
205
+
206
+        $this->assertFalse(app(StripeGateway::class)->canTakePayments($this->store));
207
+
208
+        $this->expectException(PaymentException::class);
209
+        app(StripeGateway::class)->startCheckout($order, 'https://shop.test/ok', 'https://shop.test/cart');
210
+    }
211
+
212
+    public function test_shoppers_cannot_check_out_until_the_store_can_take_payments()
213
+    {
214
+        $gateway = new FakeGateway;
215
+        $gateway->takingPayments = false;
216
+        $this->app->instance(PaymentGateway::class, $gateway);
217
+        $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
218
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
219
+
220
+        $this->get(route('stores.preview.checkout', $this->store->slug))
221
+            ->assertInertia(fn (Assert $page) => $page->where('view.takingOrders', false));
222
+
223
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
224
+            'name' => 'Aminah binti Ali',
225
+            'email' => 'aminah@example.com',
226
+            'phone' => '012-345 6789',
227
+            'line1' => '12 Jalan Mawar',
228
+            'city' => 'Shah Alam',
229
+            'postcode' => '40000',
230
+            'state' => 'Selangor',
231
+        ])->assertSessionHasErrors(['cart' => 'This store is not taking orders yet. Please check back soon.']);
232
+
233
+        $this->assertSame(0, Order::count());
234
+        $this->assertSame([], $gateway->started);
235
+    }
236
+
237
+    public function test_an_order_remembers_the_merchant_account_and_the_merchants_webhook_marks_it_paid()
238
+    {
239
+        $gateway = new FakeGateway;
240
+        $this->app->instance(PaymentGateway::class, $gateway);
241
+        $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
242
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
243
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
244
+            'name' => 'Aminah binti Ali',
245
+            'email' => 'aminah@example.com',
246
+            'phone' => '012-345 6789',
247
+            'line1' => '12 Jalan Mawar',
248
+            'city' => 'Shah Alam',
249
+            'postcode' => '40000',
250
+            'state' => 'Selangor',
251
+        ]);
252
+        $order = Order::firstOrFail();
253
+        $account = 'acct_fake_'.$this->store->id;
254
+        $this->assertSame($account, $order->payment_account);
255
+        $gateway->pay($order);
256
+        auth()->logout();
257
+
258
+        $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'forged'])
259
+            ->assertStatus(400);
260
+        // A payment in some other merchant's account never marks this order.
261
+        $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => 'acct_someone_else'], ['Stripe-Signature' => 'valid-connect'])
262
+            ->assertOk();
263
+        $this->assertFalse($order->fresh()->isPaid());
264
+
265
+        $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'valid-connect'])
266
+            ->assertOk();
267
+
268
+        $this->assertTrue($order->fresh()->isPaid());
269
+        $this->assertSame(9, $product->fresh()->stock);
270
+        Mail::assertSent(OrderConfirmation::class, 1);
271
+    }
272
+
273
+    public function test_the_real_gateway_reads_merchant_messages_with_their_own_secret()
274
+    {
275
+        config(['services.stripe.webhook_secret' => 'whsec_ours', 'services.stripe.connect_webhook_secret' => 'whsec_merchants']);
276
+
277
+        $payload = (string) json_encode([
278
+            'id' => 'evt_1',
279
+            'object' => 'event',
280
+            'account' => 'acct_123',
281
+            'type' => 'checkout.session.completed',
282
+            'data' => ['object' => [
283
+                'id' => 'cs_test_123',
284
+                'object' => 'checkout.session',
285
+                'payment_status' => 'paid',
286
+                'payment_intent' => 'pi_123',
287
+                'amount_total' => 2580,
288
+            ]],
289
+        ]);
290
+        $time = time();
291
+        $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
292
+
293
+        $status = app(StripeGateway::class)->readWebhook($payload, $sign('whsec_merchants'), fromMerchants: true);
294
+
295
+        $this->assertSame('cs_test_123', $status->checkoutId);
296
+        $this->assertSame('acct_123', $status->account);
297
+        $this->assertTrue($status->paid);
298
+
299
+        $this->expectException(PaymentException::class);
300
+        app(StripeGateway::class)->readWebhook($payload, $sign('whsec_ours'), fromMerchants: true);
301
+    }
302
+
303
+    public function test_the_overview_asks_merchants_to_connect_stripe()
304
+    {
305
+        $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
306
+
307
+        $this->get(route('dashboard'))
308
+            ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', false));
309
+
310
+        $this->connectedAccount();
311
+
312
+        $this->get(route('dashboard'))
313
+            ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', true));
314
+    }
315
+
316
+    public function test_a_live_store_that_cannot_take_payments_needs_attention()
317
+    {
318
+        $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
319
+        // A sale already made, so the overview shows its full view with "Needs attention".
320
+        Order::factory()->for($this->store)->create(['status' => OrderStatus::Paid, 'paid_at' => now(), 'shipped_at' => now()]);
321
+
322
+        $this->get(route('dashboard'))
323
+            ->assertInertia(fn (Assert $page) => $page
324
+                ->where('stats.attention.0.kind', 'payments')
325
+                ->where('stats.attention.0.store.slug', $this->store->slug));
326
+
327
+        $this->connectedAccount();
328
+
329
+        $this->get(route('dashboard'))
330
+            ->assertInertia(fn (Assert $page) => $page->where('stats.attention', fn ($items) => collect($items)->doesntContain('kind', 'payments')));
331
+    }
332
+}

+ 27
- 6
tests/Support/FakeGateway.php 파일 보기

7
 use App\Commerce\Payments\PaymentGateway;
7
 use App\Commerce\Payments\PaymentGateway;
8
 use App\Commerce\Payments\PaymentStatus;
8
 use App\Commerce\Payments\PaymentStatus;
9
 use App\Models\Order;
9
 use App\Models\Order;
10
+use App\Models\Store;
10
 
11
 
11
 /**
12
 /**
12
  * A payment provider for tests. Nothing leaves the machine.
13
  * A payment provider for tests. Nothing leaves the machine.
22
 
23
 
23
     public bool $failToStart = false;
24
     public bool $failToStart = false;
24
 
25
 
26
+    /** Whether stores can take payments. Most tests do not care about connecting Stripe. */
27
+    public bool $takingPayments = true;
28
+
25
     public ?string $successUrl = null;
29
     public ?string $successUrl = null;
26
 
30
 
27
     public ?string $cancelUrl = null;
31
     public ?string $cancelUrl = null;
31
         return 'fake';
35
         return 'fake';
32
     }
36
     }
33
 
37
 
38
+    public function canTakePayments(Store $store): bool
39
+    {
40
+        return $this->takingPayments;
41
+    }
42
+
34
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
43
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
35
     {
44
     {
36
         if ($this->failToStart) {
45
         if ($this->failToStart) {
43
         $this->cancelUrl = $cancelUrl;
52
         $this->cancelUrl = $cancelUrl;
44
         $this->payments[$id] = new PaymentStatus($id, paid: false);
53
         $this->payments[$id] = new PaymentStatus($id, paid: false);
45
 
54
 
46
-        return new CheckoutLink($id, 'https://pay.test/'.$id);
55
+        return new CheckoutLink($id, 'https://pay.test/'.$id, 'acct_fake_'.$order->store_id);
47
     }
56
     }
48
 
57
 
49
-    public function checkPayment(string $checkoutId): PaymentStatus
58
+    public function checkPayment(Order $order): PaymentStatus
50
     {
59
     {
51
-        return $this->payments[$checkoutId] ?? throw new PaymentException('Unknown payment.');
60
+        return $this->find((string) $order->payment_checkout_id);
52
     }
61
     }
53
 
62
 
54
-    public function readWebhook(string $payload, string $signature): ?PaymentStatus
63
+    public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
55
     {
64
     {
56
-        if ($signature !== 'valid') {
65
+        if ($signature !== ($fromMerchants ? 'valid-connect' : 'valid')) {
57
             throw new PaymentException('Bad signature.');
66
             throw new PaymentException('Bad signature.');
58
         }
67
         }
59
 
68
 
60
         $data = json_decode($payload, true);
69
         $data = json_decode($payload, true);
61
 
70
 
62
-        return isset($data['checkout_id']) ? $this->checkPayment($data['checkout_id']) : null;
71
+        if (! isset($data['checkout_id'])) {
72
+            return null;
73
+        }
74
+
75
+        $status = $this->find($data['checkout_id']);
76
+
77
+        // Messages about merchants' accounts say which account the payment was made in.
78
+        return new PaymentStatus($status->checkoutId, $status->paid, $status->reference, $status->amount, $data['account'] ?? null);
79
+    }
80
+
81
+    private function find(string $checkoutId): PaymentStatus
82
+    {
83
+        return $this->payments[$checkoutId] ?? throw new PaymentException('Unknown payment.');
63
     }
84
     }
64
 
85
 
65
     /**
86
     /**

+ 81
- 0
tests/Support/FakeMerchantAccounts.php 파일 보기

1
+<?php
2
+
3
+namespace Tests\Support;
4
+
5
+use App\Commerce\Payments\MerchantAccounts;
6
+use App\Commerce\Payments\MerchantAccountStatus;
7
+use App\Commerce\Payments\PaymentException;
8
+use App\Models\Store;
9
+
10
+/**
11
+ * Merchants' Stripe accounts for tests. Nothing leaves the machine.
12
+ * Tests set what Stripe "says" about an account in $statuses.
13
+ */
14
+final class FakeMerchantAccounts implements MerchantAccounts
15
+{
16
+    /** @var array<string, MerchantAccountStatus> */
17
+    public array $statuses = [];
18
+
19
+    /** @var list<string> */
20
+    public array $created = [];
21
+
22
+    /** @var list<array{account: string, return: string, refresh: string}> */
23
+    public array $links = [];
24
+
25
+    /** @var list<string> */
26
+    public array $fpxRequested = [];
27
+
28
+    public int $statusCalls = 0;
29
+
30
+    public bool $down = false;
31
+
32
+    public function create(Store $store, string $email): string
33
+    {
34
+        $this->failIfDown();
35
+
36
+        $id = 'acct_fake_'.$store->id;
37
+        $this->created[] = $id;
38
+        $this->statuses[$id] ??= new MerchantAccountStatus(false, false, false);
39
+
40
+        return $id;
41
+    }
42
+
43
+    public function setupLink(string $accountId, string $returnUrl, string $refreshUrl): string
44
+    {
45
+        $this->failIfDown();
46
+
47
+        $this->links[] = ['account' => $accountId, 'return' => $returnUrl, 'refresh' => $refreshUrl];
48
+
49
+        return 'https://connect.stripe.test/setup/'.$accountId;
50
+    }
51
+
52
+    public function status(string $accountId): MerchantAccountStatus
53
+    {
54
+        $this->failIfDown();
55
+        $this->statusCalls++;
56
+
57
+        return $this->statuses[$accountId] ?? throw new PaymentException('Unknown account.');
58
+    }
59
+
60
+    public function requestFpx(string $accountId): void
61
+    {
62
+        $this->failIfDown();
63
+
64
+        $this->fpxRequested[] = $accountId;
65
+    }
66
+
67
+    /**
68
+     * Pretend the merchant finished Stripe's form and Stripe approved the account.
69
+     */
70
+    public function approve(string $accountId, bool $payouts = true): void
71
+    {
72
+        $this->statuses[$accountId] = new MerchantAccountStatus(true, $payouts, true);
73
+    }
74
+
75
+    private function failIfDown(): void
76
+    {
77
+        if ($this->down) {
78
+            throw new PaymentException('Stripe is down.');
79
+        }
80
+    }
81
+}

+ 3
- 0
tests/TestCase.php 파일 보기

3
 namespace Tests;
3
 namespace Tests;
4
 
4
 
5
 use App\Billing\SubscriptionGateway;
5
 use App\Billing\SubscriptionGateway;
6
+use App\Commerce\Payments\MerchantAccounts;
6
 use App\Commerce\Payments\PaymentGateway;
7
 use App\Commerce\Payments\PaymentGateway;
7
 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
8
 use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
8
 use Laravel\Fortify\Features;
9
 use Laravel\Fortify\Features;
9
 use Tests\Support\FakeGateway;
10
 use Tests\Support\FakeGateway;
11
+use Tests\Support\FakeMerchantAccounts;
10
 use Tests\Support\FakeSubscriptionGateway;
12
 use Tests\Support\FakeSubscriptionGateway;
11
 
13
 
12
 abstract class TestCase extends BaseTestCase
14
 abstract class TestCase extends BaseTestCase
18
         // No test may ever talk to the real payment service. Tests that care replace these with their own.
20
         // No test may ever talk to the real payment service. Tests that care replace these with their own.
19
         $this->app->instance(PaymentGateway::class, new FakeGateway);
21
         $this->app->instance(PaymentGateway::class, new FakeGateway);
20
         $this->app->instance(SubscriptionGateway::class, new FakeSubscriptionGateway);
22
         $this->app->instance(SubscriptionGateway::class, new FakeSubscriptionGateway);
23
+        $this->app->instance(MerchantAccounts::class, new FakeMerchantAccounts);
21
     }
24
     }
22
 
25
 
23
     protected function skipUnlessFortifyHas(string $feature, ?string $message = null): void
26
     protected function skipUnlessFortifyHas(string $feature, ?string $message = null): void

Loading…
취소
저장