Parcourir la source

Double-check unpaid orders and let shoppers complete their payment

- Every 5 minutes, ask Stripe or HitPay about unpaid orders whose payment news may have been missed, and mark them paid
- After 25 hours with no payment, the order becomes "Not paid" and is left alone
- Both payment pages now close 23 hours after the order, and that deadline is shown to shoppers
- Order page: "Complete payment" button with the deadline; "Payment time is over" after it
- Cart page: banner for the shopper's own unpaid order (same browser only)
- One "Complete your payment" email about 30 minutes after an unpaid order, in English or Malay; not sent if they paid, ordered again, the provider could not be checked, or under an hour is left
- Every "Complete payment" link asks the provider first, so a paid or expired order goes to the order page
- Merchant order page: notes for orders waiting for payment and for "Not paid" orders
- New columns on orders: payment_checked_at, payment_url, payment_expires_at, payment_reminded_at (run php artisan migrate)
payment-double-check-and-complete-payment
fahmisaad il y a 6 heures
Parent
révision
5ed6d66cd9

+ 59
- 12
PROGRESS.md Voir le fichier

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-12-02
6
 **Last updated:** 2026-12-02
7
-**Current step:** Everything up to the store logo (footer and tab icon) is on `main`. GrabPay is switched on for merchants and tested, and DuitNow QR, Touch 'n Go and ShopeePay through HitPay are built and tested with a real HitPay sandbox payment (order #1011, DuitNow). Both not committed yet. Step 9 part 8 on hold
8
-**Next action:** Commit GrabPay and HitPay. Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
7
+**Current step:** GrabPay and HitPay (DuitNow QR, Touch 'n Go, ShopeePay) are on `main`. The double-check for missed payments and "Complete payment" (order page button, cart reminder, reminder email, merchant notes) are built (not committed yet). Step 9 part 8 on hold
8
+**Next action:** Commit the double-check and "Complete payment". Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting (follow the "Before going live" checklist in Step 10)
9
 
9
 
10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11
 
11
 
154
 - Refunds are done in the merchant's HitPay dashboard. DuitNow payments cannot be refunded through HitPay.
154
 - Refunds are done in the merchant's HitPay dashboard. DuitNow payments cannot be refunded through HitPay.
155
 - Code: `app/Commerce/Payments/HitPay/` (`HitPayApi`, `HitPayGateway`), `PaymentGateways` (the ways to pay), `HitPayController`, `HitPayWebhookController`, `resources/js/components/stores/hitpay-setup.tsx`.
155
 - Code: `app/Commerce/Payments/HitPay/` (`HitPayApi`, `HitPayGateway`), `PaymentGateways` (the ways to pay), `HitPayController`, `HitPayWebhookController`, `resources/js/components/stores/hitpay-setup.tsx`.
156
 
156
 
157
+### Double-check for missed payments (added 2026-12-02)
158
+
159
+**Why:** an order is normally marked paid in one of two ways: (1) the shopper comes back to the store after paying, and the store asks Stripe or HitPay; (2) Stripe or HitPay calls our webhook. If the shopper closes the phone right after paying **and** the webhook is missed (our server was down for a moment, the provider had a problem, or the app has no public https address yet, like on this machine), the merchant has the money but the order stays "Awaiting payment". The double-check catches that.
160
+
161
+**How it works:** `php artisan orders:check-payments` runs **every 5 minutes** (`routes/console.php`). It asks Stripe or HitPay about orders still awaiting payment, and marks paid the ones that were paid (stock lowered, email sent, exactly as on the return page). Code: `App\Commerce\PaymentDoubleCheck`.
162
+
163
+**Rules that keep it light** (so 100 waiting orders cost almost nothing):
164
+
165
+| Order age            | How often it is asked about                                |
166
+| -------------------- | ---------------------------------------------------------- |
167
+| Under 2 minutes      | Not yet (most payments are confirmed on their own by then) |
168
+| 2 to 15 minutes      | Every 5 minutes                                            |
169
+| 15 minutes to 1 hour | Every 15 minutes                                           |
170
+| 1 hour to 25 hours   | Every hour                                                 |
171
+| Over 25 hours        | Never again: the order becomes **"Not paid"**              |
172
+
173
+- About 30 questions per abandoned order in total; none for orders that were paid normally. Example: 100 waiting orders is roughly one question every few seconds at worst, far below HitPay's limit (about 400 a minute) and Stripe's (about 100 a second). The questions are free.
174
+- Payment pages expire before we give up, so nobody can pay an order we stopped checking: both Stripe's and HitPay's pages expire **23 hours** after the order (`Checkout::PAY_WITHIN_HOURS`; Stripe gets `expires_at`, HitPay `expires_after`).
175
+- `orders.payment_checked_at` remembers the last question. It is saved before asking, so a provider that is down is not asked again on the very next run.
176
+- "Not paid" (`OrderStatus::Unpaid`) is a new order status, shown grey in the orders list. If a payment still arrives later (webhook or the shopper's order page), the order is marked paid as usual.
177
+- **It only runs while Laravel's scheduler runs.** On this machine, `composer run dev` starts it (as "scheduler", added in `AppServiceProvider`). On the server, it needs one cron line (see "Before going live" in section 3, Step 10). Without it, nothing is double-checked, and nothing warns about it.
178
+- Real run on 2026-12-02: one old test order (#1007, Luna Skin, from 23 Nov) became "Not paid"; the run took under a second.
179
+
180
+### Complete payment and the reminder email (added 2026-12-03)
181
+
182
+**Why:** a shopper (say Aminah) who closes the payment page without paying could not get back to it, and did not know how long she had. Now she can, from three places, until the deadline.
183
+
184
+- **The deadline:** 23 hours after the order (`Checkout::PAY_WITHIN_HOURS`). Saved on the order as `payment_expires_at`, together with the payment page address (`payment_url`). Both providers' pages expire at that time.
185
+- **Order page** (`/orders/<secret id>`): "Complete payment" button and "You can still pay until 4 Dec, 3:15 pm". After the deadline: "Payment time is over… You were not charged. Please order again."
186
+- **Cart page:** "You have an unpaid order #1012. Pay by … [Complete payment]". Only in the browser that placed the order (the browser session remembers it, like the cart). Forgotten once paid or closed.
187
+- **Email "Complete your payment":** sent **once**, about **30 minutes** after the order, by the double-check (`PaymentDoubleCheck::REMIND_AFTER_MINUTES`). Not sooner, because many shoppers are still on the payment page in the first minutes (scanning a QR code, waiting for a bank code). Only sent after Stripe or HitPay confirms the order is unpaid; not when the shopper placed a newer order since; not when less than an hour is left. `payment_reminded_at` remembers it. Works on any device, because it goes to the email typed at checkout.
188
+- **All three buttons go to `/orders/<secret id>/pay`**, which asks the provider first: already paid → the thank-you page; too late → the order page with the "time is over" notice; otherwise → back to the same payment page.
189
+- **Who can use it:** whoever has the secret order link (26 random characters) or the same browser. No login needed. The worst a leaked link allows is paying for someone else's order.
190
+- **Merchants** see "Waiting for the shopper to pay. They can pay until … We emailed them a reminder on …" on a waiting order, and "The shopper did not pay in time, so this order is closed. You don't need to do anything" on a "Not paid" one.
191
+- Older orders (before 2026-12-03) have no saved payment page, so they keep the old "not paid yet" notice.
192
+- Code: `CheckoutController::pay`, `Cart::rememberUnpaidOrder` / `unpaidOrder`, `App\Mail\PaymentReminder`, `resources/views/mail/orders/payment-reminder*.blade.php`. Tests: `CompletePaymentTest`.
193
+
157
 ### How shipping and WhatsApp work (added in Step 7)
194
 ### How shipping and WhatsApp work (added in Step 7)
158
 
195
 
159
 - Shipping fees are stored on the store in sen (`shipping_west`, `shipping_east`, `free_shipping_over`). Sabah, Sarawak and Labuan use the east fee; every other state uses the west fee.
196
 - Shipping fees are stored on the store in sen (`shipping_west`, `shipping_east`, `free_shipping_over`). Sabah, Sarawak and Labuan use the east fee; every other state uses the west fee.
441
 - [x] Checkout with Stripe Malaysia (test mode): shopper details and address, then Stripe's hosted payment page. Tested with a real Stripe test payment on 2026-11-15
478
 - [x] Checkout with Stripe Malaysia (test mode): shopper details and address, then Stripe's hosted payment page. Tested with a real Stripe test payment on 2026-11-15
442
 - [x] Orders list and order page for the merchant ("Orders" tab)
479
 - [x] Orders list and order page for the merchant ("Orders" tab)
443
 - [x] Order confirmation email, in the store's language, sent once when the order is paid
480
 - [x] Order confirmation email, in the store's language, sent once when the order is paid
444
-- [ ] Known gaps, to do later: (shipping fee and "mark as shipped" were done in Step 7 part 1); unpaid orders stay in the list as "Awaiting payment"; the Stripe webhook needs a public address, so it only starts working after hosting (Step 10)
481
+- [ ] Known gaps, to do later: (shipping fee and "mark as shipped" were done in Step 7 part 1); unpaid orders become "Not paid" after 25 hours (double-check, added 2026-12-02); shoppers can come back and pay for 23 hours ("Complete payment" and a reminder email, added 2026-12-03); the Stripe and HitPay webhooks need a public https address, so they only start working after hosting (Step 10)
445
 - [x] Content pages by chat ("add an About page", "remove the About page"): the AI creates the page, and the app itself makes sure the menu links to it. Tested with real DeepSeek on 2026-11-15
482
 - [x] Content pages by chat ("add an About page", "remove the About page"): the AI creates the page, and the app itself makes sure the menu links to it. Tested with real DeepSeek on 2026-11-15
446
 
483
 
447
 ### Step 5 — Publishing
484
 ### Step 5 — Publishing
553
     - [x] GrabPay (2026-12-01): asked for on each merchant's account once the sign-up form is finished, like FPX (`grabpay_payments` capability, then switched on in the account's payment method settings). Stores connected before this get it switched on the next time the app checks their account. New column `stripe_accounts.grabpay_requested`. Real test: Luna Skin order #1010 (RM 50) paid with GrabPay on Stripe's test page; RM 50.00 landed in Luna Skin's own account (RM 48.50 after Stripe's 3% GrabPay fee), nothing in ours
590
     - [x] GrabPay (2026-12-01): asked for on each merchant's account once the sign-up form is finished, like FPX (`grabpay_payments` capability, then switched on in the account's payment method settings). Stores connected before this get it switched on the next time the app checks their account. New column `stripe_accounts.grabpay_requested`. Real test: Luna Skin order #1010 (RM 50) paid with GrabPay on Stripe's test page; RM 50.00 landed in Luna Skin's own account (RM 48.50 after Stripe's 3% GrabPay fee), nothing in ours
554
     - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
591
     - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
555
 - [ ] Choose hosting and deploy
592
 - [ ] Choose hosting and deploy
593
+    - Before going live, on the server (checklist, added 2026-12-02):
594
+        - [ ] `APP_URL` starts with `https://` (needed for the HitPay webhook; Stripe's webhooks are added in Stripe with the https address)
595
+        - [ ] `HITPAY_SANDBOX=false`, so merchants connect their real HitPay accounts
596
+        - [ ] Stripe live keys, `STRIPE_WEBHOOK_SECRET` and `STRIPE_CONNECT_WEBHOOK_SECRET` filled in
597
+        - [ ] **Scheduler cron line**, or the double-check for missed payments never runs: `* * * * * cd /path-to-app && php artisan schedule:run >> /dev/null 2>&1`. Check with `php artisan schedule:list` (shows `orders:check-payments` every 5 minutes)
598
+        - [ ] A queue worker kept running (`php artisan queue:work`), for AI jobs
599
+        - [ ] `php artisan migrate` after every update
556
 - [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)
600
 - [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)
557
 - [ ] Backup AI provider in case one is down
601
 - [ ] Backup AI provider in case one is down
558
 - [ ] Spending caps on every AI account
602
 - [ ] Spending caps on every AI account
580
 
624
 
581
 Then, from the project folder:
625
 Then, from the project folder:
582
 
626
 
583
-| Task                                | Command                                    |
584
-| ----------------------------------- | ------------------------------------------ |
585
-| Start the app (server, queue, Vite) | `composer run dev`                         |
586
-| Open the app                        | http://localhost:8000                      |
587
-| Run all tests                       | `php artisan test`                         |
588
-| Check PHP style and types           | `composer lint` and `composer types:check` |
589
-| Check frontend                      | `npm run check` and `npm run types:check`  |
590
-| Rebuild frontend for tests          | `npm run build`                            |
627
+| Task                                           | Command                                    |
628
+| ---------------------------------------------- | ------------------------------------------ |
629
+| Start the app (server, queue, scheduler, Vite) | `composer run dev`                         |
630
+| Open the app                                   | http://localhost:8000                      |
631
+| Run all tests                                  | `php artisan test`                         |
632
+| Check PHP style and types                      | `composer lint` and `composer types:check` |
633
+| Check frontend                                 | `npm run check` and `npm run types:check`  |
634
+| Rebuild frontend for tests                     | `npm run build`                            |
591
 
635
 
592
 - Settings files: `.env` is uploaded to the repository and holds only basic, non-secret settings (secrets and all AI settings are blank). `.env.local` is never uploaded and holds everything needed to run, including keys. When `.env.local` exists the app reads it instead of `.env`, so it must be complete. This is set up in `bootstrap/app.php`.
636
 - Settings files: `.env` is uploaded to the repository and holds only basic, non-secret settings (secrets and all AI settings are blank). `.env.local` is never uploaded and holds everything needed to run, including keys. When `.env.local` exists the app reads it instead of `.env`, so it must be complete. This is set up in `bootstrap/app.php`.
593
 - Database: MySQL, database `ai_commerce`, settings in `.env.local`.
637
 - Database: MySQL, database `ai_commerce`, settings in `.env.local`.
594
 - Local test login: created by `php artisan db:seed`. Email is in `database/seeders/DatabaseSeeder.php`, password in `database/factories/UserFactory.php`.
638
 - Local test login: created by `php artisan db:seed`. Email is in `database/seeders/DatabaseSeeder.php`, password in `database/factories/UserFactory.php`.
595
 - AI: `.env.local` now uses the real providers (`claude` and `deepseek`), so every generation and edit costs a little money. To work for free, set both providers to `fake`. For real AI, set `AI_GENERATE_PROVIDER=claude` and `AI_EDIT_PROVIDER=deepseek`, and fill in `ANTHROPIC_API_KEY` and `DEEPSEEK_API_KEY`.
639
 - AI: `.env.local` now uses the real providers (`claude` and `deepseek`), so every generation and edit costs a little money. To work for free, set both providers to `fake`. For real AI, set `AI_GENERATE_PROVIDER=claude` and `AI_EDIT_PROVIDER=deepseek`, and fill in `ANTHROPIC_API_KEY` and `DEEPSEEK_API_KEY`.
640
+- The double-check for missed payments runs every 5 minutes through the scheduler, which `composer run dev` also starts. To run it once by hand: `php artisan orders:check-payments`.
596
 - AI jobs need the background worker. `composer run dev` starts it. Without it, a job waits and is marked failed after 10 minutes.
641
 - AI jobs need the background worker. `composer run dev` starts it. Without it, a job waits and is marked failed after 10 minutes.
597
 - Emails (such as verification links) are written to `storage/logs/laravel.log`, not sent.
642
 - Emails (such as verification links) are written to `storage/logs/laravel.log`, not sent.
598
 - Code repository: `https://git.mirfalah.my/mirfalah-tech/ai_commerce.git` (remote name `origin`). The `.env.local` file is never uploaded.
643
 - Code repository: `https://git.mirfalah.my/mirfalah-tech/ai_commerce.git` (remote name `origin`). The `.env.local` file is never uploaded.
741
 | 2026-12-01 | GrabPay switched on for every merchant's own Stripe account (like FPX); tested with order #1010 paid by GrabPay into Luna Skin's account. Researched DuitNow QR and e-wallets: HitPay recommended. 364 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit; decide on HitPay                                        |
786
 | 2026-12-01 | GrabPay switched on for every merchant's own Stripe account (like FPX); tested with order #1010 paid by GrabPay into Luna Skin's account. Researched DuitNow QR and e-wallets: HitPay recommended. 364 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit; decide on HitPay                                        |
742
 | 2026-12-02 | Compared Stripe and HitPay fees. Built DuitNow QR, Touch 'n Go and ShopeePay through each merchant's own HitPay account: API key in Settings, choice of Stripe or HitPay at checkout, paid only after asking HitPay (return page and webhook). 376 tests pass; Settings card and checkout choice checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                 | Real HitPay sandbox test; commit                                |
787
 | 2026-12-02 | Compared Stripe and HitPay fees. Built DuitNow QR, Touch 'n Go and ShopeePay through each merchant's own HitPay account: API key in Settings, choice of Stripe or HitPay at checkout, paid only after asking HitPay (return page and webhook). 376 tests pass; Settings card and checkout choice checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                 | Real HitPay sandbox test; commit                                |
743
 | 2026-12-02 | Real HitPay sandbox test: Malaysian sandbox account, methods switched on in HitPay first (all start off), order #1011 (RM 50) paid by DuitNow QR and marked paid; fee RM 0.60. HitPay key kept out of error logs. 376 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Commit; warn merchants when HitPay refuses a method             |
788
 | 2026-12-02 | Real HitPay sandbox test: Malaysian sandbox account, methods switched on in HitPay first (all start off), order #1011 (RM 50) paid by DuitNow QR and marked paid; fee RM 0.60. HitPay key kept out of error logs. 376 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Commit; warn merchants when HitPay refuses a method             |
744
-| 2026-12-02 | HitPay reminder: the card's guide says to Turn On methods in HitPay first; methods HitPay refuses are remembered, left out of checkout for an hour (the shopper still pays with what is left) and shown as a warning in the card until the merchant saves. 379 tests pass; warning checked in the browser. | Commit |
789
+| 2026-12-02 | HitPay reminder: the card's guide says to Turn On methods in HitPay first; methods HitPay refuses are remembered, left out of checkout for an hour (the shopper still pays with what is left) and shown as a warning in the card until the merchant saves. 379 tests pass; warning checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                               | Commit                                                          |
790
+| 2026-12-02 | Double-check for missed payments: `orders:check-payments` every 5 minutes asks Stripe or HitPay about orders awaiting payment (often at first, hourly later), marks paid the ones that were paid, and turns them "Not paid" after 25 hours; HitPay pages now expire after 23 hours. Scheduler added to `composer run dev`; "Before going live" checklist added to Step 10. 385 tests pass; real run turned old order #1007 into "Not paid".                                                                                                                                                                                                                                                                                                              | Commit                                                          |
791
+| 2026-12-03 | "Complete payment": the order keeps its payment page and a 23-hour deadline (Stripe and HitPay pages expire then); order page button with the deadline, "unpaid order" note on the cart page (same browser), one "Complete your payment" email about 30 minutes after an unpaid order (sent by the double-check), and merchant notes for waiting and "Not paid" orders. 398 tests pass.                                                                                                                                                                                                                                                                                                                                                                  | Commit                                                          |

+ 38
- 0
app/Commerce/Cart.php Voir le fichier

4
 
4
 
5
 use App\Models\AutomaticDiscount;
5
 use App\Models\AutomaticDiscount;
6
 use App\Models\DiscountCode;
6
 use App\Models\DiscountCode;
7
+use App\Models\Order;
7
 use App\Models\Product;
8
 use App\Models\Product;
8
 use App\Models\ProductVariant;
9
 use App\Models\ProductVariant;
9
 use App\Models\Store;
10
 use App\Models\Store;
148
     {
149
     {
149
         $this->session->forget($this->key());
150
         $this->session->forget($this->key());
150
         $this->session->forget($this->discountKey());
151
         $this->session->forget($this->discountKey());
152
+        $this->session->forget($this->unpaidOrderKey());
153
+    }
154
+
155
+    /**
156
+     * Remember the order the shopper just placed, so the cart page can offer "Complete payment" if they leave the
157
+     * payment page. Kept in this browser only, like the cart itself.
158
+     */
159
+    public function rememberUnpaidOrder(Order $order): void
160
+    {
161
+        $this->session->put($this->unpaidOrderKey(), $order->public_id);
162
+    }
163
+
164
+    /**
165
+     * The order this shopper placed and can still pay, or null. An order that was paid or ran out of time is forgotten.
166
+     */
167
+    public function unpaidOrder(): ?Order
168
+    {
169
+        $publicId = $this->session->get($this->unpaidOrderKey());
170
+
171
+        if (! is_string($publicId)) {
172
+            return null;
173
+        }
174
+
175
+        $order = $this->store->orders()->where('public_id', $publicId)->first();
176
+
177
+        if ($order === null || ! $order->canStillPay()) {
178
+            $this->session->forget($this->unpaidOrderKey());
179
+
180
+            return null;
181
+        }
182
+
183
+        return $order;
151
     }
184
     }
152
 
185
 
153
     /**
186
     /**
445
     {
478
     {
446
         return 'cart_discount.'.$this->store->id;
479
         return 'cart_discount.'.$this->store->id;
447
     }
480
     }
481
+
482
+    private function unpaidOrderKey(): string
483
+    {
484
+        return 'unpaid_order.'.$this->store->id;
485
+    }
448
 }
486
 }

+ 6
- 0
app/Commerce/Checkout.php Voir le fichier

28
     /** Stripe does not accept payments below RM 2.00. */
28
     /** Stripe does not accept payments below RM 2.00. */
29
     public const int MINIMUM_TOTAL = 200;
29
     public const int MINIMUM_TOTAL = 200;
30
 
30
 
31
+    /**
32
+     * How long a shopper has to pay after placing the order. The payment page (Stripe or HitPay) stops taking
33
+     * payments after this, and the double-check gives up on the order a little later (PaymentDoubleCheck).
34
+     */
35
+    public const int PAY_WITHIN_HOURS = 23;
36
+
31
     /** The first order number of every store. */
37
     /** The first order number of every store. */
32
     private const int FIRST_NUMBER = 1001;
38
     private const int FIRST_NUMBER = 1001;
33
 
39
 

+ 160
- 0
app/Commerce/PaymentDoubleCheck.php Voir le fichier

1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Commerce\Payments\PaymentException;
6
+use App\Commerce\Payments\PaymentGateways;
7
+use App\Enums\OrderStatus;
8
+use App\Mail\PaymentReminder;
9
+use App\Models\Order;
10
+use Carbon\CarbonInterface;
11
+use Illuminate\Support\Facades\Mail;
12
+use Throwable;
13
+
14
+/**
15
+ * The double-check for unpaid orders, run every 5 minutes (orders:check-payments).
16
+ *
17
+ * Normally an order is marked paid when the shopper comes back to the store, or when Stripe or HitPay tells our
18
+ * webhook. If both are missed (the shopper closed the phone and the webhook failed, or there is no public https
19
+ * address yet), this asks the provider itself.
20
+ *
21
+ * To stay light, new orders are asked about often and older ones rarely, and nothing is asked after a day:
22
+ * - not before the order is 2 minutes old (most payments are confirmed by then anyway)
23
+ * - every 5 minutes for the first 15 minutes, every 15 minutes until 1 hour, then every hour
24
+ * - after 25 hours the order becomes "Not paid" and is never asked about again. Both payment pages expire
25
+ *   after 23 hours (Checkout::PAY_WITHIN_HOURS), so nobody can pay after that.
26
+ * That is about 30 questions per abandoned order in total, and none for orders that were paid normally.
27
+ *
28
+ * It also sends the "Complete your payment" email, once, about 30 minutes after an order that is still not paid.
29
+ * Not sooner: many shoppers are still on the payment page in the first minutes (scanning a QR code, waiting for a
30
+ * bank code), and an email then would only confuse them. It is sent only after the provider confirms the order is
31
+ * unpaid, and not when the shopper has placed a newer order since (they probably started again).
32
+ */
33
+class PaymentDoubleCheck
34
+{
35
+    public const int FIRST_CHECK_AFTER_MINUTES = 2;
36
+
37
+    public const int GIVE_UP_AFTER_HOURS = 25;
38
+
39
+    public const int REMIND_AFTER_MINUTES = 30;
40
+
41
+    public function __construct(
42
+        private readonly PaymentGateways $gateways,
43
+        private readonly Checkout $checkout,
44
+    ) {}
45
+
46
+    /**
47
+     * @return array{checked: int, paid: int, failed: int, reminded: int, given_up: int}
48
+     */
49
+    public function run(): array
50
+    {
51
+        $result = ['checked' => 0, 'paid' => 0, 'failed' => 0, 'reminded' => 0, 'given_up' => 0];
52
+
53
+        $orders = Order::query()
54
+            ->with('store')
55
+            ->where('status', OrderStatus::Pending)
56
+            ->whereNotNull('payment_checkout_id')
57
+            ->where('created_at', '<=', now()->subMinutes(self::FIRST_CHECK_AFTER_MINUTES))
58
+            ->where('created_at', '>', now()->subHours(self::GIVE_UP_AFTER_HOURS))
59
+            ->lazyById(100);
60
+
61
+        foreach ($orders as $order) {
62
+            $remind = $this->needsReminder($order);
63
+
64
+            if (! $remind && ! self::isDue($order, now())) {
65
+                continue;
66
+            }
67
+
68
+            // Saved before asking, so a provider that is down is not asked again on the very next run.
69
+            $order->payment_checked_at = now();
70
+            $order->saveQuietly();
71
+            $result['checked']++;
72
+
73
+            try {
74
+                if ($this->checkout->markPaid($order, $this->gateways->for($order)->checkPayment($order))) {
75
+                    $result['paid']++;
76
+
77
+                    continue;
78
+                }
79
+            } catch (PaymentException $e) {
80
+                // Not knowing whether they paid, no reminder is sent this time.
81
+                report($e);
82
+                $result['failed']++;
83
+
84
+                continue;
85
+            }
86
+
87
+            if ($remind && $this->remind($order)) {
88
+                $result['reminded']++;
89
+            }
90
+        }
91
+
92
+        // A day later: the shopper gave up.
93
+        $result['given_up'] = Order::query()
94
+            ->where('status', OrderStatus::Pending)
95
+            ->where('created_at', '<=', now()->subHours(self::GIVE_UP_AFTER_HOURS))
96
+            ->update(['status' => OrderStatus::Unpaid, 'updated_at' => now()]);
97
+
98
+        return $result;
99
+    }
100
+
101
+    /**
102
+     * Whether the shopper should get the "Complete your payment" email now: 30 minutes after ordering, once, while
103
+     * there is still at least an hour to pay, and only for their latest order in the store.
104
+     */
105
+    private function needsReminder(Order $order): bool
106
+    {
107
+        if ($order->payment_reminded_at !== null
108
+            || $order->payment_url === null
109
+            || $order->created_at->gt(now()->subMinutes(self::REMIND_AFTER_MINUTES))
110
+            || $order->payment_expires_at === null
111
+            || $order->payment_expires_at->lt(now()->addHour())) {
112
+            return false;
113
+        }
114
+
115
+        return ! Order::query()
116
+            ->where('store_id', $order->store_id)
117
+            ->where('customer_email', $order->customer_email)
118
+            ->where('id', '>', $order->id)
119
+            ->exists();
120
+    }
121
+
122
+    /**
123
+     * Send the reminder. Marked as sent first, so a shopper never gets it twice, even if sending fails.
124
+     */
125
+    private function remind(Order $order): bool
126
+    {
127
+        $order->payment_reminded_at = now();
128
+        $order->saveQuietly();
129
+
130
+        try {
131
+            Mail::to($order->customer_email)->send(new PaymentReminder($order));
132
+        } catch (Throwable $e) {
133
+            report($e);
134
+
135
+            return false;
136
+        }
137
+
138
+        return true;
139
+    }
140
+
141
+    /**
142
+     * Whether it is time to ask about the order again. A little early is fine, because the schedule runs every
143
+     * 5 minutes and never exactly on the second.
144
+     */
145
+    public static function isDue(Order $order, CarbonInterface $now): bool
146
+    {
147
+        if ($order->payment_checked_at === null) {
148
+            return true;
149
+        }
150
+
151
+        $age = $order->created_at->diffInMinutes($now);
152
+        $gap = match (true) {
153
+            $age < 15 => 5,
154
+            $age < 60 => 15,
155
+            default => 60,
156
+        };
157
+
158
+        return $order->payment_checked_at->diffInSeconds($now) >= $gap * 60 - 30;
159
+    }
160
+}

+ 3
- 0
app/Commerce/Payments/HitPay/HitPayGateway.php Voir le fichier

2
 
2
 
3
 namespace App\Commerce\Payments\HitPay;
3
 namespace App\Commerce\Payments\HitPay;
4
 
4
 
5
+use App\Commerce\Checkout;
5
 use App\Commerce\Payments\CheckoutLink;
6
 use App\Commerce\Payments\CheckoutLink;
6
 use App\Commerce\Payments\PaymentException;
7
 use App\Commerce\Payments\PaymentException;
7
 use App\Commerce\Payments\PaymentGateway;
8
 use App\Commerce\Payments\PaymentGateway;
59
             'reference_number' => (string) $order->number,
60
             'reference_number' => (string) $order->number,
60
             'redirect_url' => $successUrl,
61
             'redirect_url' => $successUrl,
61
             'allow_repeated_payments' => 'false',
62
             'allow_repeated_payments' => 'false',
63
+            // The shopper is told this deadline on the order page and in the reminder email.
64
+            'expires_after' => Checkout::PAY_WITHIN_HOURS.' hours',
62
             // The store sends its own email once the order is paid.
65
             // The store sends its own email once the order is paid.
63
             'send_email' => 'false',
66
             'send_email' => 'false',
64
             // HitPay only calls public https addresses, so a development machine relies on the shopper coming back.
67
             // HitPay only calls public https addresses, so a development machine relies on the shopper coming back.

+ 3
- 0
app/Commerce/Payments/StripeGateway.php Voir le fichier

2
 
2
 
3
 namespace App\Commerce\Payments;
3
 namespace App\Commerce\Payments;
4
 
4
 
5
+use App\Commerce\Checkout;
5
 use App\Models\Order;
6
 use App\Models\Order;
6
 use App\Models\OrderItem;
7
 use App\Models\OrderItem;
7
 use App\Models\Store;
8
 use App\Models\Store;
85
                 // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
86
                 // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the shopper back.
86
                 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
87
                 'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
87
                 'cancel_url' => $cancelUrl,
88
                 'cancel_url' => $cancelUrl,
89
+                // The shopper is told this deadline on the order page and in the reminder email. Stripe's default is 24 hours.
90
+                'expires_at' => ($order->payment_expires_at ?? now()->addHours(Checkout::PAY_WITHIN_HOURS))->getTimestamp(),
88
             ], $in);
91
             ], $in);
89
         } catch (ApiErrorException $e) {
92
         } catch (ApiErrorException $e) {
90
             throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);
93
             throw new PaymentException('Stripe could not create the payment page: '.$e->getMessage(), 0, $e);

+ 22
- 0
app/Console/Commands/CheckOrderPayments.php Voir le fichier

1
+<?php
2
+
3
+namespace App\Console\Commands;
4
+
5
+use App\Commerce\PaymentDoubleCheck;
6
+use Illuminate\Console\Attributes\Description;
7
+use Illuminate\Console\Attributes\Signature;
8
+use Illuminate\Console\Command;
9
+
10
+#[Signature('orders:check-payments')]
11
+#[Description('Ask Stripe and HitPay about orders still awaiting payment, in case a payment was missed')]
12
+class CheckOrderPayments extends Command
13
+{
14
+    public function handle(PaymentDoubleCheck $doubleCheck): int
15
+    {
16
+        $result = $doubleCheck->run();
17
+
18
+        $this->info("Checked {$result['checked']} unpaid orders: {$result['paid']} were paid, {$result['failed']} could not be checked, {$result['reminded']} shoppers reminded by email. {$result['given_up']} marked not paid after a day.");
19
+
20
+        return self::SUCCESS;
21
+    }
22
+}

+ 7
- 0
app/Enums/OrderStatus.php Voir le fichier

9
 
9
 
10
     case Paid = 'paid';
10
     case Paid = 'paid';
11
 
11
 
12
+    /**
13
+     * Still not paid a day later: the shopper gave up. The double-check stops asking about it.
14
+     * A payment that still arrives (from the webhook or the shopper's return page) marks it paid.
15
+     */
16
+    case Unpaid = 'unpaid';
17
+
12
     public function label(): string
18
     public function label(): string
13
     {
19
     {
14
         return match ($this) {
20
         return match ($this) {
15
             self::Pending => 'Awaiting payment',
21
             self::Pending => 'Awaiting payment',
16
             self::Paid => 'Paid',
22
             self::Paid => 'Paid',
23
+            self::Unpaid => 'Not paid',
17
         };
24
         };
18
     }
25
     }
19
 }
26
 }

+ 12
- 1
app/Http/Controllers/CartController.php Voir le fichier

21
 
21
 
22
     public function show(Request $request): Response
22
     public function show(Request $request): Response
23
     {
23
     {
24
-        return $this->renderStorefront($request, $this->storefront($request), ['type' => 'cart']);
24
+        $storefront = $this->storefront($request);
25
+        $unpaid = $this->cart($request, $storefront->store)->unpaidOrder();
26
+
27
+        return $this->renderStorefront($request, $storefront, [
28
+            'type' => 'cart',
29
+            // An order this shopper placed in this browser and left on the payment page, so they can finish paying.
30
+            'unpaidOrder' => $unpaid === null ? null : [
31
+                'number' => $unpaid->number,
32
+                'public_id' => $unpaid->public_id,
33
+                'expires_at' => $unpaid->payment_expires_at?->toIso8601String(),
34
+            ],
35
+        ]);
25
     }
36
     }
26
 
37
 
27
     /**
38
     /**

+ 47
- 10
app/Http/Controllers/CheckoutController.php Voir le fichier

94
         unset($details['pay_with']);
94
         unset($details['pay_with']);
95
 
95
 
96
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
96
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
97
+        // Set before the payment page is made, so the page and what the shopper is told end at the same time.
98
+        $order->payment_expires_at = now()->addHours(Checkout::PAY_WITHIN_HOURS);
97
 
99
 
98
         try {
100
         try {
99
             $link = $gateway->startCheckout(
101
             $link = $gateway->startCheckout(
112
 
114
 
113
         $order->payment_provider = $gateway->name();
115
         $order->payment_provider = $gateway->name();
114
         $order->payment_checkout_id = $link->id;
116
         $order->payment_checkout_id = $link->id;
117
+        $order->payment_url = $link->url;
115
         $order->payment_account = $link->account;
118
         $order->payment_account = $link->account;
116
         $order->save();
119
         $order->save();
117
 
120
 
121
+        // So the cart page can offer "Complete payment" if the shopper leaves the payment page.
122
+        $this->cart($request, $store)->rememberUnpaidOrder($order);
123
+
118
         // The payment page is on another website, so this is a full browser redirect.
124
         // The payment page is on another website, so this is a full browser redirect.
119
         return Inertia::location($link->url);
125
         return Inertia::location($link->url);
120
     }
126
     }
127
         $storefront = $this->storefront($request);
133
         $storefront = $this->storefront($request);
128
         $store = $storefront->store;
134
         $store = $storefront->store;
129
 
135
 
136
+        $order = $this->findOrder($request, $checkout, $gateways);
137
+
138
+        if ($order->isPaid()) {
139
+            $this->cart($request, $store)->clear();
140
+        }
141
+
142
+        return $this->renderStorefront($request, $storefront, [
143
+            'type' => 'order',
144
+            'order' => $order->toDisplay(),
145
+            // "Complete payment" while the payment page still takes payments; "closed" once it no longer does.
146
+            'payment' => $order->isPaid() || $order->payment_expires_at === null ? null : [
147
+                'can_pay' => $order->canStillPay(),
148
+                'expires_at' => $order->payment_expires_at->toIso8601String(),
149
+            ],
150
+        ]);
151
+    }
152
+
153
+    /**
154
+     * "Complete payment": back to the same payment page, for a shopper who left it. Used by the order page, the
155
+     * cart page and the reminder email. Asks the provider first, so a shopper who already paid sees the thank-you.
156
+     */
157
+    public function pay(Request $request, Checkout $checkout, PaymentGateways $gateways): HttpResponse
158
+    {
159
+        $storefront = $this->storefront($request);
160
+        $order = $this->findOrder($request, $checkout, $gateways);
161
+
162
+        if (! $order->canStillPay()) {
163
+            return redirect($storefront->path('/orders/'.$order->public_id));
164
+        }
165
+
166
+        // The payment page is on another website, so this is a full browser redirect.
167
+        return Inertia::location((string) $order->payment_url);
168
+    }
169
+
170
+    /**
171
+     * The order in the address, marked paid first if the provider says it was. Nothing in the web address is trusted.
172
+     */
173
+    private function findOrder(Request $request, Checkout $checkout, PaymentGateways $gateways): Order
174
+    {
130
         /** @var Order $order */
175
         /** @var Order $order */
131
-        $order = $store->orders()->with('items')->where('public_id', (string) $request->route('publicId'))->firstOrFail();
176
+        $order = $this->storefront($request)->store->orders()->with('items')->where('public_id', (string) $request->route('publicId'))->firstOrFail();
132
 
177
 
133
-        // Ask the payment provider directly. Nothing in the web address is trusted.
134
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
178
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
135
             try {
179
             try {
136
                 $checkout->markPaid($order, $gateways->for($order)->checkPayment($order));
180
                 $checkout->markPaid($order, $gateways->for($order)->checkPayment($order));
139
             }
183
             }
140
         }
184
         }
141
 
185
 
142
-        if ($order->isPaid()) {
143
-            $this->cart($request, $store)->clear();
144
-        }
145
-
146
-        return $this->renderStorefront($request, $storefront, [
147
-            'type' => 'order',
148
-            'order' => $order->toDisplay(),
149
-        ]);
186
+        return $order;
150
     }
187
     }
151
 }
188
 }

+ 59
- 0
app/Mail/PaymentReminder.php Voir le fichier

1
+<?php
2
+
3
+namespace App\Mail;
4
+
5
+use App\Models\Order;
6
+use Illuminate\Bus\Queueable;
7
+use Illuminate\Mail\Mailable;
8
+use Illuminate\Mail\Mailables\Address;
9
+use Illuminate\Mail\Mailables\Content;
10
+use Illuminate\Mail\Mailables\Envelope;
11
+use Illuminate\Queue\SerializesModels;
12
+
13
+/**
14
+ * "Complete your payment": sent once to a shopper who placed an order but left the payment page without paying
15
+ * (PaymentDoubleCheck). Written in the store's language.
16
+ */
17
+class PaymentReminder extends Mailable
18
+{
19
+    use Queueable, SerializesModels;
20
+
21
+    public function __construct(public Order $order) {}
22
+
23
+    public function envelope(): Envelope
24
+    {
25
+        $store = $this->order->store;
26
+
27
+        return new Envelope(
28
+            // Sent from our address (so it is delivered), but under the store's name, with replies going to the store.
29
+            from: new Address((string) config('mail.from.address'), $store->name),
30
+            replyTo: $store->contact_email !== null ? [new Address($store->contact_email, $store->name)] : [],
31
+            subject: $store->language->value === 'ms'
32
+                ? "Lengkapkan bayaran untuk pesanan #{$this->order->number} - {$store->name}"
33
+                : "Complete your payment for order #{$this->order->number} - {$store->name}",
34
+        );
35
+    }
36
+
37
+    public function content(): Content
38
+    {
39
+        $store = $this->order->store;
40
+        $brand = StoreBrand::for($store);
41
+
42
+        return new Content(
43
+            // In the store's own colours, fonts and corners, so shoppers see the shop they ordered from.
44
+            view: 'mail.orders.payment-reminder',
45
+            text: 'mail.orders.payment-reminder-text',
46
+            with: [
47
+                'order' => $this->order->loadMissing('items'),
48
+                'store' => $store,
49
+                'brand' => $brand,
50
+                'payUrl' => $brand->payUrl($this->order),
51
+                'orderUrl' => $brand->orderUrl($this->order),
52
+                'deadline' => $this->order->payment_expires_at
53
+                    ?->timezone('Asia/Kuala_Lumpur')
54
+                    ->locale($brand->malay ? 'ms' : 'en')
55
+                    ->translatedFormat('j F, g:i a'),
56
+            ],
57
+        );
58
+    }
59
+}

+ 12
- 0
app/Mail/StoreBrand.php Voir le fichier

135
         return $this->storeUrl().'/orders/'.$order->public_id;
135
         return $this->storeUrl().'/orders/'.$order->public_id;
136
     }
136
     }
137
 
137
 
138
+    /**
139
+     * "Complete payment": back to the order's payment page, after checking it was not paid meanwhile.
140
+     */
141
+    public function payUrl(Order $order): string
142
+    {
143
+        if (! $this->store->isPublished()) {
144
+            return route('stores.preview.order.pay', [$this->store->slug, $order->public_id]);
145
+        }
146
+
147
+        return $this->storeUrl().'/orders/'.$order->public_id.'/pay';
148
+    }
149
+
138
     /**
150
     /**
139
      * The store's own home page.
151
      * The store's own home page.
140
      */
152
      */

+ 20
- 0
app/Models/Order.php Voir le fichier

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_url The provider's payment page, so the shopper can come back to it
39
+ * @property CarbonInterface|null $payment_expires_at When the payment page stops taking payments
38
  * @property string|null $payment_account The merchant's Stripe account the order was paid into (null: our own account)
40
  * @property string|null $payment_account The merchant's Stripe account the order was paid into (null: our own account)
39
  * @property string|null $payment_reference
41
  * @property string|null $payment_reference
42
+ * @property CarbonInterface|null $payment_checked_at When the double-check last asked the provider (PaymentDoubleCheck)
43
+ * @property CarbonInterface|null $payment_reminded_at When the shopper was emailed "Complete your payment"
40
  * @property CarbonInterface|null $paid_at
44
  * @property CarbonInterface|null $paid_at
41
  * @property CarbonInterface|null $shipped_at
45
  * @property CarbonInterface|null $shipped_at
42
  * @property string|null $shipping_courier
46
  * @property string|null $shipping_courier
77
         return $this->status === OrderStatus::Paid;
81
         return $this->status === OrderStatus::Paid;
78
     }
82
     }
79
 
83
 
84
+    /**
85
+     * Whether the shopper can still go back to the payment page and pay: not paid yet, and the page has not expired.
86
+     */
87
+    public function canStillPay(): bool
88
+    {
89
+        return $this->status === OrderStatus::Pending
90
+            && $this->payment_url !== null
91
+            && $this->payment_expires_at?->isFuture() === true;
92
+    }
93
+
80
     /**
94
     /**
81
      * The order as shown to people. Money is in ringgit here.
95
      * The order as shown to people. Money is in ringgit here.
82
      *
96
      *
101
             'shipping_total' => $this->shipping_total / 100,
115
             'shipping_total' => $this->shipping_total / 100,
102
             'total' => $this->total / 100,
116
             'total' => $this->total / 100,
103
             'paid_at' => $this->paid_at?->toIso8601String(),
117
             'paid_at' => $this->paid_at?->toIso8601String(),
118
+            // Until when the shopper can pay, and when they were reminded by email. Null for older orders.
119
+            'payment_expires_at' => $this->payment_expires_at?->toIso8601String(),
120
+            'payment_reminded_at' => $this->payment_reminded_at?->toIso8601String(),
104
             'shipped_at' => $this->shipped_at?->toIso8601String(),
121
             'shipped_at' => $this->shipped_at?->toIso8601String(),
105
             'shipping_courier' => $this->shipping_courier,
122
             'shipping_courier' => $this->shipping_courier,
106
             'tracking_number' => $this->tracking_number,
123
             'tracking_number' => $this->tracking_number,
130
     {
147
     {
131
         return [
148
         return [
132
             'status' => OrderStatus::class,
149
             'status' => OrderStatus::class,
150
+            'payment_expires_at' => 'datetime',
151
+            'payment_checked_at' => 'datetime',
152
+            'payment_reminded_at' => 'datetime',
133
             'shipping_address' => 'array',
153
             'shipping_address' => 'array',
134
             'paid_at' => 'datetime',
154
             'paid_at' => 'datetime',
135
             'shipped_at' => 'datetime',
155
             'shipped_at' => 'datetime',

+ 4
- 0
app/Providers/AppServiceProvider.php Voir le fichier

12
 use App\Commerce\Shipping\FlatRateShipping;
12
 use App\Commerce\Shipping\FlatRateShipping;
13
 use App\Commerce\Shipping\ShippingProvider;
13
 use App\Commerce\Shipping\ShippingProvider;
14
 use Carbon\CarbonImmutable;
14
 use Carbon\CarbonImmutable;
15
+use Illuminate\Foundation\DevCommands;
15
 use Illuminate\Support\Facades\Date;
16
 use Illuminate\Support\Facades\Date;
16
 use Illuminate\Support\Facades\DB;
17
 use Illuminate\Support\Facades\DB;
17
 use Illuminate\Support\ServiceProvider;
18
 use Illuminate\Support\ServiceProvider;
39
     public function boot(): void
40
     public function boot(): void
40
     {
41
     {
41
         $this->configureDefaults();
42
         $this->configureDefaults();
43
+
44
+        // `composer run dev` also runs the scheduler, so the double-check for unpaid orders runs on this machine too.
45
+        DevCommands::artisan('schedule:work', 'scheduler');
42
     }
46
     }
43
 
47
 
44
     /**
48
     /**

+ 26
- 0
database/migrations/2026_12_02_000003_add_payment_checked_at_to_orders.php Voir le fichier

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('orders', function (Blueprint $table) {
12
+            // When the double-check last asked the payment provider about this unpaid order (orders:check-payments).
13
+            $table->timestamp('payment_checked_at')->nullable()->after('payment_reference');
14
+            // The double-check looks for unpaid orders by age, across all stores.
15
+            $table->index(['status', 'created_at']);
16
+        });
17
+    }
18
+
19
+    public function down(): void
20
+    {
21
+        Schema::table('orders', function (Blueprint $table) {
22
+            $table->dropIndex(['status', 'created_at']);
23
+            $table->dropColumn('payment_checked_at');
24
+        });
25
+    }
26
+};

+ 27
- 0
database/migrations/2026_12_03_000001_add_payment_link_to_orders.php Voir le fichier

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('orders', function (Blueprint $table) {
12
+            // The provider's payment page, so a shopper who left it can come back and pay ("Complete payment").
13
+            $table->text('payment_url')->nullable()->after('payment_checkout_id');
14
+            // When that page stops taking payments (Checkout::PAY_WITHIN_HOURS after the order).
15
+            $table->timestamp('payment_expires_at')->nullable()->after('payment_url');
16
+            // When the shopper was emailed a "Complete your payment" reminder (PaymentDoubleCheck).
17
+            $table->timestamp('payment_reminded_at')->nullable()->after('payment_checked_at');
18
+        });
19
+    }
20
+
21
+    public function down(): void
22
+    {
23
+        Schema::table('orders', function (Blueprint $table) {
24
+            $table->dropColumn(['payment_url', 'payment_expires_at', 'payment_reminded_at']);
25
+        });
26
+    }
27
+};

+ 23
- 0
resources/js/pages/stores/orders/show.tsx Voir le fichier

71
                             ? ` · Paid ${formatDateTime(order.paid_at)}`
71
                             ? ` · Paid ${formatDateTime(order.paid_at)}`
72
                             : ''}
72
                             : ''}
73
                     </p>
73
                     </p>
74
+                    {order.status === 'pending' && (
75
+                        <p
76
+                            className="mt-4 rounded-md bg-muted p-3 text-sm"
77
+                            data-test="order-waiting"
78
+                        >
79
+                            Waiting for the shopper to pay.
80
+                            {order.payment_expires_at &&
81
+                                ` They can pay until ${formatDateTime(order.payment_expires_at)}.`}
82
+                            {order.payment_reminded_at &&
83
+                                ` We emailed them a reminder on ${formatDateTime(order.payment_reminded_at)}.`}{' '}
84
+                            Stock is only taken once they pay.
85
+                        </p>
86
+                    )}
87
+                    {order.status === 'unpaid' && (
88
+                        <p
89
+                            className="mt-4 rounded-md bg-muted p-3 text-sm"
90
+                            data-test="order-not-paid"
91
+                        >
92
+                            The shopper did not pay in time, so this order is
93
+                            closed. You don’t need to do anything: no money was
94
+                            taken and your stock did not change.
95
+                        </p>
96
+                    )}
74
                 </div>
97
                 </div>
75
 
98
 
76
                 <Card>
99
                 <Card>

+ 38
- 4
resources/js/storefront/pages/cart.tsx Voir le fichier

4
 import type { FormEvent } from 'react';
4
 import type { FormEvent } from 'react';
5
 import { useStorefront } from '../context';
5
 import { useStorefront } from '../context';
6
 import { ProductImage } from '../product-card';
6
 import { ProductImage } from '../product-card';
7
-import { storefrontText } from '../text';
7
+import { formatDeadline, storefrontText } from '../text';
8
 import { formatPrice } from '../theme';
8
 import { formatPrice } from '../theme';
9
-import type { CartLine } from '../types';
9
+import type { CartLine, UnpaidOrder } from '../types';
10
 import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
10
 import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
11
 
11
 
12
-/** The shopper's cart. Built by us, in the store's colours and fonts. */
13
-export function CartPage() {
12
+/**
13
+ * The shopper's cart. Built by us, in the store's colours and fonts.
14
+ * When this shopper left the payment page without paying, a note at the top takes them back to it.
15
+ */
16
+export function CartPage({ unpaidOrder }: { unpaidOrder: UnpaidOrder | null }) {
14
     const { cart, language, baseUrl, shop } = useStorefront();
17
     const { cart, language, baseUrl, shop } = useStorefront();
15
 
18
 
16
     const t = storefrontText(language);
19
     const t = storefrontText(language);
45
                     {t.yourCart}
48
                     {t.yourCart}
46
                 </h1>
49
                 </h1>
47
 
50
 
51
+                {unpaidOrder && (
52
+                    <div
53
+                        role="status"
54
+                        data-test="unpaid-order"
55
+                        className="mt-6 flex flex-col gap-4 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-4 text-sm sm:flex-row sm:items-center sm:justify-between sm:p-5"
56
+                    >
57
+                        <p>
58
+                            <span className="font-medium">
59
+                                {t.unpaidOrderBanner(unpaidOrder.number)}
60
+                            </span>
61
+                            {unpaidOrder.expires_at && (
62
+                                <span className="text-(--sf-muted)">
63
+                                    {' '}
64
+                                    {t.unpaidOrderDeadline(
65
+                                        formatDeadline(
66
+                                            unpaidOrder.expires_at,
67
+                                            language,
68
+                                        ),
69
+                                    )}
70
+                                </span>
71
+                            )}
72
+                        </p>
73
+                        <SfButton
74
+                            href={`/orders/${unpaidOrder.public_id}/pay`}
75
+                            className="shrink-0"
76
+                        >
77
+                            {t.completePayment}
78
+                        </SfButton>
79
+                    </div>
80
+                )}
81
+
48
                 {cart.adjusted && (
82
                 {cart.adjusted && (
49
                     <p
83
                     <p
50
                         role="status"
84
                         role="status"

+ 47
- 10
resources/js/storefront/pages/order.tsx Voir le fichier

1
 import { useStorefront } from '../context';
1
 import { useStorefront } from '../context';
2
-import { storefrontText } from '../text';
2
+import { formatDeadline, storefrontText } from '../text';
3
 import { formatPrice } from '../theme';
3
 import { formatPrice } from '../theme';
4
-import type { StoreOrder } from '../types';
4
+import type { OrderPayment, StoreOrder } from '../types';
5
 import { Container, SfButton } from '../ui';
5
 import { Container, SfButton } from '../ui';
6
 import { whatsappLink } from '../whatsapp';
6
 import { whatsappLink } from '../whatsapp';
7
 
7
 
8
-/** Where the shopper lands after the payment page: a thank-you, or a "not paid yet" notice. */
9
-export function OrderPage({ order }: { order: StoreOrder }) {
10
-    const { language, shop, storeName } = useStorefront();
8
+/**
9
+ * Where the shopper lands after the payment page, and where the reminder email leads: a thank-you, a
10
+ * "Complete payment" button with the deadline, or a notice that the time to pay is over.
11
+ */
12
+export function OrderPage({
13
+    order,
14
+    payment,
15
+}: {
16
+    order: StoreOrder;
17
+    payment: OrderPayment | null;
18
+}) {
19
+    const { language, shop, storeName, cart } = useStorefront();
11
     const t = storefrontText(language);
20
     const t = storefrontText(language);
12
     const paid = order.status === 'paid';
21
     const paid = order.status === 'paid';
22
+    const canPay = !paid && payment?.can_pay === true;
23
+    const closed = !paid && payment !== null && !payment.can_pay;
13
     const address = order.shipping_address;
24
     const address = order.shipping_address;
14
 
25
 
15
     return (
26
     return (
16
         <main className="py-12 md:py-16">
27
         <main className="py-12 md:py-16">
17
             <Container className="max-w-3xl">
28
             <Container className="max-w-3xl">
18
                 <h1 className="sf-heading text-4xl font-semibold sm:text-5xl">
29
                 <h1 className="sf-heading text-4xl font-semibold sm:text-5xl">
19
-                    {paid ? t.thankYou : t.orderPendingTitle}
30
+                    {paid
31
+                        ? t.thankYou
32
+                        : closed
33
+                          ? t.orderClosedTitle
34
+                          : t.orderPendingTitle}
20
                 </h1>
35
                 </h1>
21
                 <p className="mt-4 text-(--sf-muted)" role="status">
36
                 <p className="mt-4 text-(--sf-muted)" role="status">
22
                     {paid
37
                     {paid
23
                         ? t.orderPaid(order.number, order.customer_email)
38
                         ? t.orderPaid(order.number, order.customer_email)
24
-                        : t.orderPending(order.number)}
39
+                        : canPay
40
+                          ? t.payBy(
41
+                                order.number,
42
+                                formatDeadline(payment.expires_at, language),
43
+                            )
44
+                          : closed
45
+                            ? t.orderClosed(order.number)
46
+                            : t.orderPending(order.number)}
25
                 </p>
47
                 </p>
48
+                {canPay && (
49
+                    <SfButton
50
+                        href={`/orders/${order.public_id}/pay`}
51
+                        className="mt-6"
52
+                    >
53
+                        {t.completePayment}
54
+                    </SfButton>
55
+                )}
26
 
56
 
27
                 <div className="sf-card mt-10 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
57
                 <div className="sf-card mt-10 rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
28
                     <h2 className="font-medium">{t.orderSummary}</h2>
58
                     <h2 className="font-medium">{t.orderSummary}</h2>
111
                 )}
141
                 )}
112
 
142
 
113
                 <div className="mt-8 flex flex-wrap items-center gap-3">
143
                 <div className="mt-8 flex flex-wrap items-center gap-3">
114
-                    <SfButton href={paid ? '/shop' : '/cart'}>
115
-                        {paid ? t.continueShopping : t.backToCart}
116
-                    </SfButton>
144
+                    {paid || (closed && cart.lines.length === 0) ? (
145
+                        <SfButton href="/shop">{t.continueShopping}</SfButton>
146
+                    ) : (
147
+                        <SfButton
148
+                            href="/cart"
149
+                            variant={canPay ? 'outline' : 'primary'}
150
+                        >
151
+                            {t.backToCart}
152
+                        </SfButton>
153
+                    )}
117
                     {shop.whatsapp && (
154
                     {shop.whatsapp && (
118
                         <a
155
                         <a
119
                             href={whatsappLink(
156
                             href={whatsappLink(

+ 2
- 2
resources/js/storefront/renderer.tsx Voir le fichier

86
     }
86
     }
87
 
87
 
88
     if (view.type === 'cart') {
88
     if (view.type === 'cart') {
89
-        return <CartPage />;
89
+        return <CartPage unpaidOrder={view.unpaidOrder ?? null} />;
90
     }
90
     }
91
 
91
 
92
     if (view.type === 'checkout') {
92
     if (view.type === 'checkout') {
101
     }
101
     }
102
 
102
 
103
     if (view.type === 'order') {
103
     if (view.type === 'order') {
104
-        return <OrderPage order={view.order} />;
104
+        return <OrderPage order={view.order} payment={view.payment ?? null} />;
105
     }
105
     }
106
 
106
 
107
     if (view.type === 'product') {
107
     if (view.type === 'product') {

+ 29
- 0
resources/js/storefront/text.ts Voir le fichier

93
         orderPendingTitle: 'Payment not completed',
93
         orderPendingTitle: 'Payment not completed',
94
         orderPending: (number: number) =>
94
         orderPending: (number: number) =>
95
             `Order #${number} has not been paid yet. Your cart is still saved, so you can try again.`,
95
             `Order #${number} has not been paid yet. Your cart is still saved, so you can try again.`,
96
+        completePayment: 'Complete payment',
97
+        payBy: (number: number, deadline: string) =>
98
+            `Order #${number} has not been paid yet. You can still pay until ${deadline}. After that the order is closed.`,
99
+        orderClosedTitle: 'Payment time is over',
100
+        orderClosed: (number: number) =>
101
+            `Order #${number} was not paid in time, so it is closed. You were not charged. To buy these items, please order again.`,
102
+        unpaidOrderBanner: (number: number) =>
103
+            `You have an unpaid order #${number}.`,
104
+        unpaidOrderDeadline: (deadline: string) => `Pay by ${deadline}.`,
96
         deliverTo: 'Deliver to',
105
         deliverTo: 'Deliver to',
97
         quantityShort: 'Qty',
106
         quantityShort: 'Qty',
98
         discountCode: 'Discount code',
107
         discountCode: 'Discount code',
215
         orderPendingTitle: 'Pembayaran belum selesai',
224
         orderPendingTitle: 'Pembayaran belum selesai',
216
         orderPending: (number: number) =>
225
         orderPending: (number: number) =>
217
             `Pesanan #${number} belum dibayar. Troli anda masih disimpan, jadi anda boleh cuba lagi.`,
226
             `Pesanan #${number} belum dibayar. Troli anda masih disimpan, jadi anda boleh cuba lagi.`,
227
+        completePayment: 'Lengkapkan bayaran',
228
+        payBy: (number: number, deadline: string) =>
229
+            `Pesanan #${number} belum dibayar. Anda masih boleh membayar sehingga ${deadline}. Selepas itu pesanan akan ditutup.`,
230
+        orderClosedTitle: 'Masa bayaran telah tamat',
231
+        orderClosed: (number: number) =>
232
+            `Pesanan #${number} tidak dibayar dalam masa yang ditetapkan, jadi ia telah ditutup. Anda tidak dicaj. Untuk membeli item ini, sila buat pesanan semula.`,
233
+        unpaidOrderBanner: (number: number) =>
234
+            `Anda ada pesanan #${number} yang belum dibayar.`,
235
+        unpaidOrderDeadline: (deadline: string) => `Bayar sebelum ${deadline}.`,
218
         deliverTo: 'Hantar ke',
236
         deliverTo: 'Hantar ke',
219
         quantityShort: 'Kuantiti',
237
         quantityShort: 'Kuantiti',
220
         discountCode: 'Kod diskaun',
238
         discountCode: 'Kod diskaun',
253
 export function storefrontText(language: string): StorefrontWords {
271
 export function storefrontText(language: string): StorefrontWords {
254
     return language === 'ms' ? words.ms : words.en;
272
     return language === 'ms' ? words.ms : words.en;
255
 }
273
 }
274
+
275
+/** "4 Dec, 3:15 pm", in Malaysian time, for payment deadlines. */
276
+export function formatDeadline(iso: string, language: string): string {
277
+    return new Date(iso).toLocaleString(language === 'ms' ? 'ms-MY' : 'en-MY', {
278
+        day: 'numeric',
279
+        month: 'short',
280
+        hour: 'numeric',
281
+        minute: '2-digit',
282
+        timeZone: 'Asia/Kuala_Lumpur',
283
+    });
284
+}

+ 16
- 3
resources/js/storefront/types.ts Voir le fichier

333
     id: number;
333
     id: number;
334
     public_id: string;
334
     public_id: string;
335
     number: number;
335
     number: number;
336
-    status: 'pending' | 'paid';
336
+    status: 'pending' | 'paid' | 'unpaid';
337
     status_label: string;
337
     status_label: string;
338
     customer_name: string;
338
     customer_name: string;
339
     customer_email: string;
339
     customer_email: string;
347
     shipping_total: number;
347
     shipping_total: number;
348
     total: number;
348
     total: number;
349
     paid_at: string | null;
349
     paid_at: string | null;
350
+    /** Until when the shopper can pay. Null for older orders. */
351
+    payment_expires_at: string | null;
352
+    payment_reminded_at: string | null;
350
     shipped_at: string | null;
353
     shipped_at: string | null;
351
     shipping_courier: string | null;
354
     shipping_courier: string | null;
352
     tracking_number: string | null;
355
     tracking_number: string | null;
395
 /** One way to pay at checkout: a payment provider and the methods on its page. */
398
 /** One way to pay at checkout: a payment provider and the methods on its page. */
396
 export type PayWay = { key: string; methods: PayMethod[] };
399
 export type PayWay = { key: string; methods: PayMethod[] };
397
 
400
 
401
+/** An order this shopper placed in this browser and has not paid yet, shown on the cart page. */
402
+export type UnpaidOrder = {
403
+    number: number;
404
+    public_id: string;
405
+    expires_at: string | null;
406
+};
407
+
408
+/** For an unpaid order: whether the shopper can still go back to the payment page, and until when. */
409
+export type OrderPayment = { can_pay: boolean; expires_at: string };
410
+
398
 /** Which storefront page to show. */
411
 /** Which storefront page to show. */
399
 export type StorefrontView =
412
 export type StorefrontView =
400
     | { type: 'page'; pageId: string }
413
     | { type: 'page'; pageId: string }
401
     | { type: 'shop' }
414
     | { type: 'shop' }
402
-    | { type: 'cart' }
415
+    | { type: 'cart'; unpaidOrder?: UnpaidOrder | null }
403
     | {
416
     | {
404
           type: 'checkout';
417
           type: 'checkout';
405
           states: string[];
418
           states: string[];
410
           /** The ways to pay, for the shopper to choose. */
423
           /** The ways to pay, for the shopper to choose. */
411
           payWays: PayWay[];
424
           payWays: PayWay[];
412
       }
425
       }
413
-    | { type: 'order'; order: StoreOrder }
426
+    | { type: 'order'; order: StoreOrder; payment?: OrderPayment | null }
414
     | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }
427
     | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }
415
     | {
428
     | {
416
           type: 'collection';
429
           type: 'collection';

+ 5
- 1
resources/js/types/store.ts Voir le fichier

108
     id: number;
108
     id: number;
109
     public_id: string;
109
     public_id: string;
110
     number: number;
110
     number: number;
111
-    status: 'pending' | 'paid';
111
+    status: 'pending' | 'paid' | 'unpaid';
112
     status_label: string;
112
     status_label: string;
113
     customer_name: string;
113
     customer_name: string;
114
     customer_email: string;
114
     customer_email: string;
128
     shipping_total: number;
128
     shipping_total: number;
129
     total: number;
129
     total: number;
130
     paid_at: string | null;
130
     paid_at: string | null;
131
+    /** Until when the shopper can pay. Null for older orders. */
132
+    payment_expires_at: string | null;
133
+    /** When the shopper was emailed "Complete your payment". */
134
+    payment_reminded_at: string | null;
131
     shipped_at: string | null;
135
     shipped_at: string | null;
132
     shipping_courier: string | null;
136
     shipping_courier: string | null;
133
     tracking_number: string | null;
137
     tracking_number: string | null;

+ 26
- 0
resources/views/mail/orders/payment-reminder-text.blade.php Voir le fichier

1
+@php($m = $brand->malay)
2
+{!! $m ? 'Lengkapkan bayaran anda' : 'Complete your payment' !!}
3
+
4
+{!! $m ? 'Hai' : 'Hi' !!} {!! $order->customer_name !!},
5
+
6
+{!! $m ? "Pesanan #{$order->number} daripada ".rtrim($store->name, '.')." belum dibayar. Barang anda masih menunggu." : "Your order #{$order->number} from ".rtrim($store->name, '.')." has not been paid yet. Your items are still waiting." !!}
7
+
8
+{!! $m ? 'Lengkapkan bayaran' : 'Complete payment' !!}: {!! $payUrl !!}
9
+@if ($deadline)
10
+{!! $m ? "Anda boleh membayar sehingga {$deadline}. Selepas itu pesanan akan ditutup dan anda tidak akan dicaj." : "You can pay until {$deadline}. After that the order is closed and you will not be charged." !!}
11
+@endif
12
+
13
+@foreach ($order->items as $item)
14
+- {!! $item->name !!} × {!! $item->quantity !!}: {!! $brand->money($item->line_total) !!}
15
+@endforeach
16
+{!! $m ? 'Jumlah perlu dibayar' : 'Total to pay' !!}: {!! $brand->money($order->total) !!}
17
+
18
+{!! $m ? 'Sudah membayar? Abaikan e-mel ini.' : 'Already paid? You can ignore this email.' !!}
19
+{!! $m ? 'Lihat pesanan anda' : 'View your order' !!}: {!! $orderUrl !!}
20
+
21
+{!! $m ? 'Terima kasih,' : 'Thanks,' !!}
22
+{!! $store->name !!}
23
+@if ($brand->contactEmail())
24
+
25
+{!! $m ? 'Ada soalan? Balas e-mel ini atau tulis kepada' : 'Questions? Reply to this email or write to' !!} {!! $brand->contactEmail() !!}
26
+@endif

+ 49
- 0
resources/views/mail/orders/payment-reminder.blade.php Voir le fichier

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
+@endphp
6
+<x-mail.store :brand="$brand" :preheader="$m ? 'Pesanan #'.$order->number.' menunggu bayaran anda.' : 'Order #'.$order->number.' is waiting for your payment.'">
7
+    <h1 style="margin: 0 0 16px; font-family: {{ $brand->headingFont }}; font-size: 26px; line-height: 1.25; font-weight: 700; color: {{ $brand->color('foreground') }};">
8
+        {{ $m ? 'Lengkapkan bayaran anda' : 'Complete your payment' }}
9
+    </h1>
10
+    <p style="margin: 0 0 12px;">{{ $m ? 'Hai' : 'Hi' }} {{ $order->customer_name }},</p>
11
+    <p style="margin: 0 0 24px;">
12
+        {{ $m
13
+            ? "Pesanan #{$order->number} daripada ".rtrim($store->name, '.')." belum dibayar. Barang anda masih menunggu. Klik butang di bawah untuk kembali ke halaman bayaran."
14
+            : "Your order #{$order->number} from ".rtrim($store->name, '.')." has not been paid yet. Your items are still waiting. Click the button below to go back to the payment page." }}
15
+    </p>
16
+
17
+    {{-- Button --}}
18
+    <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 12px;">
19
+        <tr>
20
+            <td class="sf-cell"><x-mail.store-button :brand="$brand" :href="$payUrl">{{ $m ? 'Lengkapkan bayaran' : 'Complete payment' }}</x-mail.store-button></td>
21
+        </tr>
22
+    </table>
23
+    @if ($deadline)
24
+        <p style="margin: 0 0 28px; font-size: 13px; color: {{ $brand->color('muted') }};">
25
+            {{ $m ? "Anda boleh membayar sehingga {$deadline}. Selepas itu pesanan akan ditutup dan anda tidak akan dicaj." : "You can pay until {$deadline}. After that the order is closed and you will not be charged." }}
26
+        </p>
27
+    @endif
28
+
29
+    {{-- What was ordered --}}
30
+    <div style="{{ $label }} margin: 0 0 6px;">{{ $m ? 'Pesanan anda' : 'Your order' }}</div>
31
+    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 0 0 28px; border-top: 1px solid {{ $brand->color('border') }};">
32
+        @foreach ($order->items as $item)
33
+            <tr>
34
+                <td style="{{ $line }} padding: 10px 12px 10px 0;">{{ $item->name }} <span style="color: {{ $brand->color('muted') }};">× {{ $item->quantity }}</span></td>
35
+                <td align="right" style="{{ $line }} padding: 10px 0; white-space: nowrap;">{{ $brand->money($item->line_total) }}</td>
36
+            </tr>
37
+        @endforeach
38
+        <tr>
39
+            <td style="padding: 14px 0 0; font-weight: 700;">{{ $m ? 'Jumlah perlu dibayar' : 'Total to pay' }}</td>
40
+            <td align="right" style="padding: 14px 0 0; font-weight: 700; white-space: nowrap;">{{ $brand->money($order->total) }}</td>
41
+        </tr>
42
+    </table>
43
+
44
+    <p style="margin: 0 0 20px; color: {{ $brand->color('muted') }};">
45
+        {{ $m ? 'Sudah membayar? Abaikan e-mel ini.' : 'Already paid? You can ignore this email.' }}
46
+        <a href="{{ $orderUrl }}" style="color: {{ $brand->color('foreground') }}; font-weight: 600; text-decoration: underline;">{{ $m ? 'Lihat pesanan anda' : 'View your order' }}</a>
47
+    </p>
48
+    <p style="margin: 0;">{{ $m ? 'Terima kasih,' : 'Thanks,' }}<br><strong>{{ $store->name }}</strong></p>
49
+</x-mail.store>

+ 6
- 0
routes/console.php Voir le fichier

2
 
2
 
3
 use Illuminate\Foundation\Inspiring;
3
 use Illuminate\Foundation\Inspiring;
4
 use Illuminate\Support\Facades\Artisan;
4
 use Illuminate\Support\Facades\Artisan;
5
+use Illuminate\Support\Facades\Schedule;
5
 
6
 
6
 Artisan::command('inspire', function () {
7
 Artisan::command('inspire', function () {
7
     $this->comment(Inspiring::quote());
8
     $this->comment(Inspiring::quote());
8
 })->purpose('Display an inspiring quote');
9
 })->purpose('Display an inspiring quote');
10
+
11
+// The double-check for unpaid orders: asks Stripe and HitPay about orders whose payment news was missed.
12
+// Runs only while the scheduler runs: `composer run dev` on this machine, and a cron line on the server
13
+// (`* * * * * php artisan schedule:run`, see PROGRESS.md).
14
+Schedule::command('orders:check-payments')->everyFiveMinutes()->withoutOverlapping();

+ 2
- 0
routes/web.php Voir le fichier

60
         Route::get('checkout', [CheckoutController::class, 'show'])->name('checkout');
60
         Route::get('checkout', [CheckoutController::class, 'show'])->name('checkout');
61
         Route::post('checkout', [CheckoutController::class, 'store'])->middleware('throttle:20,1')->name('checkout.store');
61
         Route::post('checkout', [CheckoutController::class, 'store'])->middleware('throttle:20,1')->name('checkout.store');
62
         Route::get('orders/{publicId}', [CheckoutController::class, 'order'])->name('order');
62
         Route::get('orders/{publicId}', [CheckoutController::class, 'order'])->name('order');
63
+        Route::get('orders/{publicId}/pay', [CheckoutController::class, 'pay'])->middleware('throttle:20,1')->name('order.pay');
63
 
64
 
64
         // Pages the merchant added, such as /about.
65
         // Pages the merchant added, such as /about.
65
         Route::get('{pageId}', [StoreDesignController::class, 'page'])->name('page')->where('pageId', '[a-z][a-z0-9-]*');
66
         Route::get('{pageId}', [StoreDesignController::class, 'page'])->name('page')->where('pageId', '[a-z][a-z0-9-]*');
112
     Route::get('stores/{slug}/preview/checkout', [CheckoutController::class, 'show'])->name('stores.preview.checkout');
113
     Route::get('stores/{slug}/preview/checkout', [CheckoutController::class, 'show'])->name('stores.preview.checkout');
113
     Route::post('stores/{slug}/preview/checkout', [CheckoutController::class, 'store'])->name('stores.preview.checkout.store');
114
     Route::post('stores/{slug}/preview/checkout', [CheckoutController::class, 'store'])->name('stores.preview.checkout.store');
114
     Route::get('stores/{slug}/preview/orders/{publicId}', [CheckoutController::class, 'order'])->name('stores.preview.order');
115
     Route::get('stores/{slug}/preview/orders/{publicId}', [CheckoutController::class, 'order'])->name('stores.preview.order');
116
+    Route::get('stores/{slug}/preview/orders/{publicId}/pay', [CheckoutController::class, 'pay'])->name('stores.preview.order.pay');
115
 
117
 
116
     // Pages the merchant added, such as /about. Listed after the store's own pages so those win.
118
     // Pages the merchant added, such as /about. Listed after the store's own pages so those win.
117
     Route::get('stores/{slug}/preview/{pageId}', [StoreDesignController::class, 'page'])->name('stores.preview.page')->where('pageId', '[a-z][a-z0-9-]*');
119
     Route::get('stores/{slug}/preview/{pageId}', [StoreDesignController::class, 'page'])->name('stores.preview.page')->where('pageId', '[a-z][a-z0-9-]*');

+ 255
- 0
tests/Feature/Stores/CompletePaymentTest.php Voir le fichier

1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Checkout;
6
+use App\Commerce\PaymentDoubleCheck;
7
+use App\Commerce\Payments\PaymentGateway;
8
+use App\Mail\PaymentReminder;
9
+use App\Models\Order;
10
+use App\Models\Product;
11
+use App\Models\Store;
12
+use App\Models\User;
13
+use App\StorePlan\SamplePlan;
14
+use Illuminate\Foundation\Testing\RefreshDatabase;
15
+use Illuminate\Support\Facades\Mail;
16
+use Inertia\Testing\AssertableInertia as Assert;
17
+use Tests\Support\FakeGateway;
18
+use Tests\TestCase;
19
+
20
+/**
21
+ * A shopper who left the payment page can come back and pay: from the order page, the cart page, or the
22
+ * "Complete your payment" email.
23
+ */
24
+class CompletePaymentTest extends TestCase
25
+{
26
+    use RefreshDatabase;
27
+
28
+    private Store $store;
29
+
30
+    private FakeGateway $gateway;
31
+
32
+    protected function setUp(): void
33
+    {
34
+        parent::setUp();
35
+
36
+        Mail::fake();
37
+
38
+        $this->gateway = new FakeGateway;
39
+        $this->app->instance(PaymentGateway::class, $this->gateway);
40
+
41
+        $user = User::factory()->create();
42
+        $this->store = Store::factory()->for($user)->create();
43
+        $this->store->plan = SamplePlan::for($this->store);
44
+        $this->store->save();
45
+        $this->actingAs($user);
46
+    }
47
+
48
+    /** A shopper goes to the payment page and does not come back. */
49
+    private function placeOrder(string $email = 'aminah@example.com'): Order
50
+    {
51
+        $product = Product::factory()->for($this->store)->create(['price' => 4200, 'stock' => 10]);
52
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
53
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
54
+            'name' => 'Aminah binti Ali',
55
+            'email' => $email,
56
+            'phone' => '012-345 6789',
57
+            'line1' => '12 Jalan Mawar',
58
+            'city' => 'Shah Alam',
59
+            'postcode' => '40000',
60
+            'state' => 'Selangor',
61
+        ]);
62
+
63
+        return Order::latest('id')->firstOrFail();
64
+    }
65
+
66
+    private function runCheck(): array
67
+    {
68
+        return app(PaymentDoubleCheck::class)->run();
69
+    }
70
+
71
+    public function test_the_order_keeps_its_payment_page_and_deadline()
72
+    {
73
+        $this->freezeSecond();
74
+        $order = $this->placeOrder();
75
+
76
+        $this->assertSame('https://pay.test/'.$order->payment_checkout_id, $order->payment_url);
77
+        $this->assertTrue($order->payment_expires_at->eq(now()->addHours(Checkout::PAY_WITHIN_HOURS)));
78
+        $this->assertTrue($order->canStillPay());
79
+    }
80
+
81
+    public function test_the_order_page_offers_complete_payment_with_the_deadline()
82
+    {
83
+        $order = $this->placeOrder();
84
+
85
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
86
+            ->assertInertia(fn (Assert $page) => $page
87
+                ->where('view.order.status', 'pending')
88
+                ->where('view.payment.can_pay', true)
89
+                ->where('view.payment.expires_at', $order->payment_expires_at->toIso8601String()));
90
+
91
+        // The button goes back to the same payment page.
92
+        $this->get(route('stores.preview.order.pay', [$this->store->slug, $order->public_id]))
93
+            ->assertRedirect($order->payment_url);
94
+    }
95
+
96
+    public function test_complete_payment_shows_the_thank_you_when_the_shopper_already_paid()
97
+    {
98
+        $order = $this->placeOrder();
99
+        $this->gateway->pay($order);
100
+
101
+        $this->get(route('stores.preview.order.pay', [$this->store->slug, $order->public_id]))
102
+            ->assertRedirect(route('stores.preview.order', [$this->store->slug, $order->public_id]));
103
+        $this->assertTrue($order->fresh()->isPaid());
104
+
105
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
106
+            ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid')->where('view.payment', null));
107
+    }
108
+
109
+    public function test_after_the_deadline_the_order_is_closed()
110
+    {
111
+        $order = $this->placeOrder();
112
+        $this->travel(Checkout::PAY_WITHIN_HOURS)->hours();
113
+        $this->travel(1)->minutes();
114
+
115
+        $this->get(route('stores.preview.order.pay', [$this->store->slug, $order->public_id]))
116
+            ->assertRedirect(route('stores.preview.order', [$this->store->slug, $order->public_id]));
117
+
118
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
119
+            ->assertInertia(fn (Assert $page) => $page->where('view.payment.can_pay', false));
120
+    }
121
+
122
+    public function test_older_orders_without_a_saved_payment_page_show_the_old_notice()
123
+    {
124
+        $order = $this->placeOrder();
125
+        $order->forceFill(['payment_url' => null, 'payment_expires_at' => null])->save();
126
+
127
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
128
+            ->assertInertia(fn (Assert $page) => $page->where('view.payment', null));
129
+        $this->get(route('stores.preview.order.pay', [$this->store->slug, $order->public_id]))
130
+            ->assertRedirect(route('stores.preview.order', [$this->store->slug, $order->public_id]));
131
+    }
132
+
133
+    public function test_the_cart_page_reminds_this_shopper_of_their_unpaid_order()
134
+    {
135
+        $order = $this->placeOrder();
136
+
137
+        $this->get(route('stores.preview.cart', $this->store->slug))
138
+            ->assertInertia(fn (Assert $page) => $page
139
+                ->where('view.unpaidOrder.number', $order->number)
140
+                ->where('view.unpaidOrder.public_id', $order->public_id));
141
+
142
+        // Someone in another browser does not see it.
143
+        $this->flushSession();
144
+        $this->get(route('stores.preview.cart', $this->store->slug))
145
+            ->assertInertia(fn (Assert $page) => $page->where('view.unpaidOrder', null));
146
+    }
147
+
148
+    public function test_the_cart_page_forgets_the_order_once_paid_or_closed()
149
+    {
150
+        $order = $this->placeOrder();
151
+        $this->gateway->pay($order);
152
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
153
+
154
+        $this->get(route('stores.preview.cart', $this->store->slug))
155
+            ->assertInertia(fn (Assert $page) => $page->where('view.unpaidOrder', null));
156
+
157
+        $this->placeOrder();
158
+        $this->travel(Checkout::PAY_WITHIN_HOURS + 1)->hours();
159
+
160
+        $this->get(route('stores.preview.cart', $this->store->slug))
161
+            ->assertInertia(fn (Assert $page) => $page->where('view.unpaidOrder', null));
162
+    }
163
+
164
+    public function test_the_shopper_is_emailed_once_about_30_minutes_after_leaving_the_payment_page()
165
+    {
166
+        $order = $this->placeOrder();
167
+
168
+        $this->travel(20)->minutes();
169
+        $this->runCheck();
170
+        Mail::assertNothingSent();
171
+
172
+        $this->travel(11)->minutes();
173
+        $this->artisan('orders:check-payments')
174
+            ->expectsOutputToContain('1 shoppers reminded by email')
175
+            ->assertSuccessful();
176
+
177
+        Mail::assertSent(PaymentReminder::class, function (PaymentReminder $mail) use ($order) {
178
+            $html = $mail->render();
179
+
180
+            return $mail->hasTo('aminah@example.com')
181
+                && $mail->envelope()->subject === "Complete your payment for order #{$order->number} - {$this->store->name}"
182
+                && str_contains($html, route('stores.preview.order.pay', [$this->store->slug, $order->public_id]))
183
+                && str_contains($html, 'You can pay until');
184
+        });
185
+        $this->assertNotNull($order->fresh()->payment_reminded_at);
186
+
187
+        // Never twice.
188
+        $this->travel(2)->hours();
189
+        $this->runCheck();
190
+        Mail::assertSent(PaymentReminder::class, 1);
191
+    }
192
+
193
+    public function test_no_reminder_when_the_shopper_paid()
194
+    {
195
+        $order = $this->placeOrder();
196
+        $this->gateway->pay($order);
197
+
198
+        $this->travel(31)->minutes();
199
+        $result = $this->runCheck();
200
+
201
+        $this->assertSame(1, $result['paid']);
202
+        $this->assertSame(0, $result['reminded']);
203
+        Mail::assertNotSent(PaymentReminder::class);
204
+    }
205
+
206
+    public function test_no_reminder_when_the_shopper_ordered_again_since()
207
+    {
208
+        $first = $this->placeOrder();
209
+        $this->travel(5)->minutes();
210
+        $second = $this->placeOrder();
211
+        $this->gateway->pay($second);
212
+        $this->get(route('stores.preview.order', [$this->store->slug, $second->public_id]));
213
+
214
+        $this->travel(40)->minutes();
215
+        $this->runCheck();
216
+
217
+        Mail::assertNotSent(PaymentReminder::class);
218
+        $this->assertNull($first->fresh()->payment_reminded_at);
219
+    }
220
+
221
+    public function test_no_reminder_while_the_provider_cannot_say_whether_they_paid()
222
+    {
223
+        $order = $this->placeOrder();
224
+        unset($this->gateway->payments[$order->payment_checkout_id]);
225
+
226
+        $this->travel(31)->minutes();
227
+        $this->assertSame(1, $this->runCheck()['failed']);
228
+
229
+        Mail::assertNotSent(PaymentReminder::class);
230
+        $this->assertNull($order->fresh()->payment_reminded_at);
231
+    }
232
+
233
+    public function test_the_reminder_is_written_in_malay_for_malay_stores()
234
+    {
235
+        $this->store->forceFill(['language' => 'ms'])->save();
236
+        $order = $this->placeOrder();
237
+
238
+        $this->travel(31)->minutes();
239
+        $this->runCheck();
240
+
241
+        Mail::assertSent(PaymentReminder::class, fn (PaymentReminder $mail) => $mail->envelope()->subject === "Lengkapkan bayaran untuk pesanan #{$order->number} - {$this->store->name}"
242
+            && str_contains($mail->render(), 'Anda boleh membayar sehingga'));
243
+    }
244
+
245
+    public function test_merchants_see_when_an_order_is_waiting_for_payment()
246
+    {
247
+        $order = $this->placeOrder();
248
+
249
+        $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
250
+            ->assertInertia(fn (Assert $page) => $page
251
+                ->where('order.status', 'pending')
252
+                ->where('order.payment_expires_at', $order->payment_expires_at->toIso8601String())
253
+                ->where('order.payment_reminded_at', null));
254
+    }
255
+}

+ 18
- 0
tests/Feature/Stores/HitPayTest.php Voir le fichier

249
                 && $request['purpose'] === 'Kedai Ali order #1001'
249
                 && $request['purpose'] === 'Kedai Ali order #1001'
250
                 && $request['redirect_url'] === route('stores.preview.order', [$this->store->slug, $order->public_id])
250
                 && $request['redirect_url'] === route('stores.preview.order', [$this->store->slug, $order->public_id])
251
                 && $request['send_email'] === 'false'
251
                 && $request['send_email'] === 'false'
252
+                // Expires before the double-check gives up on the order.
253
+                && $request['expires_after'] === '23 hours'
252
                 // A development machine has no public https address for HitPay to call.
254
                 // A development machine has no public https address for HitPay to call.
253
                 && ! isset($request['webhook']);
255
                 && ! isset($request['webhook']);
254
         });
256
         });
407
         $this->get(route('stores.preview.checkout', $this->store->slug))
409
         $this->get(route('stores.preview.checkout', $this->store->slug))
408
             ->assertInertia(fn (Assert $page) => $page->where('view.payWays', [['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']]]));
410
             ->assertInertia(fn (Assert $page) => $page->where('view.payWays', [['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']]]));
409
     }
411
     }
412
+
413
+    public function test_the_double_check_asks_hitpay_about_hitpay_orders()
414
+    {
415
+        $this->connectHitPay();
416
+        $this->fakeHitPay();
417
+        $this->placeOrder();
418
+        $order = Order::firstOrFail();
419
+
420
+        // The shopper paid by DuitNow and closed the phone; no webhook came.
421
+        $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']]);
422
+        $this->travel(3)->minutes();
423
+        $this->artisan('orders:check-payments')->assertSuccessful();
424
+
425
+        $this->assertTrue($order->fresh()->isPaid());
426
+        $this->assertSame('hp_pay_9', $order->fresh()->payment_reference);
427
+    }
410
 }
428
 }

+ 172
- 0
tests/Feature/Stores/PaymentDoubleCheckTest.php Voir le fichier

1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\PaymentDoubleCheck;
6
+use App\Commerce\Payments\PaymentGateway;
7
+use App\Enums\OrderStatus;
8
+use App\Mail\OrderConfirmation;
9
+use App\Models\Order;
10
+use App\Models\Product;
11
+use App\Models\Store;
12
+use App\Models\User;
13
+use App\StorePlan\SamplePlan;
14
+use Illuminate\Foundation\Testing\RefreshDatabase;
15
+use Illuminate\Support\Facades\Mail;
16
+use Inertia\Testing\AssertableInertia as Assert;
17
+use Tests\Support\FakeGateway;
18
+use Tests\TestCase;
19
+
20
+/**
21
+ * The double-check every 5 minutes for orders whose payment news was missed.
22
+ */
23
+class PaymentDoubleCheckTest extends TestCase
24
+{
25
+    use RefreshDatabase;
26
+
27
+    private Store $store;
28
+
29
+    private FakeGateway $gateway;
30
+
31
+    protected function setUp(): void
32
+    {
33
+        parent::setUp();
34
+
35
+        Mail::fake();
36
+
37
+        $this->gateway = new FakeGateway;
38
+        $this->app->instance(PaymentGateway::class, $this->gateway);
39
+
40
+        $user = User::factory()->create();
41
+        $this->store = Store::factory()->for($user)->create();
42
+        $this->store->plan = SamplePlan::for($this->store);
43
+        $this->store->save();
44
+        $this->actingAs($user);
45
+    }
46
+
47
+    /** A shopper goes to the payment page and does not come back. */
48
+    private function placeOrder(): Order
49
+    {
50
+        $product = Product::factory()->for($this->store)->create(['price' => 4200, 'stock' => 10]);
51
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
52
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
53
+            'name' => 'Aminah binti Ali',
54
+            'email' => 'aminah@example.com',
55
+            'phone' => '012-345 6789',
56
+            'line1' => '12 Jalan Mawar',
57
+            'city' => 'Shah Alam',
58
+            'postcode' => '40000',
59
+            'state' => 'Selangor',
60
+        ]);
61
+
62
+        return Order::latest('id')->firstOrFail();
63
+    }
64
+
65
+    private function runCheck(): array
66
+    {
67
+        return app(PaymentDoubleCheck::class)->run();
68
+    }
69
+
70
+    public function test_a_payment_whose_news_was_missed_is_found_and_the_order_marked_paid()
71
+    {
72
+        $order = $this->placeOrder();
73
+        // The shopper paid, then closed the phone; no webhook came.
74
+        $this->gateway->pay($order);
75
+
76
+        // Too new to ask about yet.
77
+        $this->assertSame(0, $this->runCheck()['checked']);
78
+        $this->assertFalse($order->fresh()->isPaid());
79
+
80
+        $this->travel(3)->minutes();
81
+        $this->artisan('orders:check-payments')
82
+            ->expectsOutputToContain('Checked 1 unpaid orders: 1 were paid')
83
+            ->assertSuccessful();
84
+
85
+        $order->refresh();
86
+        $this->assertTrue($order->isPaid());
87
+        $this->assertNotNull($order->payment_checked_at);
88
+        $this->assertSame(9, Product::firstOrFail()->stock);
89
+        Mail::assertSent(OrderConfirmation::class, 1);
90
+
91
+        // Paid orders are never asked about again.
92
+        $this->travel(10)->minutes();
93
+        $this->assertSame(0, $this->runCheck()['checked']);
94
+    }
95
+
96
+    public function test_new_orders_are_asked_about_often_and_older_ones_rarely()
97
+    {
98
+        $order = $this->placeOrder();
99
+
100
+        $this->travel(3)->minutes();
101
+        $this->assertSame(1, $this->runCheck()['checked']);
102
+
103
+        // Every 5 minutes in the first quarter of an hour.
104
+        $this->travel(2)->minutes();
105
+        $this->assertSame(0, $this->runCheck()['checked']);
106
+        $this->travel(3)->minutes();
107
+        $this->assertSame(1, $this->runCheck()['checked']);
108
+
109
+        // Every 15 minutes until an hour.
110
+        $this->travel(22)->minutes(); // 30 minutes old
111
+        $this->assertSame(1, $this->runCheck()['checked']);
112
+        $this->travel(10)->minutes();
113
+        $this->assertSame(0, $this->runCheck()['checked']);
114
+        $this->travel(5)->minutes();
115
+        $this->assertSame(1, $this->runCheck()['checked']);
116
+
117
+        // Then every hour.
118
+        $this->travel(2)->hours();
119
+        $this->assertSame(1, $this->runCheck()['checked']);
120
+        $this->travel(30)->minutes();
121
+        $this->assertSame(0, $this->runCheck()['checked']);
122
+
123
+        $this->assertFalse($order->fresh()->isPaid());
124
+    }
125
+
126
+    public function test_a_day_later_an_unpaid_order_becomes_not_paid_and_is_left_alone()
127
+    {
128
+        $order = $this->placeOrder();
129
+
130
+        $this->travel(26)->hours();
131
+        $result = $this->runCheck();
132
+
133
+        $this->assertSame(0, $result['checked']);
134
+        $this->assertSame(1, $result['given_up']);
135
+        $this->assertSame(OrderStatus::Unpaid, $order->fresh()->status);
136
+        $this->assertSame(0, $this->runCheck()['given_up']);
137
+
138
+        $this->get(route('stores.orders.index', $this->store->slug))
139
+            ->assertInertia(fn (Assert $page) => $page->where('orders.0.status', 'unpaid')->where('orders.0.status_label', 'Not paid'));
140
+
141
+        // A payment that still arrives (the shopper opens the order page) counts.
142
+        $this->gateway->pay($order);
143
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
144
+            ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid'));
145
+        $this->assertTrue($order->fresh()->isPaid());
146
+    }
147
+
148
+    public function test_a_provider_that_cannot_be_reached_does_not_stop_the_other_orders()
149
+    {
150
+        $first = $this->placeOrder();
151
+        $second = $this->placeOrder();
152
+        $this->gateway->pay($second);
153
+        // The provider no longer knows the first payment page.
154
+        unset($this->gateway->payments[$first->payment_checkout_id]);
155
+
156
+        $this->travel(3)->minutes();
157
+        $result = $this->runCheck();
158
+
159
+        $this->assertSame(['checked' => 2, 'paid' => 1, 'failed' => 1, 'reminded' => 0, 'given_up' => 0], $result);
160
+        $this->assertTrue($second->fresh()->isPaid());
161
+        // Not asked again on the very next run.
162
+        $this->travel(1)->minutes();
163
+        $this->assertSame(0, $this->runCheck()['checked']);
164
+    }
165
+
166
+    public function test_the_check_is_scheduled_every_five_minutes()
167
+    {
168
+        $this->artisan('schedule:list')
169
+            ->expectsOutputToContain('*/5 * * * *  php artisan orders:check-payments')
170
+            ->assertSuccessful();
171
+    }
172
+}

Chargement…
Annuler
Enregistrer