Explorar el Código

Add subscription billing with free trial and plan limits

Step 6:
- Plans in a database table (prices in sen); 14-day free trial for
  every new account.
- Stripe subscriptions behind a SubscriptionGateway interface:
  subscribe, switch plan, cancel at period end, undo.
- Billing page with usage meters and plan cards; sidebar link; trial
  notice on the dashboard.
- Limits enforced for stores, regenerations and AI edits. With no plan,
  AI, new stores and publishing are refused and live stores go offline.
- The Stripe webhook also keeps subscriptions in step.

Tests: 164 pass (14 new). Verified with a real Stripe test
subscription: subscribe, cancel, undo.
feature/billing
fahmisaad hace 4 días
padre
commit
bb2afcd59e

+ 74
- 57
PROGRESS.md Ver fichero

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-14
7
-**Current step:** Step 6 — Our own subscription billing (Step 5 Publishing is done for local use; custom domains wait for hosting)
8
-**Next action:** Start Step 6: plans table, subscribe, upgrade and cancel through Stripe, 14-day trial, enforce plan limits
7
+**Current step:** Step 7 — Malaysia features (Step 6 billing is done and tested with a real Stripe test subscription)
8
+**Next action:** Merge `feature/billing` into `main`, then start Step 7: FPX, DuitNow and e-wallets at checkout, EasyParcel shipping, Bahasa Malaysia, WhatsApp
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -110,6 +110,17 @@ Changing from Claude to another AI model (or back) must be a settings change, no
110 110
 - Taking a store offline keeps the design, products and orders.
111 111
 - Some store names cannot be used as addresses (`www`, `admin`, `login` and so on). Such a store gets a number added, for example `login-2`.
112 112
 
113
+### How billing works (added in Step 6)
114
+
115
+- Plans live in the `plans` table, not in code, so prices and limits can change without a release. `config/plans.php` holds only the trial length and the trial plan's key.
116
+- Every new account gets `trial_ends_at` 14 days ahead. While that date is in the future the account is on the free trial.
117
+- A paid plan is one row in `subscriptions`, a copy of what Stripe says. Stripe is the source of truth. The copy is refreshed when the merchant comes back from Stripe, every time the Billing page opens, and by the webhook.
118
+- An account's current plan is: an active paid plan, otherwise the free trial while it lasts, otherwise nothing. "Active" includes `past_due` (a card failed and Stripe is retrying).
119
+- With no plan: AI, new stores and publishing are refused, and live stores show "not found". Nothing is deleted, and everything returns once a plan is chosen.
120
+- The Stripe product and price for each plan are created the first time someone subscribes to it, and saved on the plan.
121
+- Switching plans changes the existing subscription; Stripe charges or credits the difference on the next bill.
122
+- Subscriptions go through one interface (`SubscriptionGateway`), like payments and AI.
123
+
113 124
 ### Plan prices and limits (starting numbers, adjust after real usage)
114 125
 
115 126
 | Plan                 | Price / month | Stores | Full regenerations / month | AI edits / month |
@@ -187,10 +198,12 @@ Changing from Claude to another AI model (or back) must be a settings change, no
187 198
 
188 199
 ### Step 6 — Our own subscription billing
189 200
 
190
-- [ ] Plans table matching the price table above
191
-- [ ] Subscribe, upgrade, cancel through Stripe
192
-- [ ] Free trial of 14 days
193
-- [ ] Enforce plan limits (stores, regenerations, edits)
201
+- [x] Plans table matching the price table above (`plans` table; prices in sen)
202
+- [x] Subscribe, upgrade, downgrade and cancel through Stripe (Billing page). Cancel keeps the plan until the end of the paid month and can be undone
203
+- [x] Free trial of 14 days for every new account (existing test accounts got a fresh 14 days)
204
+- [x] Enforce plan limits: stores, regenerations and AI edits. When the trial ends with no plan, AI, new stores and publishing are switched off and live stores go offline; nothing is deleted
205
+- [x] Tested with a real Stripe test subscription on 2026-11-16: subscribe to Growth, cancel, undo
206
+- [ ] Known gaps, to do later: a merchant who downgrades keeps stores above the new limit (they just cannot add more); no invoices page yet (Stripe sends receipts); no email before the trial ends; the subscription webhook needs hosting, like the order webhook
194 207
 
195 208
 ### Step 7 — Malaysia features
196 209
 
@@ -264,41 +277,44 @@ Then, from the project folder:
264 277
 
265 278
 ## 4b. Where things are in the code
266 279
 
267
-| Thing                                  | Location                                                                        |
268
-| -------------------------------------- | ------------------------------------------------------------------------------- |
269
-| Store model                            | `app/Models/Store.php`                                                          |
270
-| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                      |
271
-| Store categories, languages, statuses  | `app/Enums/`                                                                    |
272
-| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                               |
273
-| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                |
274
-| Store tests                            | `tests/Feature/Stores/`                                                         |
275
-| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                  |
276
-| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                               |
277
-| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                  |
278
-| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                |
279
-| AI settings                            | `config/ai.php` (providers, models per task)                                    |
280
-| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                    |
281
-| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                             |
282
-| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                            |
283
-| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                               |
284
-| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                               |
285
-| Progress screen and chat box           | `resources/js/components/stores/`                                               |
286
-| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                         |
287
-| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                    |
288
-| Product screens                        | `resources/js/pages/stores/products/`                                           |
289
-| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                |
290
-| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`      |
291
-| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                 |
292
-| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`) |
293
-| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |
294
-| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                |
295
-| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                 |
296
-| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                |
297
-| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                               |
298
-| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`              |
299
-| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                               |
300
-| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                              |
301
-| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`     |
280
+| Thing                                  | Location                                                                                    |
281
+| -------------------------------------- | ------------------------------------------------------------------------------------------- |
282
+| Store model                            | `app/Models/Store.php`                                                                      |
283
+| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                  |
284
+| Store categories, languages, statuses  | `app/Enums/`                                                                                |
285
+| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                           |
286
+| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                            |
287
+| Store tests                            | `tests/Feature/Stores/`                                                                     |
288
+| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                              |
289
+| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                           |
290
+| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                              |
291
+| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                            |
292
+| AI settings                            | `config/ai.php` (providers, models per task)                                                |
293
+| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                |
294
+| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                         |
295
+| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                        |
296
+| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                           |
297
+| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                           |
298
+| Progress screen and chat box           | `resources/js/components/stores/`                                                           |
299
+| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                     |
300
+| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                |
301
+| Product screens                        | `resources/js/pages/stores/products/`                                                       |
302
+| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                            |
303
+| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                  |
304
+| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                             |
305
+| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)             |
306
+| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`             |
307
+| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                            |
308
+| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                             |
309
+| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                            |
310
+| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                           |
311
+| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php` |
312
+| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)              |
313
+| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                 |
314
+| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                          |
315
+| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                           |
316
+| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                          |
317
+| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                 |
302 318
 
303 319
 ## 5. Open questions
304 320
 
@@ -319,19 +335,20 @@ Then, from the project folder:
319 335
 
320 336
 Add one line per work session: date, what was done, what is next.
321 337
 
322
-| Date       | Done                                                                                                                                                                                                                                                                                                    | Next                                                            |
323
-| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
324
-| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                     | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
325
-| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                | Step 2: store plan format, sections, renderer                   |
326
-| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                         | Step 3: swappable AI layer and store generation                 |
327
-| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                   | Step 3: swappable AI layer and store generation                 |
328
-| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek. | Add API keys, run the real test, then Step 4                    |
329
-| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                      | Real AI test, then Step 4                                       |
330
-| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                       | Merge into `main`, then Step 4: products                        |
331
-| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                             | Step 4 part 2: cart, Stripe checkout, orders, email             |
332
-| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                   | Stripe checkout (needs test keys), orders, email                |
333
-| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                   | Merge into `main`, then Step 5: publishing                      |
334
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                            | Step 5: publishing                                              |
335
-| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                      | Step 5: publishing                                              |
336
-| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                            | Step 5: publishing                                              |
337
-| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                    | Step 6: subscription billing                                    |
338
+| Date       | Done                                                                                                                                                                                                                                                                                                                                         | Next                                                            |
339
+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
340
+| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                          | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
341
+| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                     | Step 2: store plan format, sections, renderer                   |
342
+| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                              | Step 3: swappable AI layer and store generation                 |
343
+| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
344
+| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                      | Add API keys, run the real test, then Step 4                    |
345
+| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                           | Real AI test, then Step 4                                       |
346
+| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                            | Merge into `main`, then Step 4: products                        |
347
+| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                  | Step 4 part 2: cart, Stripe checkout, orders, email             |
348
+| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                        | Stripe checkout (needs test keys), orders, email                |
349
+| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                                                        | Merge into `main`, then Step 5: publishing                      |
350
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                 | Step 5: publishing                                              |
351
+| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                           | Step 5: publishing                                              |
352
+| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                 | Step 5: publishing                                              |
353
+| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                         | Step 6: subscription billing                                    |
354
+| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5. | Merge into `main`, then Step 7                                  |

+ 12
- 2
README.md Ver fichero

@@ -18,8 +18,8 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
18 18
 | 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                |
19 19
 | 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                |
20 20
 | 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting |
21
-| 6    | Our own subscription billing                            | Next                                                |
22
-| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Not started                                         |
21
+| 6    | Our own subscription billing                            | Done                                                |
22
+| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Next                                                |
23 23
 | 8    | Discounts and product options: codes, variants, bundles | Not started                                         |
24 24
 | 9    | Before launch: hosting, legal pages, backups            | Not started                                         |
25 25
 
@@ -45,6 +45,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
45 45
 - Orders tab for the merchant, and an order confirmation email to the shopper
46 46
 - Publishing: a store goes live at its own address (`storename.localhost:8000` on a local machine), with no login for shoppers
47 47
 - Design changes stay private until the merchant clicks "Publish changes"
48
+- Billing: 14-day free trial, then Starter, Growth or Pro through Stripe. Merchants can switch or cancel on the Billing page, and plan limits are enforced
48 49
 
49 50
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.
50 51
 
@@ -193,6 +194,14 @@ Changing from Claude to another AI model is a settings change, not a code rewrit
193 194
 - AI work runs in the background, so the worker must be running. `composer run dev` starts it.
194 195
 - Settings are in `config/ai.php`. Plan limits are in `config/plans.php`.
195 196
 
197
+## Billing
198
+
199
+- Every new account starts a 14-day free trial.
200
+- Plans and their limits are in the `plans` database table. Prices are in sen.
201
+- Merchants subscribe on the Billing page through Stripe's own payment page, using the same Stripe keys as checkout.
202
+- To test, use Stripe's test card `4242 4242 4242 4242`. The Stripe product and price for each plan are created automatically the first time someone subscribes to it.
203
+- When the trial ends with no paid plan, AI, new stores and publishing are switched off and live stores go offline. Nothing is deleted.
204
+
196 205
 ## Published stores
197 206
 
198 207
 - A published store opens at `<store name>.<domain>`, for example http://luna-skin.localhost:8000.
@@ -264,4 +273,5 @@ Starting numbers, to adjust after real usage.
264 273
 Private. All rights reserved.
265 274
 | Cart, checkout and payments | `app/Commerce/` |
266 275
 | Live store or preview | `app/Storefront/Storefront.php`, top of `routes/web.php` |
276
+| Plans, trial and billing | `app/Billing/`, `app/Models/Plan.php`, `resources/js/pages/billing/` |
267 277
 | Orders for the merchant | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |

+ 173
- 0
app/Billing/Billing.php Ver fichero

@@ -0,0 +1,173 @@
1
+<?php
2
+
3
+namespace App\Billing;
4
+
5
+use App\Commerce\Payments\CheckoutLink;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Models\Plan;
8
+use App\Models\Subscription;
9
+use App\Models\User;
10
+use Illuminate\Support\Carbon;
11
+
12
+/**
13
+ * Starting, changing and cancelling a merchant's paid plan.
14
+ *
15
+ * Stripe is the source of truth. Our "subscriptions" table is a copy that is refreshed
16
+ * whenever Stripe tells us something (webhook) or we ask it (billing page, after a change).
17
+ */
18
+class Billing
19
+{
20
+    public function __construct(private readonly SubscriptionGateway $gateway) {}
21
+
22
+    /**
23
+     * Send the merchant to a payment page to start the given plan.
24
+     *
25
+     * @throws PaymentException
26
+     */
27
+    public function startCheckout(User $user, Plan $plan, string $successUrl, string $cancelUrl): CheckoutLink
28
+    {
29
+        $subscription = $this->record($user);
30
+
31
+        if ($subscription->stripe_customer_id === null) {
32
+            $subscription->stripe_customer_id = $this->gateway->createCustomer($user);
33
+            $subscription->save();
34
+        }
35
+
36
+        return $this->gateway->startCheckout(
37
+            $subscription->stripe_customer_id,
38
+            $this->priceId($plan),
39
+            $successUrl,
40
+            $cancelUrl,
41
+        );
42
+    }
43
+
44
+    /**
45
+     * The merchant came back from the payment page. Attach the subscription it created.
46
+     * Returns true when a subscription was attached.
47
+     *
48
+     * @throws PaymentException
49
+     */
50
+    public function completeCheckout(User $user, string $checkoutId): bool
51
+    {
52
+        $state = $this->gateway->findByCheckout($checkoutId);
53
+        $subscription = $this->record($user);
54
+
55
+        // The payment page must belong to this merchant. An id copied from someone else is ignored.
56
+        if ($state === null || $state->customerId !== $subscription->stripe_customer_id) {
57
+            return false;
58
+        }
59
+
60
+        $this->apply($subscription, $state);
61
+
62
+        return true;
63
+    }
64
+
65
+    /**
66
+     * Move to another paid plan.
67
+     *
68
+     * @throws PaymentException
69
+     */
70
+    public function changePlan(User $user, Plan $plan): void
71
+    {
72
+        $subscription = $this->record($user);
73
+
74
+        if ($subscription->stripe_subscription_id === null) {
75
+            throw new PaymentException('There is no subscription to change.');
76
+        }
77
+
78
+        $this->apply($subscription, $this->gateway->changePrice($subscription->stripe_subscription_id, $this->priceId($plan)));
79
+    }
80
+
81
+    /**
82
+     * Cancel at the end of the paid-for period, or undo that.
83
+     *
84
+     * @throws PaymentException
85
+     */
86
+    public function setCancel(User $user, bool $cancel): void
87
+    {
88
+        $subscription = $this->record($user);
89
+
90
+        if ($subscription->stripe_subscription_id === null) {
91
+            throw new PaymentException('There is no subscription to change.');
92
+        }
93
+
94
+        $this->apply($subscription, $this->gateway->setCancelAtPeriodEnd($subscription->stripe_subscription_id, $cancel));
95
+    }
96
+
97
+    /**
98
+     * Ask Stripe for the latest state of this merchant's subscription.
99
+     * A failure is reported and otherwise ignored, so the billing page still opens.
100
+     */
101
+    public function refresh(User $user): void
102
+    {
103
+        $subscription = $user->subscription;
104
+
105
+        if ($subscription?->stripe_subscription_id === null) {
106
+            return;
107
+        }
108
+
109
+        try {
110
+            $this->apply($subscription, $this->gateway->find($subscription->stripe_subscription_id));
111
+        } catch (PaymentException $e) {
112
+            report($e);
113
+        }
114
+    }
115
+
116
+    /**
117
+     * Stripe told us about a subscription through the webhook.
118
+     */
119
+    public function applyFromWebhook(SubscriptionState $state): void
120
+    {
121
+        $subscription = Subscription::query()->where('stripe_customer_id', $state->customerId)->first();
122
+
123
+        if ($subscription !== null) {
124
+            $this->apply($subscription, $state);
125
+        }
126
+    }
127
+
128
+    /**
129
+     * Copy what Stripe says into our table.
130
+     */
131
+    private function apply(Subscription $subscription, SubscriptionState $state): void
132
+    {
133
+        $plan = $state->priceId !== null ? Plan::query()->where('stripe_price_id', $state->priceId)->first() : null;
134
+
135
+        $subscription->stripe_subscription_id = $state->subscriptionId;
136
+        $subscription->status = $state->status;
137
+        $subscription->plan_id = $plan !== null ? $plan->id : $subscription->plan_id;
138
+        $subscription->current_period_end = $state->currentPeriodEnd !== null ? Carbon::createFromTimestamp($state->currentPeriodEnd) : null;
139
+        $subscription->cancel_at_period_end = $state->cancelAtPeriodEnd;
140
+        $subscription->save();
141
+
142
+        $subscription->user->unsetRelation('subscription');
143
+    }
144
+
145
+    /**
146
+     * The provider's price id for a plan, creating it at the provider the first time.
147
+     */
148
+    private function priceId(Plan $plan): string
149
+    {
150
+        if ($plan->stripe_price_id === null) {
151
+            $created = $this->gateway->createPrice($plan);
152
+
153
+            $plan->stripe_product_id = $created['product'];
154
+            $plan->stripe_price_id = $created['price'];
155
+            $plan->save();
156
+        }
157
+
158
+        return $plan->stripe_price_id;
159
+    }
160
+
161
+    private function record(User $user): Subscription
162
+    {
163
+        $subscription = $user->subscription ?? new Subscription;
164
+
165
+        if (! $subscription->exists) {
166
+            $subscription->user_id = $user->id;
167
+            $subscription->save();
168
+            $user->setRelation('subscription', $subscription);
169
+        }
170
+
171
+        return $subscription;
172
+    }
173
+}

+ 175
- 0
app/Billing/StripeSubscriptionGateway.php Ver fichero

@@ -0,0 +1,175 @@
1
+<?php
2
+
3
+namespace App\Billing;
4
+
5
+use App\Commerce\Payments\CheckoutLink;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Models\Plan;
8
+use App\Models\User;
9
+use Stripe\Exception\ApiErrorException;
10
+use Stripe\Exception\SignatureVerificationException;
11
+use Stripe\StripeClient;
12
+use Stripe\Subscription as StripeSubscription;
13
+use Stripe\Webhook;
14
+use UnexpectedValueException;
15
+
16
+/**
17
+ * Merchants' monthly subscriptions through Stripe Billing.
18
+ * Stripe hosts the payment page and charges the card every month.
19
+ */
20
+final class StripeSubscriptionGateway implements SubscriptionGateway
21
+{
22
+    public function createCustomer(User $user): string
23
+    {
24
+        return $this->call(fn (StripeClient $stripe) => $stripe->customers->create([
25
+            'email' => $user->email,
26
+            'name' => $user->name,
27
+            'metadata' => ['user_id' => (string) $user->id],
28
+        ])->id);
29
+    }
30
+
31
+    public function createPrice(Plan $plan): array
32
+    {
33
+        return $this->call(function (StripeClient $stripe) use ($plan): array {
34
+            $product = $stripe->products->create([
35
+                'name' => config('app.name').' '.$plan->name,
36
+                'metadata' => ['plan' => $plan->key],
37
+            ]);
38
+
39
+            $price = $stripe->prices->create([
40
+                'product' => $product->id,
41
+                'currency' => 'myr',
42
+                'unit_amount' => $plan->price,
43
+                'recurring' => ['interval' => 'month'],
44
+                'metadata' => ['plan' => $plan->key],
45
+            ]);
46
+
47
+            return ['product' => $product->id, 'price' => $price->id];
48
+        });
49
+    }
50
+
51
+    public function startCheckout(string $customerId, string $priceId, string $successUrl, string $cancelUrl): CheckoutLink
52
+    {
53
+        return $this->call(function (StripeClient $stripe) use ($customerId, $priceId, $successUrl, $cancelUrl): CheckoutLink {
54
+            $session = $stripe->checkout->sessions->create([
55
+                'mode' => 'subscription',
56
+                'customer' => $customerId,
57
+                'line_items' => [['price' => $priceId, 'quantity' => 1]],
58
+                // Stripe replaces {CHECKOUT_SESSION_ID} with the real id when it sends the merchant back.
59
+                'success_url' => $successUrl.(str_contains($successUrl, '?') ? '&' : '?').'session_id={CHECKOUT_SESSION_ID}',
60
+                'cancel_url' => $cancelUrl,
61
+            ]);
62
+
63
+            if (! is_string($session->url)) {
64
+                throw new PaymentException('Stripe did not return a payment page address.');
65
+            }
66
+
67
+            return new CheckoutLink($session->id, $session->url);
68
+        });
69
+    }
70
+
71
+    public function findByCheckout(string $checkoutId): ?SubscriptionState
72
+    {
73
+        $subscriptionId = $this->call(function (StripeClient $stripe) use ($checkoutId): ?string {
74
+            $session = $stripe->checkout->sessions->retrieve($checkoutId);
75
+
76
+            return $session->status === 'complete' && is_string($session->subscription) ? $session->subscription : null;
77
+        });
78
+
79
+        return $subscriptionId === null ? null : $this->find($subscriptionId);
80
+    }
81
+
82
+    public function find(string $subscriptionId): SubscriptionState
83
+    {
84
+        return $this->call(fn (StripeClient $stripe) => $this->state($stripe->subscriptions->retrieve($subscriptionId)));
85
+    }
86
+
87
+    public function changePrice(string $subscriptionId, string $priceId): SubscriptionState
88
+    {
89
+        return $this->call(function (StripeClient $stripe) use ($subscriptionId, $priceId): SubscriptionState {
90
+            $itemId = $stripe->subscriptions->retrieve($subscriptionId)->items->data[0]->id ?? null;
91
+
92
+            if (! is_string($itemId)) {
93
+                throw new PaymentException('The subscription has nothing to change.');
94
+            }
95
+
96
+            return $this->state($stripe->subscriptions->update($subscriptionId, [
97
+                'items' => [['id' => $itemId, 'price' => $priceId]],
98
+                // Charge or credit the difference for the rest of the month.
99
+                'proration_behavior' => 'create_prorations',
100
+                // Changing plan also undoes a pending cancellation.
101
+                'cancel_at_period_end' => false,
102
+            ]));
103
+        });
104
+    }
105
+
106
+    public function setCancelAtPeriodEnd(string $subscriptionId, bool $cancel): SubscriptionState
107
+    {
108
+        return $this->call(fn (StripeClient $stripe) => $this->state(
109
+            $stripe->subscriptions->update($subscriptionId, ['cancel_at_period_end' => $cancel]),
110
+        ));
111
+    }
112
+
113
+    public function readWebhook(string $payload, string $signature): ?SubscriptionState
114
+    {
115
+        $secret = (string) config('services.stripe.webhook_secret');
116
+
117
+        if ($secret === '') {
118
+            throw new PaymentException('STRIPE_WEBHOOK_SECRET is not set.');
119
+        }
120
+
121
+        try {
122
+            $event = Webhook::constructEvent($payload, $signature, $secret);
123
+        } catch (SignatureVerificationException|UnexpectedValueException $e) {
124
+            throw new PaymentException('The webhook message is not from Stripe.', 0, $e);
125
+        }
126
+
127
+        $subscription = $event->data->object ?? null;
128
+
129
+        if (! str_starts_with($event->type, 'customer.subscription.') || ! $subscription instanceof StripeSubscription) {
130
+            return null;
131
+        }
132
+
133
+        return $this->state($subscription);
134
+    }
135
+
136
+    private function state(StripeSubscription $subscription): SubscriptionState
137
+    {
138
+        $item = $subscription->items->data[0] ?? null;
139
+
140
+        // Newer Stripe versions keep the period end on the item, older ones on the subscription.
141
+        $periodEnd = $item->current_period_end ?? $subscription['current_period_end'] ?? null;
142
+
143
+        return new SubscriptionState(
144
+            subscriptionId: $subscription->id,
145
+            customerId: is_string($subscription->customer) ? $subscription->customer : $subscription->customer->id,
146
+            status: (string) $subscription->status,
147
+            priceId: $item?->price?->id,
148
+            currentPeriodEnd: is_int($periodEnd) ? $periodEnd : null,
149
+            cancelAtPeriodEnd: (bool) $subscription->cancel_at_period_end,
150
+        );
151
+    }
152
+
153
+    /**
154
+     * Run one Stripe request, turning Stripe's errors into our own.
155
+     *
156
+     * @template T
157
+     *
158
+     * @param  callable(StripeClient): T  $request
159
+     * @return T
160
+     */
161
+    private function call(callable $request): mixed
162
+    {
163
+        $secret = (string) config('services.stripe.secret');
164
+
165
+        if ($secret === '') {
166
+            throw new PaymentException('STRIPE_SECRET is missing in the settings file.');
167
+        }
168
+
169
+        try {
170
+            return $request(new StripeClient($secret));
171
+        } catch (ApiErrorException $e) {
172
+            throw new PaymentException('Stripe request failed: '.$e->getMessage(), 0, $e);
173
+        }
174
+    }
175
+}

+ 72
- 0
app/Billing/SubscriptionGateway.php Ver fichero

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+namespace App\Billing;
4
+
5
+use App\Commerce\Payments\CheckoutLink;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Models\Plan;
8
+use App\Models\User;
9
+
10
+/**
11
+ * The one interface the app uses for merchants' monthly subscriptions.
12
+ * Stripe is the first provider.
13
+ */
14
+interface SubscriptionGateway
15
+{
16
+    /**
17
+     * Register the merchant with the provider. Returns the provider's customer id.
18
+     *
19
+     * @throws PaymentException
20
+     */
21
+    public function createCustomer(User $user): string;
22
+
23
+    /**
24
+     * Register a plan with the provider as a monthly price.
25
+     *
26
+     * @return array{product: string, price: string}
27
+     *
28
+     * @throws PaymentException
29
+     */
30
+    public function createPrice(Plan $plan): array;
31
+
32
+    /**
33
+     * Create a payment page that starts a monthly subscription.
34
+     *
35
+     * @throws PaymentException
36
+     */
37
+    public function startCheckout(string $customerId, string $priceId, string $successUrl, string $cancelUrl): CheckoutLink;
38
+
39
+    /**
40
+     * The subscription that a payment page led to, or null if it was not completed.
41
+     *
42
+     * @throws PaymentException
43
+     */
44
+    public function findByCheckout(string $checkoutId): ?SubscriptionState;
45
+
46
+    /**
47
+     * @throws PaymentException
48
+     */
49
+    public function find(string $subscriptionId): SubscriptionState;
50
+
51
+    /**
52
+     * Move a subscription to another plan. The provider works out the price difference.
53
+     *
54
+     * @throws PaymentException
55
+     */
56
+    public function changePrice(string $subscriptionId, string $priceId): SubscriptionState;
57
+
58
+    /**
59
+     * Cancel at the end of the paid-for period, or undo that.
60
+     *
61
+     * @throws PaymentException
62
+     */
63
+    public function setCancelAtPeriodEnd(string $subscriptionId, bool $cancel): SubscriptionState;
64
+
65
+    /**
66
+     * Read a message the provider sent to our webhook address.
67
+     * Returns null when the message is not about a subscription.
68
+     *
69
+     * @throws PaymentException When the message is not genuine.
70
+     */
71
+    public function readWebhook(string $payload, string $signature): ?SubscriptionState;
72
+}

+ 21
- 0
app/Billing/SubscriptionState.php Ver fichero

@@ -0,0 +1,21 @@
1
+<?php
2
+
3
+namespace App\Billing;
4
+
5
+/**
6
+ * What the payment provider says about one subscription, in a shape that does not depend on the provider.
7
+ */
8
+final readonly class SubscriptionState
9
+{
10
+    public function __construct(
11
+        public string $subscriptionId,
12
+        public string $customerId,
13
+        /** The provider's word for the state: active, past_due, canceled and so on. */
14
+        public string $status,
15
+        /** The provider's id of the price being paid, which tells us the plan. */
16
+        public ?string $priceId,
17
+        /** Unix time when the paid-for period ends. */
18
+        public ?int $currentPeriodEnd,
19
+        public bool $cancelAtPeriodEnd,
20
+    ) {}
21
+}

+ 44
- 16
app/Billing/UsageLimits.php Ver fichero

@@ -4,50 +4,78 @@ namespace App\Billing;
4 4
 
5 5
 use App\Enums\GenerationStatus;
6 6
 use App\Enums\GenerationType;
7
+use App\Models\Plan;
7 8
 use App\Models\StoreGeneration;
8 9
 use App\Models\User;
9 10
 
10 11
 /**
11
- * How much AI a user has used, and how much their plan allows.
12
+ * What a user's plan allows, and how much of it they have used.
12 13
  *
13
- * Failed jobs never count. The first design of a store is free; only redesigns count as regenerations.
14
+ * - Failed AI jobs never count.
15
+ * - The first design of a store is free; only redesigns count as regenerations.
16
+ * - With no plan (trial over, no subscription) every limit is zero.
14 17
  */
15 18
 class UsageLimits
16 19
 {
17 20
     /**
18
-     * @return array{plan: string, plan_name: string, period: string, regenerations: array{used: int, limit: int}, edits: array{used: int, limit: int}}
21
+     * @return array{active: bool, plan: string|null, plan_name: string, period: string, on_trial: bool, trial_ends_at: string|null, stores: array{used: int, limit: int}, regenerations: array{used: int, limit: int}, edits: array{used: int, limit: int}}
19 22
      */
20 23
     public function for(User $user): array
21 24
     {
22
-        $key = array_key_exists($user->plan, config('plans.plans')) ? $user->plan : config('plans.default');
23
-        $plan = config("plans.plans.$key");
25
+        $plan = $user->currentPlan();
26
+        $period = $plan !== null ? $plan->period : 'month';
27
+        $paying = $plan?->isPaid() ?? false;
24 28
 
25 29
         return [
26
-            'plan' => $key,
27
-            'plan_name' => $plan['name'],
28
-            'period' => $plan['period'],
30
+            'active' => $plan !== null,
31
+            'plan' => $plan?->key,
32
+            'plan_name' => $plan !== null ? $plan->name : 'No plan',
33
+            'period' => $period,
34
+            'on_trial' => $plan !== null && ! $paying,
35
+            'trial_ends_at' => $user->trial_ends_at?->toIso8601String(),
36
+            'stores' => [
37
+                'used' => $user->stores()->count(),
38
+                'limit' => $plan !== null ? $plan->stores : 0,
39
+            ],
29 40
             'regenerations' => [
30
-                'used' => $this->used($user, GenerationType::Generate, $plan['period']),
31
-                'limit' => (int) $plan['regenerations'],
41
+                'used' => $this->used($user, GenerationType::Generate, $period),
42
+                'limit' => $plan !== null ? $plan->regenerations : 0,
32 43
             ],
33 44
             'edits' => [
34
-                'used' => $this->used($user, GenerationType::Edit, $plan['period']),
35
-                'limit' => (int) $plan['edits'],
45
+                'used' => $this->used($user, GenerationType::Edit, $period),
46
+                'limit' => $plan !== null ? $plan->edits : 0,
36 47
             ],
37 48
         ];
38 49
     }
39 50
 
40
-    public function canRegenerate(User $user): bool
51
+    /**
52
+     * Whether the user has a plan at all: a paid one, or a free trial that has not ended.
53
+     */
54
+    public function hasPlan(User $user): bool
41 55
     {
42
-        $usage = $this->for($user)['regenerations'];
56
+        return $user->currentPlan() instanceof Plan;
57
+    }
43 58
 
44
-        return $usage['used'] < $usage['limit'];
59
+    public function canCreateStore(User $user): bool
60
+    {
61
+        return $this->hasRoom($this->for($user)['stores']);
62
+    }
63
+
64
+    public function canRegenerate(User $user): bool
65
+    {
66
+        return $this->hasRoom($this->for($user)['regenerations']);
45 67
     }
46 68
 
47 69
     public function canEdit(User $user): bool
48 70
     {
49
-        $usage = $this->for($user)['edits'];
71
+        return $this->hasRoom($this->for($user)['edits']);
72
+    }
50 73
 
74
+    /**
75
+     * @param  array{used: int, limit: int}  $usage
76
+     */
77
+    private function hasRoom(array $usage): bool
78
+    {
51 79
         return $usage['used'] < $usage['limit'];
52 80
     }
53 81
 

+ 125
- 0
app/Http/Controllers/BillingController.php Ver fichero

@@ -0,0 +1,125 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Billing\Billing;
6
+use App\Billing\UsageLimits;
7
+use App\Commerce\Payments\PaymentException;
8
+use App\Models\Plan;
9
+use Illuminate\Http\RedirectResponse;
10
+use Illuminate\Http\Request;
11
+use Illuminate\Validation\Rule;
12
+use Inertia\Inertia;
13
+use Inertia\Response;
14
+use Symfony\Component\HttpFoundation\Response as HttpResponse;
15
+
16
+/**
17
+ * The merchant's own plan: see it, start it, change it, cancel it.
18
+ */
19
+class BillingController extends Controller
20
+{
21
+    public function index(Request $request, Billing $billing, UsageLimits $usage): Response|RedirectResponse
22
+    {
23
+        $user = $request->user();
24
+
25
+        // Coming back from the payment page: attach the new subscription, then show a clean address.
26
+        if (is_string($request->query('session_id'))) {
27
+            try {
28
+                $attached = $billing->completeCheckout($user, $request->query('session_id'));
29
+            } catch (PaymentException $e) {
30
+                report($e);
31
+                $attached = false;
32
+            }
33
+
34
+            Inertia::flash('toast', $attached
35
+                ? ['type' => 'success', 'message' => __('Your plan is active. Thank you!')]
36
+                : ['type' => 'error', 'message' => __('We could not confirm the payment. If you were charged, it will show here shortly.')]);
37
+
38
+            return to_route('billing');
39
+        }
40
+
41
+        // Ask Stripe for the latest state, so this page is right even without webhooks.
42
+        $billing->refresh($user);
43
+
44
+        $subscription = $user->subscription()->with('plan')->first();
45
+
46
+        return Inertia::render('billing/index', [
47
+            'usage' => $usage->for($user),
48
+            'plans' => Plan::query()->where('price', '>', 0)->orderBy('sort')->get()->map(fn (Plan $plan) => $plan->toDisplay()),
49
+            'subscription' => $subscription !== null && $subscription->stripe_subscription_id !== null ? [
50
+                'active' => $subscription->isActive(),
51
+                'status' => $subscription->status,
52
+                'plan' => $subscription->plan?->key,
53
+                'current_period_end' => $subscription->current_period_end?->toIso8601String(),
54
+                'cancel_at_period_end' => $subscription->cancel_at_period_end,
55
+            ] : null,
56
+        ]);
57
+    }
58
+
59
+    /**
60
+     * Start a paid plan, or move to a different one.
61
+     */
62
+    public function subscribe(Request $request, Billing $billing): HttpResponse
63
+    {
64
+        $validated = $request->validate([
65
+            'plan' => ['required', 'string', Rule::exists('plans', 'key')->where(fn ($query) => $query->where('price', '>', 0))],
66
+        ]);
67
+
68
+        $user = $request->user();
69
+        $plan = Plan::query()->where('key', $validated['plan'])->firstOrFail();
70
+
71
+        try {
72
+            // Already paying: switch plans in place. Stripe works out the price difference.
73
+            if ($user->subscription?->isActive()) {
74
+                $billing->changePlan($user, $plan);
75
+
76
+                return $this->back('success', __('You are now on the :plan plan.', ['plan' => $plan->name]));
77
+            }
78
+
79
+            $link = $billing->startCheckout($user, $plan, route('billing'), route('billing'));
80
+        } catch (PaymentException $e) {
81
+            report($e);
82
+
83
+            return $this->back('error', __('We could not reach the payment service. Please try again in a moment.'));
84
+        }
85
+
86
+        // The payment page is on another website, so this is a full browser redirect.
87
+        return Inertia::location($link->url);
88
+    }
89
+
90
+    /**
91
+     * Stop renewing. The plan stays until the end of the period already paid for.
92
+     */
93
+    public function cancel(Request $request, Billing $billing): RedirectResponse
94
+    {
95
+        return $this->change($request, $billing, true, __('Your plan will end on the date shown. You can resume it any time before then.'));
96
+    }
97
+
98
+    /**
99
+     * Undo a cancellation before the period ends.
100
+     */
101
+    public function resume(Request $request, Billing $billing): RedirectResponse
102
+    {
103
+        return $this->change($request, $billing, false, __('Your plan will keep renewing.'));
104
+    }
105
+
106
+    private function change(Request $request, Billing $billing, bool $cancel, string $message): RedirectResponse
107
+    {
108
+        try {
109
+            $billing->setCancel($request->user(), $cancel);
110
+        } catch (PaymentException $e) {
111
+            report($e);
112
+
113
+            return $this->back('error', __('We could not reach the payment service. Please try again in a moment.'));
114
+        }
115
+
116
+        return $this->back('success', $message);
117
+    }
118
+
119
+    private function back(string $type, string $message): RedirectResponse
120
+    {
121
+        Inertia::flash('toast', ['type' => $type, 'message' => $message]);
122
+
123
+        return to_route('billing');
124
+    }
125
+}

+ 24
- 3
app/Http/Controllers/StoreController.php Ver fichero

@@ -20,9 +20,10 @@ class StoreController extends Controller
20 20
     /**
21 21
      * Show the dashboard with the user's own stores.
22 22
      */
23
-    public function index(Request $request): Response
23
+    public function index(Request $request, UsageLimits $usage): Response
24 24
     {
25 25
         return Inertia::render('dashboard', [
26
+            'usage' => $usage->for($request->user()),
26 27
             'stores' => $request->user()
27 28
                 ->stores()
28 29
                 ->latest()
@@ -34,8 +35,12 @@ class StoreController extends Controller
34 35
     /**
35 36
      * Show the "create a store" form.
36 37
      */
37
-    public function create(): Response
38
+    public function create(Request $request, UsageLimits $usage): Response|RedirectResponse
38 39
     {
40
+        if (! $usage->canCreateStore($request->user())) {
41
+            return $this->storeLimitReached($request, $usage);
42
+        }
43
+
39 44
         return Inertia::render('stores/create', [
40 45
             'categories' => StoreCategory::options(),
41 46
             'languages' => StoreLanguage::options(),
@@ -45,8 +50,12 @@ class StoreController extends Controller
45 50
     /**
46 51
      * Save a new store for the current user.
47 52
      */
48
-    public function store(CreateStoreRequest $request): RedirectResponse
53
+    public function store(CreateStoreRequest $request, UsageLimits $usage): RedirectResponse
49 54
     {
55
+        if (! $usage->canCreateStore($request->user())) {
56
+            return $this->storeLimitReached($request, $usage);
57
+        }
58
+
50 59
         $store = $request->user()->stores()->create($request->validated());
51 60
 
52 61
         Inertia::flash('toast', ['type' => 'success', 'message' => __('Store created.')]);
@@ -78,6 +87,18 @@ class StoreController extends Controller
78 87
         ]);
79 88
     }
80 89
 
90
+    /**
91
+     * The plan does not allow another store. Send the user to the billing page with the reason.
92
+     */
93
+    private function storeLimitReached(Request $request, UsageLimits $usage): RedirectResponse
94
+    {
95
+        Inertia::flash('toast', ['type' => 'error', 'message' => $usage->hasPlan($request->user())
96
+            ? __('Your plan does not allow more stores. Upgrade to add another.')
97
+            : __('Your free trial has ended. Choose a plan to continue.')]);
98
+
99
+        return to_route('billing');
100
+    }
101
+
81 102
     /**
82 103
      * The store fields the frontend is allowed to see.
83 104
      *

+ 8
- 2
app/Http/Controllers/StoreGenerationController.php Ver fichero

@@ -29,8 +29,12 @@ class StoreGenerationController extends Controller
29 29
             return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.'));
30 30
         }
31 31
 
32
+        if (! $usage->hasPlan($request->user())) {
33
+            return $this->refuse($store, __('Your free trial has ended. Choose a plan to keep using AI.'));
34
+        }
35
+
32 36
         if ($isRegeneration && ! $usage->canRegenerate($request->user())) {
33
-            return $this->refuse($store, __('You have used all the regenerations in your plan.'));
37
+            return $this->refuse($store, __('You have used all the regenerations in your plan. Upgrade for more.'));
34 38
         }
35 39
 
36 40
         $this->start($request, $store, [
@@ -59,7 +63,9 @@ class StoreGenerationController extends Controller
59 63
         }
60 64
 
61 65
         if (! $usage->canEdit($request->user())) {
62
-            return $this->refuse($store, __('You have used all the AI edits in your plan.'));
66
+            return $this->refuse($store, $usage->hasPlan($request->user())
67
+                ? __('You have used all the AI edits in your plan. Upgrade for more.')
68
+                : __('Your free trial has ended. Choose a plan to keep using AI.'));
63 69
         }
64 70
 
65 71
         $this->start($request, $store, [

+ 6
- 1
app/Http/Controllers/StorePublishController.php Ver fichero

@@ -2,6 +2,7 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
+use App\Billing\UsageLimits;
5 6
 use App\Enums\StoreStatus;
6 7
 use App\Models\Store;
7 8
 use App\StorePlan\PlanValidator;
@@ -19,12 +20,16 @@ class StorePublishController extends Controller
19 20
      * Publish the store, or publish the latest design changes of a store that is already live.
20 21
      * Shoppers see a saved copy of the design, taken at this moment.
21 22
      */
22
-    public function publish(Request $request, PlanValidator $validator, string $slug): RedirectResponse
23
+    public function publish(Request $request, PlanValidator $validator, UsageLimits $usage, string $slug): RedirectResponse
23 24
     {
24 25
         $store = $this->ownedStore($request, $slug);
25 26
 
26 27
         abort_if($store->plan === null, 404);
27 28
 
29
+        if (! $usage->hasPlan($request->user())) {
30
+            return $this->flash($store, 'error', __('Your free trial has ended. Choose a plan to publish your store.'));
31
+        }
32
+
28 33
         try {
29 34
             // Checked once more, so nothing broken can ever go live.
30 35
             $plan = $validator->validate($store->plan);

+ 15
- 3
app/Http/Controllers/StripeWebhookController.php Ver fichero

@@ -2,6 +2,8 @@
2 2
 
3 3
 namespace App\Http\Controllers;
4 4
 
5
+use App\Billing\Billing;
6
+use App\Billing\SubscriptionGateway;
5 7
 use App\Commerce\Checkout;
6 8
 use App\Commerce\Payments\PaymentException;
7 9
 use App\Commerce\Payments\PaymentGateway;
@@ -12,19 +14,29 @@ use Illuminate\Http\Response;
12 14
 /**
13 15
  * Stripe calls this address to tell us about payments.
14 16
  *
15
- * It is the safety net for shoppers who pay but close the browser before coming back to the store.
17
+ * It is the safety net for shoppers who pay but close the browser before coming back to the store,
18
+ * and it is how we hear that a merchant's monthly payment went through, failed or was cancelled.
16 19
  * Every message is checked with the webhook signing secret before anything is done.
17 20
  */
18 21
 class StripeWebhookController extends Controller
19 22
 {
20
-    public function __invoke(Request $request, PaymentGateway $gateway, Checkout $checkout): Response
23
+    public function __invoke(Request $request, PaymentGateway $gateway, Checkout $checkout, SubscriptionGateway $subscriptions, Billing $billing): Response
21 24
     {
25
+        $payload = $request->getContent();
26
+        $signature = (string) $request->header('Stripe-Signature');
27
+
22 28
         try {
23
-            $payment = $gateway->readWebhook($request->getContent(), (string) $request->header('Stripe-Signature'));
29
+            $payment = $gateway->readWebhook($payload, $signature);
30
+            // The same address also receives news about merchants' own plans.
31
+            $subscription = $subscriptions->readWebhook($payload, $signature);
24 32
         } catch (PaymentException) {
25 33
             return response('Invalid webhook.', 400);
26 34
         }
27 35
 
36
+        if ($subscription !== null) {
37
+            $billing->applyFromWebhook($subscription);
38
+        }
39
+
28 40
         if ($payment !== null) {
29 41
             $order = Order::query()->where('payment_checkout_id', $payment->checkoutId)->first();
30 42
 

+ 65
- 0
app/Models/Plan.php Ver fichero

@@ -0,0 +1,65 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+/**
8
+ * One pricing plan and what it allows. The price is in sen (1 ringgit = 100 sen).
9
+ *
10
+ * @property int $id
11
+ * @property string $key
12
+ * @property string $name
13
+ * @property int $price
14
+ * @property int $stores
15
+ * @property int $regenerations
16
+ * @property int $edits
17
+ * @property string $period
18
+ * @property string|null $stripe_product_id
19
+ * @property string|null $stripe_price_id
20
+ * @property int $sort
21
+ */
22
+class Plan extends Model
23
+{
24
+    public static function findByKey(string $key): ?self
25
+    {
26
+        return static::query()->where('key', $key)->first();
27
+    }
28
+
29
+    public function isPaid(): bool
30
+    {
31
+        return $this->price > 0;
32
+    }
33
+
34
+    /**
35
+     * What the dashboard is allowed to see. The price is in ringgit here.
36
+     *
37
+     * @return array<string, mixed>
38
+     */
39
+    public function toDisplay(): array
40
+    {
41
+        return [
42
+            'key' => $this->key,
43
+            'name' => $this->name,
44
+            'price' => $this->price / 100,
45
+            'stores' => $this->stores,
46
+            'regenerations' => $this->regenerations,
47
+            'edits' => $this->edits,
48
+            'period' => $this->period,
49
+        ];
50
+    }
51
+
52
+    /**
53
+     * @return array<string, string>
54
+     */
55
+    protected function casts(): array
56
+    {
57
+        return [
58
+            'price' => 'integer',
59
+            'stores' => 'integer',
60
+            'regenerations' => 'integer',
61
+            'edits' => 'integer',
62
+            'sort' => 'integer',
63
+        ];
64
+    }
65
+}

+ 69
- 0
app/Models/Subscription.php Ver fichero

@@ -0,0 +1,69 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Carbon\CarbonInterface;
6
+use Database\Factories\SubscriptionFactory;
7
+use Illuminate\Database\Eloquent\Factories\HasFactory;
8
+use Illuminate\Database\Eloquent\Model;
9
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
10
+
11
+/**
12
+ * A merchant's paid plan, kept in step with Stripe.
13
+ *
14
+ * @property int $id
15
+ * @property int $user_id
16
+ * @property int|null $plan_id
17
+ * @property string|null $stripe_customer_id
18
+ * @property string|null $stripe_subscription_id
19
+ * @property string|null $status
20
+ * @property CarbonInterface|null $current_period_end
21
+ * @property bool $cancel_at_period_end
22
+ * @property-read Plan|null $plan
23
+ * @property-read User $user
24
+ */
25
+class Subscription extends Model
26
+{
27
+    /** @use HasFactory<SubscriptionFactory> */
28
+    use HasFactory;
29
+
30
+    /**
31
+     * Stripe states in which the merchant keeps their plan.
32
+     * "past_due" is included: a card failed, and Stripe is still retrying it.
33
+     *
34
+     * @var list<string>
35
+     */
36
+    public const array ACTIVE_STATUSES = ['active', 'trialing', 'past_due'];
37
+
38
+    /**
39
+     * @return BelongsTo<User, $this>
40
+     */
41
+    public function user(): BelongsTo
42
+    {
43
+        return $this->belongsTo(User::class);
44
+    }
45
+
46
+    /**
47
+     * @return BelongsTo<Plan, $this>
48
+     */
49
+    public function plan(): BelongsTo
50
+    {
51
+        return $this->belongsTo(Plan::class);
52
+    }
53
+
54
+    public function isActive(): bool
55
+    {
56
+        return $this->plan_id !== null && in_array($this->status, self::ACTIVE_STATUSES, true);
57
+    }
58
+
59
+    /**
60
+     * @return array<string, string>
61
+     */
62
+    protected function casts(): array
63
+    {
64
+        return [
65
+            'current_period_end' => 'datetime',
66
+            'cancel_at_period_end' => 'boolean',
67
+        ];
68
+    }
69
+}

+ 43
- 2
app/Models/User.php Ver fichero

@@ -2,12 +2,14 @@
2 2
 
3 3
 namespace App\Models;
4 4
 
5
+use Carbon\CarbonInterface;
5 6
 use Database\Factories\UserFactory;
6 7
 use Illuminate\Contracts\Auth\MustVerifyEmail;
7 8
 use Illuminate\Database\Eloquent\Attributes\Fillable;
8 9
 use Illuminate\Database\Eloquent\Attributes\Hidden;
9 10
 use Illuminate\Database\Eloquent\Factories\HasFactory;
10 11
 use Illuminate\Database\Eloquent\Relations\HasMany;
12
+use Illuminate\Database\Eloquent\Relations\HasOne;
11 13
 use Illuminate\Foundation\Auth\User as Authenticatable;
12 14
 use Illuminate\Notifications\Notifiable;
13 15
 use Illuminate\Support\Carbon;
@@ -17,7 +19,8 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
17 19
  * @property int $id
18 20
  * @property string $name
19 21
  * @property string $email
20
- * @property string $plan
22
+ * @property CarbonInterface|null $trial_ends_at
23
+ * @property-read Subscription|null $subscription
21 24
  * @property Carbon|null $email_verified_at
22 25
  * @property string $password
23 26
  * @property string|null $two_factor_secret
@@ -28,7 +31,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
28 31
  * @property Carbon|null $updated_at
29 32
  */
30 33
 #[Fillable(['name', 'email', 'password'])]
31
-#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
34
+#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token', 'subscription'])]
32 35
 class User extends Authenticatable implements MustVerifyEmail
33 36
 {
34 37
     /** @use HasFactory<UserFactory> */
@@ -45,9 +48,47 @@ class User extends Authenticatable implements MustVerifyEmail
45 48
             'email_verified_at' => 'datetime',
46 49
             'password' => 'hashed',
47 50
             'two_factor_confirmed_at' => 'datetime',
51
+            'trial_ends_at' => 'datetime',
48 52
         ];
49 53
     }
50 54
 
55
+    protected static function booted(): void
56
+    {
57
+        // Every new account starts with a free trial.
58
+        static::creating(function (User $user): void {
59
+            $user->trial_ends_at ??= now()->addDays((int) config('plans.trial_days', 14));
60
+        });
61
+    }
62
+
63
+    /**
64
+     * The paid plan, if this user ever started one.
65
+     *
66
+     * @return HasOne<Subscription, $this>
67
+     */
68
+    public function subscription(): HasOne
69
+    {
70
+        return $this->hasOne(Subscription::class);
71
+    }
72
+
73
+    public function onTrial(): bool
74
+    {
75
+        return $this->trial_ends_at !== null && $this->trial_ends_at->isFuture();
76
+    }
77
+
78
+    /**
79
+     * The plan this user is on right now: the paid plan, or the free trial while it lasts, or nothing.
80
+     */
81
+    public function currentPlan(): ?Plan
82
+    {
83
+        $subscription = $this->subscription;
84
+
85
+        if ($subscription !== null && $subscription->isActive()) {
86
+            return $subscription->plan;
87
+        }
88
+
89
+        return $this->onTrial() ? Plan::findByKey((string) config('plans.trial_plan')) : null;
90
+    }
91
+
51 92
     /**
52 93
      * The stores this user owns.
53 94
      *

+ 3
- 0
app/Providers/AppServiceProvider.php Ver fichero

@@ -2,6 +2,8 @@
2 2
 
3 3
 namespace App\Providers;
4 4
 
5
+use App\Billing\StripeSubscriptionGateway;
6
+use App\Billing\SubscriptionGateway;
5 7
 use App\Commerce\Payments\PaymentGateway;
6 8
 use App\Commerce\Payments\StripeGateway;
7 9
 use Carbon\CarbonImmutable;
@@ -19,6 +21,7 @@ class AppServiceProvider extends ServiceProvider
19 21
     {
20 22
         // Payments go through one interface, so the provider can be changed in one place.
21 23
         $this->app->bind(PaymentGateway::class, StripeGateway::class);
24
+        $this->app->bind(SubscriptionGateway::class, StripeSubscriptionGateway::class);
22 25
     }
23 26
 
24 27
     /**

+ 3
- 0
app/Storefront/Storefront.php Ver fichero

@@ -38,6 +38,9 @@ final readonly class Storefront
38 38
         if (is_string($liveSlug)) {
39 39
             $store = Store::query()->published()->where('slug', $liveSlug)->firstOrFail();
40 40
 
41
+            // A store is only live while its owner has a plan: a paid one, or a free trial that has not ended.
42
+            abort_if($store->user->currentPlan() === null, 404);
43
+
41 44
             return new self($store, $store->published_plan ?? [], '', false, $request->getSchemeAndHttpHost());
42 45
         }
43 46
 

+ 8
- 17
config/plans.php Ver fichero

@@ -2,32 +2,23 @@
2 2
 
3 3
 /*
4 4
 |--------------------------------------------------------------------------
5
-| Pricing plans and their limits
5
+| Pricing plans
6 6
 |--------------------------------------------------------------------------
7 7
 |
8
-| Starting numbers, to adjust after real usage. Keep in step with PROGRESS.md.
9
-|
10
-| "period" says how usage is counted:
11
-|   - "total": over the whole life of the account (free trial)
12
-|   - "month": since the first day of the current month
13
-|
14
-| "regenerations" counts full redesigns of a store that already has a design.
15
-| The first design of a store is free and does not count.
8
+| The plans themselves (prices and limits) live in the "plans" database table.
9
+| This file holds the few settings around them.
16 10
 |
17 11
 */
18 12
 
19 13
 return [
20 14
 
21
-    'default' => 'trial',
15
+    // The plan every new account starts on.
16
+    'trial_plan' => 'trial',
22 17
 
23
-    'plans' => [
24
-        'trial' => ['name' => 'Free trial', 'price' => 0, 'stores' => 1, 'regenerations' => 2, 'edits' => 30, 'period' => 'total'],
25
-        'starter' => ['name' => 'Starter', 'price' => 39, 'stores' => 1, 'regenerations' => 3, 'edits' => 100, 'period' => 'month'],
26
-        'growth' => ['name' => 'Growth', 'price' => 99, 'stores' => 3, 'regenerations' => 10, 'edits' => 500, 'period' => 'month'],
27
-        'pro' => ['name' => 'Pro', 'price' => 249, 'stores' => 10, 'regenerations' => 30, 'edits' => 2000, 'period' => 'month'],
28
-    ],
18
+    // How long the free trial lasts.
19
+    'trial_days' => 14,
29 20
 
30
-    // A job that has been waiting or running longer than this is treated as failed.
21
+    // An AI job that has been waiting or running longer than this is treated as failed.
31 22
     'stale_after_minutes' => 10,
32 23
 
33 24
 ];

+ 40
- 0
database/factories/SubscriptionFactory.php Ver fichero

@@ -0,0 +1,40 @@
1
+<?php
2
+
3
+namespace Database\Factories;
4
+
5
+use App\Models\Plan;
6
+use App\Models\Subscription;
7
+use App\Models\User;
8
+use Illuminate\Database\Eloquent\Factories\Factory;
9
+
10
+/**
11
+ * @extends Factory<Subscription>
12
+ */
13
+class SubscriptionFactory extends Factory
14
+{
15
+    /**
16
+     * @return array<string, mixed>
17
+     */
18
+    public function definition(): array
19
+    {
20
+        return [
21
+            'user_id' => User::factory(),
22
+            'plan_id' => fn () => Plan::findByKey('starter')?->id,
23
+            'stripe_customer_id' => 'cus_'.fake()->unique()->lexify('????????'),
24
+            'stripe_subscription_id' => 'sub_'.fake()->unique()->lexify('????????'),
25
+            'status' => 'active',
26
+            'current_period_end' => now()->addMonth(),
27
+            'cancel_at_period_end' => false,
28
+        ];
29
+    }
30
+
31
+    public function plan(string $key): static
32
+    {
33
+        return $this->state(['plan_id' => fn () => Plan::findByKey($key)?->id]);
34
+    }
35
+
36
+    public function status(string $status): static
37
+    {
38
+        return $this->state(['status' => $status]);
39
+    }
40
+}

+ 76
- 0
database/migrations/2026_11_15_000001_create_billing_tables.php Ver fichero

@@ -0,0 +1,76 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\DB;
6
+use Illuminate\Support\Facades\Schema;
7
+
8
+return new class extends Migration
9
+{
10
+    public function up(): void
11
+    {
12
+        // What we sell to merchants. Prices are in sen (1 ringgit = 100 sen).
13
+        Schema::create('plans', function (Blueprint $table) {
14
+            $table->id();
15
+            $table->string('key')->unique();
16
+            $table->string('name');
17
+            $table->unsignedInteger('price');
18
+            $table->unsignedInteger('stores');
19
+            $table->unsignedInteger('regenerations');
20
+            $table->unsignedInteger('edits');
21
+            // "total": counted over the whole life of the account (free trial).
22
+            // "month": counted since the first day of the current month.
23
+            $table->string('period')->default('month');
24
+            // Filled in the first time someone subscribes to the plan.
25
+            $table->string('stripe_product_id')->nullable();
26
+            $table->string('stripe_price_id')->nullable();
27
+            $table->unsignedSmallInteger('sort')->default(0);
28
+            $table->timestamps();
29
+        });
30
+
31
+        $now = now();
32
+
33
+        // Starting numbers, to adjust after real usage. Keep in step with PROGRESS.md.
34
+        DB::table('plans')->insert([
35
+            ['key' => 'trial', 'name' => 'Free trial', 'price' => 0, 'stores' => 1, 'regenerations' => 2, 'edits' => 30, 'period' => 'total', 'sort' => 0, 'created_at' => $now, 'updated_at' => $now],
36
+            ['key' => 'starter', 'name' => 'Starter', 'price' => 3900, 'stores' => 1, 'regenerations' => 3, 'edits' => 100, 'period' => 'month', 'sort' => 1, 'created_at' => $now, 'updated_at' => $now],
37
+            ['key' => 'growth', 'name' => 'Growth', 'price' => 9900, 'stores' => 3, 'regenerations' => 10, 'edits' => 500, 'period' => 'month', 'sort' => 2, 'created_at' => $now, 'updated_at' => $now],
38
+            ['key' => 'pro', 'name' => 'Pro', 'price' => 24900, 'stores' => 10, 'regenerations' => 30, 'edits' => 2000, 'period' => 'month', 'sort' => 3, 'created_at' => $now, 'updated_at' => $now],
39
+        ]);
40
+
41
+        // One row per paying account, kept in step with Stripe.
42
+        Schema::create('subscriptions', function (Blueprint $table) {
43
+            $table->id();
44
+            $table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete();
45
+            $table->foreignId('plan_id')->nullable()->constrained();
46
+            $table->string('stripe_customer_id')->nullable()->index();
47
+            $table->string('stripe_subscription_id')->nullable()->unique();
48
+            // Stripe's own word for the state: active, past_due, canceled, incomplete and so on.
49
+            $table->string('status')->nullable();
50
+            // When the paid-for period ends. With "cancel_at_period_end" this is the last day of access.
51
+            $table->timestamp('current_period_end')->nullable();
52
+            $table->boolean('cancel_at_period_end')->default(false);
53
+            $table->timestamps();
54
+        });
55
+
56
+        Schema::table('users', function (Blueprint $table) {
57
+            $table->timestamp('trial_ends_at')->nullable()->after('email_verified_at');
58
+            // Replaced by the trial date above and the subscriptions table.
59
+            $table->dropColumn('plan');
60
+        });
61
+
62
+        // Accounts that already exist start their trial now.
63
+        DB::table('users')->update(['trial_ends_at' => now()->addDays((int) config('plans.trial_days', 14))]);
64
+    }
65
+
66
+    public function down(): void
67
+    {
68
+        Schema::table('users', function (Blueprint $table) {
69
+            $table->dropColumn('trial_ends_at');
70
+            $table->string('plan')->default('trial')->after('email');
71
+        });
72
+
73
+        Schema::dropIfExists('subscriptions');
74
+        Schema::dropIfExists('plans');
75
+    }
76
+};

+ 7
- 1
resources/js/components/app-sidebar.tsx Ver fichero

@@ -1,5 +1,6 @@
1 1
 import { Link } from '@inertiajs/react';
2
-import { BookOpen, FolderGit2, LayoutGrid } from 'lucide-react';
2
+import { BookOpen, CreditCard, FolderGit2, LayoutGrid } from 'lucide-react';
3
+import BillingController from '@/actions/App/Http/Controllers/BillingController';
3 4
 import AppLogo from '@/components/app-logo';
4 5
 import { NavFooter } from '@/components/nav-footer';
5 6
 import { NavMain } from '@/components/nav-main';
@@ -22,6 +23,11 @@ const mainNavItems: NavItem[] = [
22 23
         href: dashboard(),
23 24
         icon: LayoutGrid,
24 25
     },
26
+    {
27
+        title: 'Billing',
28
+        href: BillingController.index(),
29
+        icon: CreditCard,
30
+    },
25 31
 ];
26 32
 
27 33
 const footerNavItems: NavItem[] = [

+ 53
- 0
resources/js/components/plan-notice.tsx Ver fichero

@@ -0,0 +1,53 @@
1
+import { Link } from '@inertiajs/react';
2
+import BillingController from '@/actions/App/Http/Controllers/BillingController';
3
+import { Button } from '@/components/ui/button';
4
+import type { Usage } from '@/types';
5
+
6
+/** Whole days from now until the given moment, never below zero. */
7
+export function daysLeft(iso: string | null): number {
8
+    if (!iso) {
9
+        return 0;
10
+    }
11
+
12
+    return Math.max(
13
+        0,
14
+        Math.ceil((new Date(iso).getTime() - Date.now()) / 86_400_000),
15
+    );
16
+}
17
+
18
+/**
19
+ * A short reminder about the free trial, or that it has ended. Shows nothing for paying merchants.
20
+ */
21
+export default function PlanNotice({ usage }: { usage: Usage }) {
22
+    if (usage.active && !usage.on_trial) {
23
+        return null;
24
+    }
25
+
26
+    const days = daysLeft(usage.trial_ends_at);
27
+
28
+    return (
29
+        <div
30
+            className={
31
+                usage.active
32
+                    ? 'flex flex-wrap items-center justify-between gap-3 rounded-xl border p-4 text-sm'
33
+                    : 'flex flex-wrap items-center justify-between gap-3 rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200'
34
+            }
35
+            data-test="plan-notice"
36
+        >
37
+            <p>
38
+                {usage.active
39
+                    ? `You are on the free trial. ${days === 1 ? '1 day' : `${days} days`} left.`
40
+                    : 'Your free trial has ended. Your stores are offline until you choose a plan.'}
41
+            </p>
42
+            <Button
43
+                asChild
44
+                size="sm"
45
+                variant={usage.active ? 'outline' : 'default'}
46
+            >
47
+                <Link href={BillingController.index.url()}>
48
+                    {usage.active ? 'See plans' : 'Choose a plan'}
49
+                </Link>
50
+            </Button>
51
+        </div>
52
+    );
53
+}

+ 339
- 0
resources/js/pages/billing/index.tsx Ver fichero

@@ -0,0 +1,339 @@
1
+import { Form, Head } from '@inertiajs/react';
2
+import { Check } from 'lucide-react';
3
+import BillingController from '@/actions/App/Http/Controllers/BillingController';
4
+import Heading from '@/components/heading';
5
+import { daysLeft } from '@/components/plan-notice';
6
+import { Badge } from '@/components/ui/badge';
7
+import { Button } from '@/components/ui/button';
8
+import {
9
+    Card,
10
+    CardContent,
11
+    CardDescription,
12
+    CardHeader,
13
+    CardTitle,
14
+} from '@/components/ui/card';
15
+import {
16
+    Dialog,
17
+    DialogClose,
18
+    DialogContent,
19
+    DialogDescription,
20
+    DialogFooter,
21
+    DialogHeader,
22
+    DialogTitle,
23
+    DialogTrigger,
24
+} from '@/components/ui/dialog';
25
+import { formatRinggit } from '@/lib/money';
26
+import { cn } from '@/lib/utils';
27
+import { dashboard } from '@/routes';
28
+import type { Plan, SubscriptionSummary, Usage, UsageCount } from '@/types';
29
+
30
+const dateFormat = new Intl.DateTimeFormat('en-MY', { dateStyle: 'long' });
31
+
32
+function formatDate(iso: string | null): string {
33
+    return iso ? dateFormat.format(new Date(iso)) : '';
34
+}
35
+
36
+function Meter({
37
+    label,
38
+    usage,
39
+    note,
40
+}: {
41
+    label: string;
42
+    usage: UsageCount;
43
+    note: string;
44
+}) {
45
+    const percent =
46
+        usage.limit > 0
47
+            ? Math.min(100, Math.round((usage.used / usage.limit) * 100))
48
+            : 100;
49
+    const full = usage.used >= usage.limit;
50
+
51
+    return (
52
+        <div>
53
+            <div className="flex items-baseline justify-between gap-3 text-sm">
54
+                <span className="font-medium">{label}</span>
55
+                <span className="whitespace-nowrap text-muted-foreground tabular-nums">
56
+                    {usage.used} of {usage.limit}
57
+                </span>
58
+            </div>
59
+            <div
60
+                className="mt-2 h-2 overflow-hidden rounded-full bg-muted"
61
+                role="progressbar"
62
+                aria-label={label}
63
+                aria-valuemin={0}
64
+                aria-valuemax={usage.limit}
65
+                aria-valuenow={Math.min(usage.used, usage.limit)}
66
+            >
67
+                <div
68
+                    className={cn(
69
+                        'h-full rounded-full',
70
+                        full ? 'bg-amber-500' : 'bg-foreground',
71
+                    )}
72
+                    style={{ width: `${percent}%` }}
73
+                />
74
+            </div>
75
+            <p className="mt-1.5 text-xs text-muted-foreground">{note}</p>
76
+        </div>
77
+    );
78
+}
79
+
80
+export default function BillingIndex({
81
+    usage,
82
+    plans,
83
+    subscription,
84
+}: {
85
+    usage: Usage;
86
+    plans: Plan[];
87
+    subscription: SubscriptionSummary | null;
88
+}) {
89
+    const paying = subscription?.active ?? false;
90
+    const ending = paying && subscription?.cancel_at_period_end;
91
+    const pastDue = subscription?.status === 'past_due';
92
+    const counted = usage.period === 'month' ? 'this month' : 'in total';
93
+    const trialDays = daysLeft(usage.trial_ends_at);
94
+
95
+    return (
96
+        <>
97
+            <Head title="Billing" />
98
+
99
+            <div className="mx-auto w-full max-w-5xl space-y-8 p-4">
100
+                <Heading
101
+                    title="Billing"
102
+                    description="Your plan, what it includes, and how much you have used."
103
+                />
104
+
105
+                <Card>
106
+                    <CardHeader>
107
+                        <div className="flex flex-wrap items-center gap-3">
108
+                            <CardTitle>{usage.plan_name}</CardTitle>
109
+                            {usage.on_trial && (
110
+                                <Badge variant="secondary">Free trial</Badge>
111
+                            )}
112
+                            {paying && !ending && !pastDue && (
113
+                                <Badge>Active</Badge>
114
+                            )}
115
+                            {ending && (
116
+                                <Badge variant="secondary">Ending</Badge>
117
+                            )}
118
+                            {pastDue && (
119
+                                <Badge variant="destructive">
120
+                                    Payment failed
121
+                                </Badge>
122
+                            )}
123
+                        </div>
124
+                        <CardDescription data-test="plan-status">
125
+                            {!usage.active &&
126
+                                'Your free trial has ended. Your stores are offline and AI is switched off until you choose a plan below.'}
127
+                            {usage.on_trial &&
128
+                                `Your free trial ends on ${formatDate(usage.trial_ends_at)} (${trialDays === 1 ? '1 day' : `${trialDays} days`} left). Choose a plan below to keep your stores online after that.`}
129
+                            {paying &&
130
+                                !ending &&
131
+                                !pastDue &&
132
+                                `Renews on ${formatDate(subscription?.current_period_end ?? null)}.`}
133
+                            {ending &&
134
+                                `Your plan ends on ${formatDate(subscription?.current_period_end ?? null)}. After that your stores go offline.`}
135
+                            {pastDue &&
136
+                                'Your last payment did not go through. We will try again; please check your card.'}
137
+                        </CardDescription>
138
+                    </CardHeader>
139
+                    <CardContent className="space-y-6">
140
+                        <div className="grid gap-6 md:grid-cols-3">
141
+                            <Meter
142
+                                label="Stores"
143
+                                usage={usage.stores}
144
+                                note="Stores you have created"
145
+                            />
146
+                            <Meter
147
+                                label="Regenerations"
148
+                                usage={usage.regenerations}
149
+                                note={`Full redesigns ${counted}`}
150
+                            />
151
+                            <Meter
152
+                                label="AI edits"
153
+                                usage={usage.edits}
154
+                                note={`Changes by chat ${counted}`}
155
+                            />
156
+                        </div>
157
+
158
+                        {paying && (
159
+                            <div className="border-t pt-4">
160
+                                {ending ? (
161
+                                    <Form {...BillingController.resume.form()}>
162
+                                        {({ processing }) => (
163
+                                            <Button
164
+                                                variant="outline"
165
+                                                size="sm"
166
+                                                disabled={processing}
167
+                                                data-test="resume-plan-button"
168
+                                            >
169
+                                                Keep my plan
170
+                                            </Button>
171
+                                        )}
172
+                                    </Form>
173
+                                ) : (
174
+                                    <Dialog>
175
+                                        <DialogTrigger asChild>
176
+                                            <Button
177
+                                                variant="ghost"
178
+                                                size="sm"
179
+                                                className="text-muted-foreground"
180
+                                                data-test="cancel-plan-button"
181
+                                            >
182
+                                                Cancel plan
183
+                                            </Button>
184
+                                        </DialogTrigger>
185
+                                        <DialogContent>
186
+                                            <DialogHeader>
187
+                                                <DialogTitle>
188
+                                                    Cancel your plan?
189
+                                                </DialogTitle>
190
+                                                <DialogDescription>
191
+                                                    You keep your plan until{' '}
192
+                                                    {formatDate(
193
+                                                        subscription?.current_period_end ??
194
+                                                            null,
195
+                                                    )}
196
+                                                    , and you will not be
197
+                                                    charged again. After that
198
+                                                    your stores go offline.
199
+                                                    Nothing is deleted, and you
200
+                                                    can come back any time.
201
+                                                </DialogDescription>
202
+                                            </DialogHeader>
203
+                                            <DialogFooter>
204
+                                                <DialogClose asChild>
205
+                                                    <Button variant="outline">
206
+                                                        Keep my plan
207
+                                                    </Button>
208
+                                                </DialogClose>
209
+                                                <Form
210
+                                                    {...BillingController.cancel.form()}
211
+                                                >
212
+                                                    {({ processing }) => (
213
+                                                        <Button
214
+                                                            variant="destructive"
215
+                                                            disabled={
216
+                                                                processing
217
+                                                            }
218
+                                                            data-test="confirm-cancel-plan-button"
219
+                                                        >
220
+                                                            Cancel plan
221
+                                                        </Button>
222
+                                                    )}
223
+                                                </Form>
224
+                                            </DialogFooter>
225
+                                        </DialogContent>
226
+                                    </Dialog>
227
+                                )}
228
+                            </div>
229
+                        )}
230
+                    </CardContent>
231
+                </Card>
232
+
233
+                <section className="space-y-4">
234
+                    <h2 className="font-medium">Plans</h2>
235
+
236
+                    <div className="grid gap-4 lg:grid-cols-3">
237
+                        {plans.map((plan) => {
238
+                            const current = paying && usage.plan === plan.key;
239
+
240
+                            return (
241
+                                <Card
242
+                                    key={plan.key}
243
+                                    className={cn(
244
+                                        'flex flex-col',
245
+                                        current && 'border-foreground',
246
+                                    )}
247
+                                >
248
+                                    <CardHeader>
249
+                                        <div className="flex items-center justify-between gap-3">
250
+                                            <CardTitle>{plan.name}</CardTitle>
251
+                                            {current && (
252
+                                                <Badge>Your plan</Badge>
253
+                                            )}
254
+                                        </div>
255
+                                        <p className="text-2xl font-semibold tabular-nums">
256
+                                            {formatRinggit(plan.price)}
257
+                                            <span className="text-sm font-normal text-muted-foreground">
258
+                                                {' '}
259
+                                                / month
260
+                                            </span>
261
+                                        </p>
262
+                                    </CardHeader>
263
+                                    <CardContent className="flex flex-1 flex-col gap-5">
264
+                                        <ul className="space-y-2 text-sm">
265
+                                            {[
266
+                                                plan.stores === 1
267
+                                                    ? '1 store'
268
+                                                    : `${plan.stores} stores`,
269
+                                                `${plan.regenerations} full redesigns a month`,
270
+                                                `${plan.edits.toLocaleString('en-MY')} AI edits a month`,
271
+                                                'Your own store address',
272
+                                            ].map((feature) => (
273
+                                                <li
274
+                                                    key={feature}
275
+                                                    className="flex gap-2"
276
+                                                >
277
+                                                    <Check className="mt-0.5 size-4 shrink-0 text-green-600 dark:text-green-400" />
278
+                                                    {feature}
279
+                                                </li>
280
+                                            ))}
281
+                                        </ul>
282
+
283
+                                        <Form
284
+                                            {...BillingController.subscribe.form()}
285
+                                            className="mt-auto"
286
+                                        >
287
+                                            {({ processing }) => (
288
+                                                <>
289
+                                                    <input
290
+                                                        type="hidden"
291
+                                                        name="plan"
292
+                                                        value={plan.key}
293
+                                                    />
294
+                                                    <Button
295
+                                                        className="w-full"
296
+                                                        variant={
297
+                                                            current
298
+                                                                ? 'outline'
299
+                                                                : 'default'
300
+                                                        }
301
+                                                        disabled={
302
+                                                            processing ||
303
+                                                            current
304
+                                                        }
305
+                                                        data-test={`choose-plan-${plan.key}`}
306
+                                                    >
307
+                                                        {current
308
+                                                            ? 'Current plan'
309
+                                                            : paying
310
+                                                              ? `Switch to ${plan.name}`
311
+                                                              : `Choose ${plan.name}`}
312
+                                                    </Button>
313
+                                                </>
314
+                                            )}
315
+                                        </Form>
316
+                                    </CardContent>
317
+                                </Card>
318
+                            );
319
+                        })}
320
+                    </div>
321
+
322
+                    <p className="text-xs text-muted-foreground">
323
+                        Prices are in Malaysian Ringgit. You pay on a secure
324
+                        Stripe page. When you switch plans, the difference for
325
+                        the rest of the month is charged or credited on your
326
+                        next bill.
327
+                    </p>
328
+                </section>
329
+            </div>
330
+        </>
331
+    );
332
+}
333
+
334
+BillingIndex.layout = {
335
+    breadcrumbs: [
336
+        { title: 'Dashboard', href: dashboard() },
337
+        { title: 'Billing', href: '#' },
338
+    ],
339
+};

+ 11
- 2
resources/js/pages/dashboard.tsx Ver fichero

@@ -11,14 +11,23 @@ import {
11 11
 } from '@/components/ui/card';
12 12
 import { dashboard } from '@/routes';
13 13
 import { create, show } from '@/routes/stores';
14
-import type { Store } from '@/types';
14
+import PlanNotice from '@/components/plan-notice';
15
+import type { Store, Usage } from '@/types';
15 16
 
16
-export default function Dashboard({ stores }: { stores: Store[] }) {
17
+export default function Dashboard({
18
+    stores,
19
+    usage,
20
+}: {
21
+    stores: Store[];
22
+    usage: Usage;
23
+}) {
17 24
     return (
18 25
         <>
19 26
             <Head title="Dashboard" />
20 27
 
21 28
             <div className="flex h-full flex-1 flex-col gap-6 p-4">
29
+                <PlanNotice usage={usage} />
30
+
22 31
                 <div className="flex flex-wrap items-center justify-between gap-4">
23 32
                     <div>
24 33
                         <h1 className="text-xl font-semibold">Your stores</h1>

+ 26
- 1
resources/js/types/store.ts Ver fichero

@@ -39,9 +39,14 @@ export type UsageCount = {
39 39
 };
40 40
 
41 41
 export type Usage = {
42
-    plan: string;
42
+    /** False when the free trial is over and there is no paid plan. */
43
+    active: boolean;
44
+    plan: string | null;
43 45
     plan_name: string;
44 46
     period: 'total' | 'month';
47
+    on_trial: boolean;
48
+    trial_ends_at: string | null;
49
+    stores: UsageCount;
45 50
     regenerations: UsageCount;
46 51
     edits: UsageCount;
47 52
 };
@@ -96,3 +101,23 @@ export type Order = {
96 101
         line_total: number;
97 102
     }[];
98 103
 };
104
+
105
+/** A plan we sell. The price is in ringgit per month. */
106
+export type Plan = {
107
+    key: string;
108
+    name: string;
109
+    price: number;
110
+    stores: number;
111
+    regenerations: number;
112
+    edits: number;
113
+    period: 'total' | 'month';
114
+};
115
+
116
+/** The merchant's paid plan, as Stripe last reported it. */
117
+export type SubscriptionSummary = {
118
+    active: boolean;
119
+    status: string | null;
120
+    plan: string | null;
121
+    current_period_end: string | null;
122
+    cancel_at_period_end: boolean;
123
+};

+ 6
- 0
routes/web.php Ver fichero

@@ -1,5 +1,6 @@
1 1
 <?php
2 2
 
3
+use App\Http\Controllers\BillingController;
3 4
 use App\Http\Controllers\CartController;
4 5
 use App\Http\Controllers\CheckoutController;
5 6
 use App\Http\Controllers\OrderController;
@@ -53,6 +54,11 @@ Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webh
53 54
 Route::middleware(['auth', 'verified'])->group(function () {
54 55
     Route::get('dashboard', [StoreController::class, 'index'])->name('dashboard');
55 56
 
57
+    Route::get('billing', [BillingController::class, 'index'])->name('billing');
58
+    Route::post('billing/subscribe', [BillingController::class, 'subscribe'])->name('billing.subscribe');
59
+    Route::post('billing/cancel', [BillingController::class, 'cancel'])->name('billing.cancel');
60
+    Route::post('billing/resume', [BillingController::class, 'resume'])->name('billing.resume');
61
+
56 62
     Route::get('stores/create', [StoreController::class, 'create'])->name('stores.create');
57 63
     Route::post('stores', [StoreController::class, 'store'])->name('stores.store');
58 64
     Route::get('stores/{slug}', [StoreController::class, 'show'])->name('stores.show');

+ 325
- 0
tests/Feature/Billing/BillingTest.php Ver fichero

@@ -0,0 +1,325 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Billing;
4
+
5
+use App\Billing\SubscriptionGateway;
6
+use App\Models\Plan;
7
+use App\Models\Store;
8
+use App\Models\StoreGeneration;
9
+use App\Models\Subscription;
10
+use App\Models\User;
11
+use App\StorePlan\SamplePlan;
12
+use Illuminate\Foundation\Testing\RefreshDatabase;
13
+use Inertia\Testing\AssertableInertia as Assert;
14
+use Tests\Support\FakeSubscriptionGateway;
15
+use Tests\TestCase;
16
+
17
+class BillingTest extends TestCase
18
+{
19
+    use RefreshDatabase;
20
+
21
+    private FakeSubscriptionGateway $gateway;
22
+
23
+    protected function setUp(): void
24
+    {
25
+        parent::setUp();
26
+
27
+        $this->gateway = new FakeSubscriptionGateway;
28
+        $this->app->instance(SubscriptionGateway::class, $this->gateway);
29
+    }
30
+
31
+    /** Go through the payment page for a plan and come back. */
32
+    private function subscribe(User $user, string $plan): void
33
+    {
34
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => $plan])
35
+            ->assertRedirect('https://pay.test/cs_sub_1');
36
+
37
+        $this->gateway->complete('cs_sub_1');
38
+
39
+        $this->actingAs($user)->get(route('billing', ['session_id' => 'cs_sub_1']))->assertRedirect(route('billing'));
40
+    }
41
+
42
+    private function storeWithDesign(User $user): Store
43
+    {
44
+        $store = Store::factory()->for($user)->create();
45
+        $store->plan = SamplePlan::for($store);
46
+        $store->save();
47
+
48
+        return $store;
49
+    }
50
+
51
+    public function test_the_plans_match_the_price_table()
52
+    {
53
+        $this->assertSame(
54
+            [
55
+                ['trial', 0, 1, 2, 30, 'total'],
56
+                ['starter', 3900, 1, 3, 100, 'month'],
57
+                ['growth', 9900, 3, 10, 500, 'month'],
58
+                ['pro', 24900, 10, 30, 2000, 'month'],
59
+            ],
60
+            Plan::query()->orderBy('sort')->get()
61
+                ->map(fn (Plan $plan) => [$plan->key, $plan->price, $plan->stores, $plan->regenerations, $plan->edits, $plan->period])
62
+                ->all(),
63
+        );
64
+    }
65
+
66
+    public function test_a_new_account_starts_a_fourteen_day_free_trial()
67
+    {
68
+        $this->travelTo('2026-11-15 10:00:00');
69
+
70
+        $user = User::factory()->create();
71
+
72
+        $this->assertSame('2026-11-29 10:00:00', $user->trial_ends_at->toDateTimeString());
73
+        $this->assertSame('trial', $user->currentPlan()->key);
74
+
75
+        $this->actingAs($user)->get(route('billing'))
76
+            ->assertOk()
77
+            ->assertInertia(fn (Assert $page) => $page
78
+                ->component('billing/index')
79
+                ->where('usage.active', true)
80
+                ->where('usage.on_trial', true)
81
+                ->where('usage.plan', 'trial')
82
+                ->where('usage.stores.limit', 1)
83
+                ->where('usage.regenerations.limit', 2)
84
+                ->where('usage.edits.limit', 30)
85
+                ->where('subscription', null)
86
+                // Only paid plans are offered.
87
+                ->has('plans', 3)
88
+                ->where('plans.0.key', 'starter')
89
+                ->where('plans.0.price', 39)
90
+                ->where('plans.2.price', 249));
91
+    }
92
+
93
+    public function test_when_the_trial_ends_everything_is_switched_off_until_a_plan_is_chosen()
94
+    {
95
+        $user = User::factory()->create();
96
+        $store = $this->storeWithDesign($user);
97
+        $this->actingAs($user)->post(route('stores.publish', $store->slug));
98
+        auth()->logout();
99
+
100
+        $this->get('http://'.$store->slug.'.localhost/')->assertOk();
101
+
102
+        $this->travel(15)->days();
103
+
104
+        $this->assertNull($user->fresh()->currentPlan());
105
+
106
+        // The live store goes offline.
107
+        $this->get('http://'.$store->slug.'.localhost/')->assertNotFound();
108
+
109
+        $base = 'http://localhost';
110
+        $this->actingAs($user);
111
+
112
+        $this->get($base.route('billing', [], false))
113
+            ->assertInertia(fn (Assert $page) => $page
114
+                ->where('usage.active', false)
115
+                ->where('usage.plan', null)
116
+                ->where('usage.stores.limit', 0));
117
+
118
+        // No AI, no new stores, no publishing.
119
+        $this->post($base.route('stores.generate', $store->slug, false));
120
+        $this->post($base.route('stores.edits', $store->slug, false), ['instruction' => 'Make it blue']);
121
+        $this->assertSame(0, StoreGeneration::count());
122
+
123
+        $this->get($base.route('stores.create', [], false))->assertRedirect($base.route('billing', [], false));
124
+        $this->post($base.route('stores.store', [], false), ['name' => 'Second', 'category' => 'food', 'language' => 'en', 'description' => str_repeat('A good store. ', 3)]);
125
+        $this->assertSame(1, $user->stores()->count());
126
+
127
+        $this->post($base.route('stores.unpublish', $store->slug, false));
128
+        $this->post($base.route('stores.publish', $store->slug, false));
129
+        $this->assertFalse($store->fresh()->isPublished());
130
+
131
+        // Nothing is deleted: the merchant can still see the store and its design.
132
+        $this->get($base.route('stores.show', $store->slug, false))->assertOk();
133
+        $this->assertNotNull($store->fresh()->plan);
134
+    }
135
+
136
+    public function test_a_merchant_can_subscribe_and_the_plan_takes_effect()
137
+    {
138
+        $user = User::factory()->create();
139
+        $this->travel(20)->days();
140
+
141
+        $this->subscribe($user, 'growth');
142
+
143
+        $subscription = $user->fresh()->subscription;
144
+
145
+        $this->assertSame('cus_fake_'.$user->id, $subscription->stripe_customer_id);
146
+        $this->assertSame('sub_fake_2', $subscription->stripe_subscription_id);
147
+        $this->assertSame('active', $subscription->status);
148
+        $this->assertSame('growth', $subscription->plan->key);
149
+        $this->assertNotNull($subscription->current_period_end);
150
+        $this->assertSame('price_fake_growth', Plan::findByKey('growth')->stripe_price_id);
151
+        // The payment page sends the merchant back to the billing page.
152
+        $this->assertSame(route('billing'), $this->gateway->successUrl);
153
+
154
+        $this->actingAs($user)->get(route('billing'))
155
+            ->assertInertia(fn (Assert $page) => $page
156
+                ->where('usage.active', true)
157
+                ->where('usage.on_trial', false)
158
+                ->where('usage.plan', 'growth')
159
+                ->where('usage.period', 'month')
160
+                ->where('usage.stores.limit', 3)
161
+                ->where('usage.regenerations.limit', 10)
162
+                ->where('subscription.active', true)
163
+                ->where('subscription.plan', 'growth')
164
+                ->where('subscription.cancel_at_period_end', false));
165
+    }
166
+
167
+    public function test_an_unfinished_or_borrowed_payment_page_gives_no_plan()
168
+    {
169
+        $user = User::factory()->create();
170
+        $other = User::factory()->create();
171
+
172
+        // Started but never paid.
173
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'starter']);
174
+        $this->actingAs($user)->get(route('billing', ['session_id' => 'cs_sub_1']))->assertRedirect(route('billing'));
175
+        $this->assertNull($user->fresh()->subscription->stripe_subscription_id);
176
+
177
+        // Someone else pays, and this user tries to use their payment page id.
178
+        $this->actingAs($other)->post(route('billing.subscribe'), ['plan' => 'pro']);
179
+        $this->gateway->complete('cs_sub_2');
180
+        $this->actingAs($user)->get(route('billing', ['session_id' => 'cs_sub_2']));
181
+
182
+        $this->assertNull($user->fresh()->subscription->stripe_subscription_id);
183
+        $this->assertSame('trial', $user->fresh()->currentPlan()->key);
184
+    }
185
+
186
+    public function test_only_real_paid_plans_can_be_chosen()
187
+    {
188
+        $user = User::factory()->create();
189
+
190
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'trial'])->assertSessionHasErrors('plan');
191
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'enterprise'])->assertSessionHasErrors('plan');
192
+        $this->actingAs($user)->post(route('billing.subscribe'), [])->assertSessionHasErrors('plan');
193
+
194
+        $this->assertSame([], $this->gateway->checkouts);
195
+    }
196
+
197
+    public function test_a_paying_merchant_can_switch_plans_without_a_new_payment_page()
198
+    {
199
+        $user = User::factory()->create();
200
+        $this->subscribe($user, 'starter');
201
+
202
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'pro'])->assertRedirect(route('billing'));
203
+
204
+        $this->assertSame('pro', $user->fresh()->currentPlan()->key);
205
+        $this->assertSame('price_fake_pro', $this->gateway->subscriptions['sub_fake_2']->priceId);
206
+        $this->assertCount(1, $this->gateway->checkouts);
207
+
208
+        // And back down again.
209
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'starter']);
210
+
211
+        $this->assertSame('starter', $user->fresh()->currentPlan()->key);
212
+    }
213
+
214
+    public function test_cancelling_keeps_the_plan_until_the_period_ends_and_can_be_undone()
215
+    {
216
+        $user = User::factory()->create();
217
+        $this->subscribe($user, 'starter');
218
+
219
+        $this->actingAs($user)->post(route('billing.cancel'))->assertRedirect(route('billing'));
220
+
221
+        $subscription = $user->fresh()->subscription;
222
+        $this->assertTrue($subscription->cancel_at_period_end);
223
+        $this->assertTrue($subscription->isActive());
224
+        $this->assertSame('starter', $user->fresh()->currentPlan()->key);
225
+
226
+        $this->actingAs($user)->post(route('billing.resume'));
227
+        $this->assertFalse($user->fresh()->subscription->cancel_at_period_end);
228
+
229
+        // Later Stripe ends the subscription for good. The billing page picks that up by itself.
230
+        $this->travel(20)->days();
231
+        $this->gateway->setStatus('sub_fake_2', 'canceled');
232
+
233
+        $this->actingAs($user)->get(route('billing'))
234
+            ->assertInertia(fn (Assert $page) => $page
235
+                ->where('usage.active', false)
236
+                ->where('subscription.active', false)
237
+                ->where('subscription.status', 'canceled'));
238
+
239
+        $this->assertNull($user->fresh()->currentPlan());
240
+    }
241
+
242
+    public function test_cancel_and_resume_need_a_subscription()
243
+    {
244
+        $user = User::factory()->create();
245
+
246
+        $this->actingAs($user)->post(route('billing.cancel'))->assertRedirect(route('billing'));
247
+        $this->actingAs($user)->post(route('billing.resume'))->assertRedirect(route('billing'));
248
+
249
+        $this->assertNull($user->fresh()->subscription?->stripe_subscription_id);
250
+    }
251
+
252
+    public function test_a_failed_payment_keeps_the_plan_while_stripe_retries()
253
+    {
254
+        $user = User::factory()->create();
255
+        Subscription::factory()->for($user)->plan('growth')->status('past_due')->create();
256
+
257
+        $this->assertSame('growth', $user->fresh()->currentPlan()->key);
258
+
259
+        foreach (['canceled', 'unpaid', 'incomplete', 'incomplete_expired'] as $status) {
260
+            $user->subscription()->update(['status' => $status]);
261
+
262
+            $this->assertSame('trial', $user->fresh()->currentPlan()->key, "A [$status] subscription must not count as a plan.");
263
+        }
264
+    }
265
+
266
+    public function test_the_webhook_keeps_a_plan_in_step_with_stripe()
267
+    {
268
+        $user = User::factory()->create();
269
+        $this->subscribe($user, 'starter');
270
+        auth()->logout();
271
+
272
+        $this->gateway->setStatus('sub_fake_2', 'canceled');
273
+
274
+        $this->postJson(route('stripe.webhook'), ['subscription_id' => 'sub_fake_2'], ['Stripe-Signature' => 'forged'])->assertStatus(400);
275
+        $this->assertSame('active', $user->fresh()->subscription->status);
276
+
277
+        $this->postJson(route('stripe.webhook'), ['subscription_id' => 'sub_fake_2'], ['Stripe-Signature' => 'valid'])->assertOk();
278
+        $this->assertSame('canceled', $user->fresh()->subscription->status);
279
+    }
280
+
281
+    public function test_if_the_payment_service_is_down_the_merchant_sees_a_message_and_keeps_the_trial()
282
+    {
283
+        $user = User::factory()->create();
284
+        $this->gateway->down = true;
285
+
286
+        $this->actingAs($user)->post(route('billing.subscribe'), ['plan' => 'starter'])->assertRedirect(route('billing'));
287
+        $this->actingAs($user)->get(route('billing'))->assertOk();
288
+
289
+        $this->assertSame('trial', $user->fresh()->currentPlan()->key);
290
+    }
291
+
292
+    public function test_the_number_of_stores_is_limited_by_the_plan()
293
+    {
294
+        $user = User::factory()->create();
295
+        $data = fn (string $name) => ['name' => $name, 'category' => 'food', 'language' => 'en', 'description' => str_repeat('A good store. ', 3)];
296
+
297
+        $this->actingAs($user)->post(route('stores.store'), $data('One'));
298
+        $this->actingAs($user)->post(route('stores.store'), $data('Two'))->assertRedirect(route('billing'));
299
+        $this->actingAs($user)->get(route('stores.create'))->assertRedirect(route('billing'));
300
+
301
+        $this->assertSame(1, $user->stores()->count());
302
+
303
+        Subscription::factory()->for($user)->plan('growth')->create();
304
+        $user = $user->fresh();
305
+
306
+        $this->actingAs($user)->get(route('stores.create'))->assertOk();
307
+        $this->actingAs($user)->post(route('stores.store'), $data('Two'));
308
+        $this->actingAs($user)->post(route('stores.store'), $data('Three'));
309
+        $this->actingAs($user)->post(route('stores.store'), $data('Four'));
310
+
311
+        $this->assertSame(3, $user->stores()->count());
312
+
313
+        $this->actingAs($user)->get(route('dashboard'))
314
+            ->assertInertia(fn (Assert $page) => $page
315
+                ->where('usage.stores.used', 3)
316
+                ->where('usage.stores.limit', 3));
317
+    }
318
+
319
+    public function test_guests_cannot_open_billing()
320
+    {
321
+        $this->get(route('billing'))->assertRedirect(route('login'));
322
+        $this->post(route('billing.subscribe'), ['plan' => 'starter'])->assertRedirect(route('login'));
323
+        $this->post(route('billing.cancel'))->assertRedirect(route('login'));
324
+    }
325
+}

+ 4
- 5
tests/Feature/Stores/StoreGenerationTest.php Ver fichero

@@ -8,6 +8,7 @@ use App\Enums\GenerationType;
8 8
 use App\Jobs\RunStoreGeneration;
9 9
 use App\Models\Store;
10 10
 use App\Models\StoreGeneration;
11
+use App\Models\Subscription;
11 12
 use App\Models\User;
12 13
 use App\StorePlan\SamplePlan;
13 14
 use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -95,10 +96,9 @@ class StoreGenerationTest extends TestCase
95 96
         $this->assertSame(3, $store->generations()->count());
96 97
 
97 98
         // A bigger plan allows more.
98
-        $user->plan = 'starter';
99
-        $user->save();
99
+        Subscription::factory()->for($user)->plan('starter')->create();
100 100
 
101
-        $this->actingAs($user)->post(route('stores.generate', $store->slug));
101
+        $this->actingAs($user->fresh())->post(route('stores.generate', $store->slug));
102 102
 
103 103
         $this->assertSame(4, $store->generations()->count());
104 104
     }
@@ -106,8 +106,7 @@ class StoreGenerationTest extends TestCase
106 106
     public function test_monthly_plans_only_count_this_month()
107 107
     {
108 108
         $user = User::factory()->create();
109
-        $user->plan = 'starter';
110
-        $user->save();
109
+        Subscription::factory()->for($user)->plan('starter')->create();
111 110
         $store = Store::factory()->for($user)->create();
112 111
 
113 112
         StoreGeneration::factory()->for($store)->regeneration()->count(3)->create(['created_at' => now()->subMonths(2)]);

+ 3
- 0
tests/Feature/Stores/StoreTest.php Ver fichero

@@ -3,6 +3,7 @@
3 3
 namespace Tests\Feature\Stores;
4 4
 
5 5
 use App\Models\Store;
6
+use App\Models\Subscription;
6 7
 use App\Models\User;
7 8
 use Illuminate\Foundation\Testing\RefreshDatabase;
8 9
 use Inertia\Testing\AssertableInertia as Assert;
@@ -85,6 +86,8 @@ class StoreTest extends TestCase
85 86
     public function test_stores_with_the_same_name_get_different_slugs()
86 87
     {
87 88
         $user = User::factory()->create();
89
+        // The free trial allows one store; this plan allows three.
90
+        Subscription::factory()->for($user)->plan('growth')->create();
88 91
         $this->actingAs($user);
89 92
 
90 93
         $this->post(route('stores.store'), $this->validData());

+ 134
- 0
tests/Support/FakeSubscriptionGateway.php Ver fichero

@@ -0,0 +1,134 @@
1
+<?php
2
+
3
+namespace Tests\Support;
4
+
5
+use App\Billing\SubscriptionGateway;
6
+use App\Billing\SubscriptionState;
7
+use App\Commerce\Payments\CheckoutLink;
8
+use App\Commerce\Payments\PaymentException;
9
+use App\Models\Plan;
10
+use App\Models\User;
11
+
12
+/**
13
+ * A subscription provider for tests. Nothing leaves the machine.
14
+ * Tests decide whether a payment page was completed by calling complete().
15
+ */
16
+final class FakeSubscriptionGateway implements SubscriptionGateway
17
+{
18
+    /** @var array<string, SubscriptionState> Subscriptions by id. */
19
+    public array $subscriptions = [];
20
+
21
+    /** @var array<string, array{customer: string, price: string, subscription: string|null}> Payment pages by id. */
22
+    public array $checkouts = [];
23
+
24
+    public bool $down = false;
25
+
26
+    public ?string $successUrl = null;
27
+
28
+    private int $counter = 0;
29
+
30
+    public function createCustomer(User $user): string
31
+    {
32
+        $this->failIfDown();
33
+
34
+        return 'cus_fake_'.$user->id;
35
+    }
36
+
37
+    public function createPrice(Plan $plan): array
38
+    {
39
+        $this->failIfDown();
40
+
41
+        return ['product' => 'prod_fake_'.$plan->key, 'price' => 'price_fake_'.$plan->key];
42
+    }
43
+
44
+    public function startCheckout(string $customerId, string $priceId, string $successUrl, string $cancelUrl): CheckoutLink
45
+    {
46
+        $this->failIfDown();
47
+
48
+        $id = 'cs_sub_'.(++$this->counter);
49
+        $this->checkouts[$id] = ['customer' => $customerId, 'price' => $priceId, 'subscription' => null];
50
+        $this->successUrl = $successUrl;
51
+
52
+        return new CheckoutLink($id, 'https://pay.test/'.$id);
53
+    }
54
+
55
+    public function findByCheckout(string $checkoutId): ?SubscriptionState
56
+    {
57
+        $this->failIfDown();
58
+
59
+        $subscriptionId = $this->checkouts[$checkoutId]['subscription'] ?? null;
60
+
61
+        return $subscriptionId !== null ? $this->subscriptions[$subscriptionId] : null;
62
+    }
63
+
64
+    public function find(string $subscriptionId): SubscriptionState
65
+    {
66
+        $this->failIfDown();
67
+
68
+        return $this->subscriptions[$subscriptionId] ?? throw new PaymentException('Unknown subscription.');
69
+    }
70
+
71
+    public function changePrice(string $subscriptionId, string $priceId): SubscriptionState
72
+    {
73
+        return $this->replace($subscriptionId, priceId: $priceId, cancelAtPeriodEnd: false);
74
+    }
75
+
76
+    public function setCancelAtPeriodEnd(string $subscriptionId, bool $cancel): SubscriptionState
77
+    {
78
+        return $this->replace($subscriptionId, cancelAtPeriodEnd: $cancel);
79
+    }
80
+
81
+    public function readWebhook(string $payload, string $signature): ?SubscriptionState
82
+    {
83
+        if ($signature !== 'valid') {
84
+            throw new PaymentException('Bad signature.');
85
+        }
86
+
87
+        $data = json_decode($payload, true);
88
+
89
+        return isset($data['subscription_id']) ? $this->find($data['subscription_id']) : null;
90
+    }
91
+
92
+    /**
93
+     * Pretend the merchant paid on the payment page. Returns the new subscription id.
94
+     */
95
+    public function complete(string $checkoutId): string
96
+    {
97
+        $checkout = $this->checkouts[$checkoutId];
98
+        $id = 'sub_fake_'.(++$this->counter);
99
+
100
+        $this->subscriptions[$id] = new SubscriptionState($id, $checkout['customer'], 'active', $checkout['price'], now()->addMonth()->getTimestamp(), false);
101
+        $this->checkouts[$checkoutId]['subscription'] = $id;
102
+
103
+        return $id;
104
+    }
105
+
106
+    /**
107
+     * Pretend the provider changed the subscription by itself, for example after a failed payment.
108
+     */
109
+    public function setStatus(string $subscriptionId, string $status): void
110
+    {
111
+        $this->replace($subscriptionId, status: $status);
112
+    }
113
+
114
+    private function replace(string $subscriptionId, ?string $status = null, ?string $priceId = null, ?bool $cancelAtPeriodEnd = null): SubscriptionState
115
+    {
116
+        $current = $this->find($subscriptionId);
117
+
118
+        return $this->subscriptions[$subscriptionId] = new SubscriptionState(
119
+            $current->subscriptionId,
120
+            $current->customerId,
121
+            $status ?? $current->status,
122
+            $priceId ?? $current->priceId,
123
+            $current->currentPeriodEnd,
124
+            $cancelAtPeriodEnd ?? $current->cancelAtPeriodEnd,
125
+        );
126
+    }
127
+
128
+    private function failIfDown(): void
129
+    {
130
+        if ($this->down) {
131
+            throw new PaymentException('The provider is down.');
132
+        }
133
+    }
134
+}

+ 13
- 0
tests/TestCase.php Ver fichero

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

Loading…
Cancelar
Guardar