diff --git a/README.md b/README.md index 28baccb..bc1d033 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-rea - **Plan kinds**: free, subscription, lifetime and one-off - **Entitlements**: each plan turns features on and sets limits your app checks - **Pricing page** at `/pricing`, built from your plans +- **Promotions**: a launch or seasonal price on the pricing page, with what is left and until when, applied at checkout and ended on its own - **Billing settings**: current plan, invoices and saved card - **Catalogue sync** with Stripe, both ways - **Webhooks** that are safe to retry and handle events out of order @@ -93,10 +94,31 @@ payment_method.detached customer.updated ``` +A `503` answer in Stripe's webhook log is normal: an event arrived before the one it depends on (an invoice before its checkout), and Stripe's retry applies it. + Locally, forward them with `stripe listen --all-snapshot --forward-to localhost/billing/webhooks/stripe`. The rest is in the admin panel, under **Settings → Billing**: currency, checkout flow, grace period and trials. +## Promotions + +Show a discount on the pricing page, such as "$149 for the first 50 buyers", and apply it at checkout without the buyer typing a code. + +1. In Stripe, create a coupon and a promotion code for it, with any cap (*Limit the number of times this code can be redeemed*), end date, *First-time order only* and product limits. Stripe enforces all of them. +2. In the admin panel, under **Billing → Promotions**, add the code and tick the prices whose cards show it. Billing reads the discount, cap, end date and count from Stripe. + +A promotion written in code or a seeder, with no Stripe ID yet, is created at Stripe by **Push new to Stripe** (`billing:push-catalog`), as plans are: a coupon limited to its prices' products, and the code with its cap and end date. A code Stripe already has is adopted instead, but only if it makes the same offer: codes are shared by every app on one Stripe account, so a `LAUNCH` with other terms is left alone and the push warns you to rename yours. A promotion shows on the page only once it is at Stripe. It also warns when a promotion takes nothing off one of its prices, such as an amount off in euros on a dollar price. + +A price shows one promotion. Its card strikes the regular price through, shows the promotional one, and says how long it lasts on a subscription (the coupon's duration: first payment, a number of months, or forever), how many are left and until when. Checkout sends the code. The payment records the discount and the code, in the admin and in the customer's payments. + +The page reads stored data and never calls Stripe. Each completed checkout counts one redemption, and `billing:sync-catalog` (daily, and the *Sync* button) sets the count back to Stripe's. Once the cap is reached or the date passes, the page shows the regular price again, with no deploy. + +Stripe has the final word. If it has used up or expired the code before the page caught up, checkout opens at the regular price and says so above the pay button. + +## After a purchase + +A buyer coming back from the payment page lands on the Billing section of their settings, with a confirmation. An app that sells something to install can send them there instead: in the admin panel, under **Settings → Billing → Checkout**, choose the section in **After a purchase, open** (Packages, for the Packages module). An install or a template sets it with `--set=billing.after_checkout_section=modules`. The confirmation shows on whichever section opens. + ## Show plans on the homepage (optional) The plans live at `/pricing`. To also list them on the homepage, use core's `home::content.after` slot. Paths below are relative to the module's `resources/js/`. A flat install keeps one stack there; a checkout with both keeps them in `vue/` and `react/`, so use the folder of the stack you run. @@ -173,7 +195,7 @@ Run `npm run build` afterwards. php artisan modules:seed --module=billing --state=showcase ``` -Adds sample plans (pushed to Stripe when your keys are set), sample customers, and a staff account (`billing@saucebase.dev`) that only sees billing in the admin. All use the `DEMO_PASSWORD` from `.env`. +Adds sample plans and a launch promotion on Lifetime ($100 off for the first 50 buyers), pushed to Stripe when your keys are set, sample customers, and a staff account (`billing@saucebase.dev`) that only sees billing in the admin. All use the `DEMO_PASSWORD` from `.env`. ## License diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php index c7d01fb..98edc64 100644 --- a/database/factories/ProductFactory.php +++ b/database/factories/ProductFactory.php @@ -21,10 +21,11 @@ class ProductFactory extends Factory */ public function definition(): array { - $name = fake()->words(2, true).' Plan'; + $words = fake()->unique()->words(2, true); + $name = $words.' Plan'; return [ - 'sku' => strtoupper(Str::slug(fake()->unique()->word())), + 'sku' => strtoupper(Str::slug($words)), 'slug' => Str::slug($name), 'name' => $name, 'description' => fake()->sentence(12), diff --git a/database/factories/PromotionFactory.php b/database/factories/PromotionFactory.php new file mode 100644 index 0000000..b599f75 --- /dev/null +++ b/database/factories/PromotionFactory.php @@ -0,0 +1,33 @@ + + */ +class PromotionFactory extends Factory +{ + protected $model = Promotion::class; + + /** @return array */ + public function definition(): array + { + return [ + 'provider' => 'stripe', + 'provider_promotion_code_id' => 'promo_'.fake()->regexify('[A-Za-z0-9]{24}'), + 'code' => strtoupper(fake()->unique()->bothify('LAUNCH-####')), + 'percent_off' => null, + 'amount_off' => 1000, + 'currency' => 'USD', + 'duration' => 'once', + 'duration_in_months' => null, + 'max_redemptions' => null, + 'times_redeemed' => 0, + 'expires_at' => null, + 'is_active' => true, + ]; + } +} diff --git a/database/migrations/1000_00_02_000001_create_promotions_table.php b/database/migrations/1000_00_02_000001_create_promotions_table.php new file mode 100644 index 0000000..167af9b --- /dev/null +++ b/database/migrations/1000_00_02_000001_create_promotions_table.php @@ -0,0 +1,64 @@ +id(); + + $table->string('provider'); + // Null until pushed: a promotion drafted here (the demo's), like a price. + $table->string('provider_promotion_code_id')->nullable(); + $table->string('code'); + + // One of the two, as the provider's coupon has it. + $table->decimal('percent_off', 5, 2)->nullable(); + $table->unsignedBigInteger('amount_off')->nullable(); + $table->string('currency', 3)->nullable(); + + // once, repeating (for duration_in_months) or forever. + $table->string('duration')->default('once'); + $table->unsignedInteger('duration_in_months')->nullable(); + + $table->unsignedInteger('max_redemptions')->nullable(); + $table->unsignedInteger('times_redeemed')->default(0); + $table->timestamp('expires_at')->nullable(); + $table->boolean('is_active')->default(true); + + $table->timestamps(); + + $table->unique(['provider', 'provider_promotion_code_id']); + }); + + // One promotion per price, by construction. + Schema::table('prices', function (Blueprint $table) { + $table->foreignIdFor(Promotion::class)->nullable()->after('product_id')->constrained()->nullOnDelete(); + $table->index('promotion_id'); + }); + + // What the buyer saved, and with which code: kept on the payment, so it + // outlives the promotion. + Schema::table('payments', function (Blueprint $table) { + $table->unsignedBigInteger('discount_amount')->default(0)->after('amount_refunded'); + $table->string('promotion_code')->nullable()->after('discount_amount'); + }); + } + + public function down(): void + { + Schema::table('payments', fn (Blueprint $table) => $table->dropColumn(['discount_amount', 'promotion_code'])); + Schema::table('prices', fn (Blueprint $table) => $table->dropConstrainedForeignIdFor(Promotion::class)); + Schema::dropIfExists('promotions'); + } +}; diff --git a/database/seeders/ShowcaseBillingDatabaseSeeder.php b/database/seeders/ShowcaseBillingDatabaseSeeder.php index 5d4afbc..a90e8c6 100644 --- a/database/seeders/ShowcaseBillingDatabaseSeeder.php +++ b/database/seeders/ShowcaseBillingDatabaseSeeder.php @@ -70,12 +70,16 @@ private function pushToProvider(): void $push = app(CatalogPush::class); $products = 0; $prices = 0; + $promotions = 0; + $warnings = []; try { foreach (Product::whereIn('slug', ShowcaseProductSeeder::SLUGS)->get() as $product) { $report = $push->run($product); $products += $report->products; $prices += $report->prices; + $promotions += $report->promotions; + array_push($warnings, ...$report->promotionWarnings); } } catch (\Throwable $e) { $this->command->outputComponents()->warn("Billing: push failed ({$e->getMessage()}); run billing:push-catalog when the provider is reachable."); @@ -83,6 +87,10 @@ private function pushToProvider(): void return; } - $this->command->outputComponents()->info("Billing: pushed {$products} products and {$prices} prices to the provider."); + $this->command->outputComponents()->info("Billing: pushed {$products} products, {$prices} prices and {$promotions} promotions to the provider."); + + foreach ($warnings as $warning) { + $this->command->outputComponents()->warn("Billing: {$warning}"); + } } } diff --git a/database/seeders/ShowcaseProductSeeder.php b/database/seeders/ShowcaseProductSeeder.php index 25a8a22..f5d6973 100644 --- a/database/seeders/ShowcaseProductSeeder.php +++ b/database/seeders/ShowcaseProductSeeder.php @@ -7,6 +7,8 @@ use Modules\Billing\Enums\Currency; use Modules\Billing\Enums\PlanKind; use Modules\Billing\Models\Product; +use Modules\Billing\Models\Promotion; +use Modules\Billing\Settings\BillingSettings; /** * The demo site's plans, for a made-up developer tool. Between them they use @@ -75,6 +77,34 @@ public function run(): void ); } } + + $this->launchPromotion(); + } + + /** + * Lifetime at a launch price for the first 50 buyers, so the pricing page + * shows a promotion. Local until `CatalogPush` creates it at the provider; + * keyed on its code, and its terms set only once, so reseeding keeps the + * provider's ID and count. + */ + private function launchPromotion(): void + { + $lifetime = Product::where('slug', 'lifetime')->first()?->prices()->first(); + + if (! $lifetime) { + return; + } + + $promotion = Promotion::firstOrCreate(['code' => 'LAUNCH'], [ + 'provider' => app(BillingSettings::class)->gateway, + 'amount_off' => 10000, + 'currency' => Currency::default()->value, + 'duration' => 'once', + 'max_redemptions' => 50, + 'expires_at' => now()->addDays(60), + ]); + + $lifetime->update(['promotion_id' => $promotion->id]); } /** diff --git a/database/settings/0001_01_01_000020_add_after_checkout_section_to_billing_settings.php b/database/settings/0001_01_01_000020_add_after_checkout_section_to_billing_settings.php new file mode 100644 index 0000000..5e9f629 --- /dev/null +++ b/database/settings/0001_01_01_000020_add_after_checkout_section_to_billing_settings.php @@ -0,0 +1,14 @@ +migrator->exists('billing.after_checkout_section')) { + $this->migrator->add('billing.after_checkout_section', 'billing'); + } + } +}; diff --git a/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index a4c4e81..58e49bc 100644 --- a/resources/boost/skills/saucebase-billing-development/SKILL.md +++ b/resources/boost/skills/saucebase-billing-development/SKILL.md @@ -14,7 +14,7 @@ Subscription management, checkout sessions, payment processing, and webhook hand | Layer | Files | |-------|-------| | Controllers | `CheckoutController` (create, show, store), `SubscriptionController` (cancel, resume), `BillingPortalController` (portal redirect), `SettingsBillingController` (show), `WebhookController` (invoke) | -| Models | `Customer`, `Subscription`, `Product`, `Price`, `Payment`, `PaymentMethod`, `Invoice`, `CheckoutSession`, `WebhookEvent` | +| Models | `Customer`, `Subscription`, `Product`, `Price`, `Payment`, `PaymentMethod`, `Invoice`, `CheckoutSession`, `WebhookEvent`, `Promotion` | | Actions | One `handle()` each. `StartCheckout` (hand a checkout to the provider, creating the customer), `CompleteCheckout` (turn a paid checkout into its subscription or payment; the webhook and the return page both call it), `FulfillCheckout` (the return page: ask the provider, then complete), `CancelSubscription`, `ResumeSubscription`, `SuspendLapsedSubscription` (the grace sweep), `SyncPaymentMethod` (save a card the provider reports) | | Services | `WebhookHandler` — verifies, claims and routes provider events to their handlers, `PaymentGatewayManager` — driver manager (extends Laravel's Manager), `CatalogSync` — pulls products/prices from the provider, `CatalogPush` — creates local-only ones there | | Gateway | `StripeGateway` — implements `PaymentGatewayInterface` (create customer/session, cancel/resume, portal, webhook verify) | @@ -24,7 +24,7 @@ Subscription management, checkout sessions, payment processing, and webhook hand | Data | `CheckoutData`, `CheckoutResultData`, `WebhookData` (carries `occurredAt` for ordering), `CustomerData`, `AddressData`, `PaymentMethodData`, `PaymentMethodDetails` (Spatie Data objects) | | Commands | `EndGracePeriodsCommand` (`billing:end-grace-periods`, hourly, suspends subscriptions whose grace window closed), `ExpireCheckoutSessionsCommand` (every 30 min, marks abandoned/expired sessions and releases the trials they hold), `SyncCatalogCommand` (`billing:sync-catalog`, daily and on the admin's *Sync* button), `PushCatalogCommand` (`billing:push-catalog`, on the admin's *Push new* button). Both in `src/Console/Commands/`, which is where internachi discovers them | | Middleware | `RedirectToRegister` — redirects guests on checkout pages, stores intended URL | -| Filament | `BillingPlugin`, `BillingDashboard` (extends core's `Dashboard`, so it has the period picker), `Support\BillingMetrics` (every number on the cards: net revenue, MRR and active subscriptions at a date, estimated from `created_at` and `coalesce(ends_at, cancelled_at)` at today's price, churn, conversion, by plan; default currency only; each answer memoised per instance and cached 5 minutes, served stale up to 10 while it refreshes, except `pastDue()`), widgets `BillingSaasStatsWidget` (main dashboard too, sort 12, "Set up billing" without plans), `BillingHealthWidget`, `BillingAttentionWidget` (main dashboard, sort 20, only while something is past due or failed this week), and four charts, `ProductResource`, `SubscriptionResource`, `CustomerResource` | +| Filament | `BillingPlugin`, `BillingDashboard` (extends core's `Dashboard`, so it has the period picker), `Support\BillingMetrics` (every number on the cards: net revenue, MRR and active subscriptions at a date, estimated from `created_at` and `coalesce(ends_at, cancelled_at)` at today's price, churn, conversion, by plan; default currency only; each answer memoised per instance and cached 5 minutes, served stale up to 10 while it refreshes, except `pastDue()`), widgets `BillingSaasStatsWidget` (main dashboard too, sort 12, "Set up billing" without plans), `BillingHealthWidget`, `BillingAttentionWidget` (main dashboard, sort 20, only while something is past due or failed this week), and four charts, `ProductResource`, `SubscriptionResource`, `CustomerResource` (its page lists recent payments with their discount), `PromotionResource` (one `ManagePromotions` page, create/edit in modals) | | Owner | `Contracts\BillingOwner` + `Traits\Billable` on the User model (`billingCustomer()`, entitlements, `hasPaidPlan()`, `canManageBilling()`); `patches/user.patch` adds both. `Services\BillingOwners` says which owner a user acts for | | Pages | `SettingsBilling`, `Checkout` | @@ -78,7 +78,7 @@ On return, the provider sends the buyer to `settings.billing?checkout_session={o ### Webhook Processing `WebhookHandler::handle()`: 1. Calls `gateway->verifyAndParseWebhook()` — signature verification, then the gateway translates the event into a `WebhookEventType` and its typed data (`src/Data/Webhook/*`, one class per type: `WebhookEventType::dataClass()`). Handlers read it with `$webhook->dataAs(SubscriptionStateData::class)`, which throws on a mismatch. The module never reads provider JSON -2. Deduplicates by `(provider, provider_event_id)` in `webhook_events` — one atomic `UPDATE … WHERE processed_at IS NULL` claims the event, so concurrent deliveries cannot both run. A handler that throws hands the claim back (`processed_at` null), `WebhookController` answers 500, and Stripe's retry is processed rather than skipped. This is also how out-of-order delivery recovers: an invoice for a subscription that does not exist locally yet throws and is retried. +2. Deduplicates by `(provider, provider_event_id)` in `webhook_events` — one atomic `UPDATE … WHERE processed_at IS NULL` claims the event, so concurrent deliveries cannot both run. A handler that throws hands the claim back (`processed_at` null), `WebhookController` answers 500 (503 for a dependency not ready yet), and Stripe's retry is processed rather than skipped. This is also how out-of-order delivery recovers: an invoice for a subscription that does not exist locally yet throws and is retried. Retrying only helps when the missing row is still on its way, so `subscriptionForEvent()` splits the two cases: a subscription the app cannot find **under a customer it knows** throws and lets the provider retry, while one whose customer is also unknown is logged and acknowledged. Nothing here ever described that subscription — a foreign account, or a database rebuilt without it — so a 500 would have the provider retry forever. 3. Routes to private handlers via match on `WebhookEventType`: @@ -156,6 +156,15 @@ A new account takes the buyer's name and email; after that its details change on **Plan changes happen at the provider.** `GET /billing/plan/change` (`billing.plan.change`) sends the subscriber to `PaymentGatewayInterface::getPlanChangeUrl()` — Stripe's billing portal opened on its plan picker. Only the user's own current subscription is used; nothing in the request names one. The change comes back as `customer.subscription.updated`, and `onSubscriptionUpdated()` moves the row to the local price with that provider ID. A price not pulled yet is logged and skipped: the daily catalog sync and the next event put it right. Which plans the portal offers, whether downgrades wait for the period end, and how a switch is billed is the portal's configuration in the Stripe dashboard. With its defaults (`proration_behavior: none`, `billing_cycle_anchor: unchanged`) a monthly → yearly switch stretches the current period to a year and charges nothing until renewal — correct mirroring, not a bug here. +### Promotions +A `Promotion` is a provider promotion code the pricing page shows (sc-1240). Created at the provider; the admin attaches it by code (`ManagePromotions` → `findPromotion()`, stored with `fillFromProvider()`) and ticks prices. **One per price**: `prices.promotion_id`, so `PromotionResource::showOn()` moving a price takes it from any other promotion. + +- **Stored, never fetched to render.** `Promotion::available()` (at the provider — a local-only or conflicting one is never shown or sent — active, not expired, `times_redeemed < max_redemptions`) is the one rule. `Product::displayable()` eager-loads `prices.promotion` under it, so a spent one loads as null; `Price::promotional_amount` (appended, reads the loaded relation only, null otherwise) is `discountedAmount()` — percent off, or amount off in the price's own currency. Cards get `promotion` with `remaining`; the provider ID is hidden. `lib/promotion.ts` writes the notes (duration on a recurring price, N of M left, until date) for both stacks. +- **Applied.** `StartCheckout::settleRequest()` stores `coupon` = the typed code, else the price's available promotion code, so retries and replays send the same. +- **Provider decides.** `StripeGateway::resolvePromotionCode()` re-checks Stripe's own cap and date (`StripeEventMapper::promotionCode()`, tighter of code and coupon; inactive when the coupon is not `valid`). Unresolved → no discount, `allow_promotion_codes`, and `custom_text.submit.message` tells the buyer. A code Stripe restricts (first-time customers, a minimum amount, one customer: `PromotionData::restricted`) is never pre-applied, since Stripe refuses the whole session when it rules the buyer out: the buyer gets the field and a message naming the code, and Stripe checks it there. +- **Local until pushed.** `provider_promotion_code_id` is null for one drafted in code (the showcase's), like a price. `CatalogPush` creates it after the prices — `createPromotion()`: a coupon limited to its prices' products, then the code with cap and end — or adopts a code the provider already has (`findPromotion()`), count included — only when it makes the same offer (`Promotion::sameTermsAs()`: discount, currency, duration, cap; not the end date). Codes are shared by every app on one Stripe account, so a code with other terms is left local-only and named in `CatalogPushReport::promotionWarnings`, as is a promotion that takes nothing off one of its prices (`untouchedPricesWarning()`, also a warning toast in the admin). The command, the seeder and both admin push actions print them. `run($product)` pushes only promotions on that product's prices. Sync skips local-only ones. A once-only coupon on a plan with a trial is spent on the $0 trial invoice. +- **Counted once.** `CheckoutSessionData` carries `discountAmount` (`total_details.amount_discount`) and `providerPromotionCodeId` (`discounts[0].promotion_code`). `CompleteCheckout` increments the matching promotion inside the session lock, past the Completed check, and writes `payments.discount_amount` and `payments.promotion_code` (known promotions only; a code typed on Stripe's page shows as the amount alone). `CatalogSync` then sets every known promotion back to the provider's figures (`retrievePromotion()`), reporting and skipping one it cannot read. + ### Gateway Driver Pattern `PaymentGatewayManager` extends Laravel's `Manager`. The default driver is `BillingSettings::$gateway`. Adding a new gateway means implementing `PaymentGatewayInterface` and adding a `createXxxDriver()` method. The gateway talks to the provider and returns identifiers; the module owns every local row (`createCustomer()` returns the provider's customer ID, `StartCheckout` creates the `Customer`). @@ -185,13 +194,13 @@ Everything else the module seeds is demo content, run by `modules:seed --state=s | Seeder | What it makes | | --- | --- | -| `ShowcaseProductSeeder` | Five plans for a made-up developer tool, each with a kind and entitlements — Free, Pro (highlighted), Team, Lifetime (replaces Pro) and Enterprise (no price, `cta_url` to sales) — chosen so the pricing page shows every option it reads. No provider IDs. A real install defines its own. | +| `ShowcaseProductSeeder` | Five plans for a made-up developer tool, each with a kind and entitlements — Free, Pro (highlighted), Team, Lifetime (replaces Pro) and Enterprise (no price, `cta_url` to sales) — chosen so the pricing page shows every option it reads — and a `LAUNCH` promotion on Lifetime ($100 off, 50 buyers, 60 days; Lifetime because a once-only coupon on Pro's trial would be spent on the $0 trial invoice). No provider IDs. A real install defines its own. | | `ShowcaseCustomerSeeder` | 48 users, customers and cards, signing up on a rising curve over the last twelve months. | | `ShowcaseSubscriptionSeeder` | A subscription per customer, one payment and invoice per billing period since signup, plus abandoned checkouts. | Keep the `Showcase` prefix on each: it marks the data as the showcase state's rather than an install's. -`ShowcaseBillingDatabaseSeeder` runs `CatalogPush` after the three, and it is the only step that leaves the database. The seeded plans have no provider IDs, and a plan the provider does not know is not `purchasable()` — so without this every paid plan on the demo's pricing page says *Not available*. It is skipped under `runningUnitTests()` (the suite boots with the developer's own `.env`) and when the provider has no keys, and a provider that is unreachable warns rather than failing the seed. Put it here rather than inside `ShowcaseProductSeeder`: the runner draws a task line around each seeder and swallows its output. +`ShowcaseBillingDatabaseSeeder` runs `CatalogPush` (products, prices and the promotion) after the three, and it is the only step that leaves the database. The seeded plans have no provider IDs, and a plan the provider does not know is not `purchasable()` — so without this every paid plan on the demo's pricing page says *Not available*. It is skipped under `runningUnitTests()` (the suite boots with the developer's own `.env`) and when the provider has no keys, and a provider that is unreachable warns rather than failing the seed. Put it here rather than inside `ShowcaseProductSeeder`: the runner draws a task line around each seeder and swallows its output. Two properties hold the demo data together, and a new seeder should keep both. It is **deterministic** — the customer names come from a fixed faker seed, and everything else from the customer's index — and it is **idempotent**, keyed on slugs, users and `*_demo_*` IDs, so reseeding updates rather than duplicates. Customers carry no provider ID: checkout creates a real one the first time a demo account buys. `ShowcaseSeederTest` covers the second. @@ -233,7 +242,7 @@ Billing failures are `src/Exceptions/*`, all extending `BillingException`. Each | `billing.provider_error` | never thrown; the `previous` of the above | Keeps SDK class, provider code, HTTP status, request ID and a **redacted** message (keys, card-like numbers, emails) — the raw SDK exception is not chained, because the reporter writes every previous message | | `billing.invalid_webhook_signature` | `verifyAndParseWebhook()` | Empty 400, warning log, not reported | | `billing.invalid_webhook_data` | `WebhookData::dataAs()` | Reported, empty 500 — a gateway defect | -| `billing.webhook_dependency_not_ready` | a known customer's subscription or payment not here yet | Empty 500, info log, **not** reported — the resend recovers it; context names the `provider_event_id` | +| `billing.webhook_dependency_not_ready` | a known customer's subscription or payment not here yet | Empty **503**, info log (hidden above `LOG_LEVEL=info`), **not** reported — the resend recovers it; context names the `provider_event_id`. A 503 on `invoice.payment_succeeded` during a checkout is this: the invoice beat `checkout.session.completed` | | `billing.subscription_reconciliation_conflict` | `reconcileDelinquency()` overtaken on every read | Reported, empty 500, claim released for the resend | Unsupported events are acknowledged (200). Events for unknown customers are acknowledged, as before. diff --git a/resources/js/lib/intervals.test.ts b/resources/js/lib/intervals.test.ts index b1fa5e6..1faf50a 100644 --- a/resources/js/lib/intervals.test.ts +++ b/resources/js/lib/intervals.test.ts @@ -5,6 +5,7 @@ import { matchesInterval, normalizeInterval, pickInterval, + toggleIntervals, } from './intervals'; describe('intervals', () => { @@ -52,4 +53,23 @@ describe('pickInterval', () => { it('keeps the current one when nothing is offered', () => { expect(pickInterval([], 'month')).toBe('month'); }); + it('offers a toggle only when a plan is priced in more than one interval', () => { + const plan = (...intervals: (string | null)[]) => ({ + prices: intervals.map((interval) => ({ interval })), + }); + + // Monthly or yearly for the same plans, plus a lifetime: the toggle switches them. + expect(toggleIntervals([plan('year', 'monthly'), plan(null)])).toEqual([ + 'one_time', + 'month', + 'year', + ]); + + // One price each (a subscription, or the same thing paid once): all fit on one screen. + expect(toggleIntervals([plan('year'), plan(null)])).toEqual([]); + expect(toggleIntervals([plan('month'), plan('month'), plan()])).toEqual( + [], + ); + expect(toggleIntervals([])).toEqual([]); + }); }); diff --git a/resources/js/lib/intervals.ts b/resources/js/lib/intervals.ts index e43a0a8..5924cf1 100644 --- a/resources/js/lib/intervals.ts +++ b/resources/js/lib/intervals.ts @@ -42,3 +42,32 @@ export function pickInterval(available: string[], current: string): string { ? current : available[0]; } + +// Sort order: one_time, day, week, month, year +const ORDER = ['one_time', 'day', 'week', 'month', 'year']; + +/** + * The intervals the toggle offers. None unless some plan is priced in more than one: + * the toggle switches the same plans between, say, monthly and yearly. With one price + * per plan it would only hide plans from each other, so they all show together. + */ +export function toggleIntervals( + products: { prices: { interval: string | null }[] }[], +): string[] { + const perPlan = products.map( + (product) => + new Set( + product.prices.map((price) => + normalizeInterval(price.interval), + ), + ), + ); + + if (!perPlan.some((intervals) => intervals.size > 1)) { + return []; + } + + return Array.from( + new Set(perPlan.flatMap((intervals) => [...intervals])), + ).sort((a, b) => ORDER.indexOf(a) - ORDER.indexOf(b)); +} diff --git a/resources/js/lib/promotion.test.ts b/resources/js/lib/promotion.test.ts new file mode 100644 index 0000000..61f03ec --- /dev/null +++ b/resources/js/lib/promotion.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest'; +import type { Price, Promotion } from '../types'; +import { promotionNotes } from './promotion'; + +const promotion = (overrides: Partial = {}): Promotion => ({ + code: 'LAUNCH', + percent_off: null, + amount_off: 3000, + currency: 'USD', + duration: 'once', + duration_in_months: null, + max_redemptions: 50, + remaining: 38, + expires_at: null, + ...overrides, +}); + +const price = ( + p: Promotion | null, + interval: string | null = 'year', +): Price => ({ + id: 1, + amount: 17900, + currency: 'USD', + interval, + promotion: p, + promotional_amount: p ? 14900 : null, +}); + +describe('promotionNotes', () => { + it('says nothing without a promotion', () => { + expect(promotionNotes(price(null), 'en')).toEqual([]); + }); + + it('counts what is left of a capped promotion', () => { + expect(promotionNotes(price(promotion()), 'en')).toContainEqual([ + ':left of :max left', + { left: '38', max: '50' }, + ]); + }); + + it('names the end date', () => { + const [, params] = promotionNotes( + price( + promotion({ + max_redemptions: null, + remaining: null, + expires_at: '2026-12-31T12:00:00Z', + }), + ), + 'en', + ).find(([key]) => key === 'Until :date')!; + + expect(params.date).toContain('2026'); + }); + + it('says a subscription discount covers the first payment only', () => { + expect(promotionNotes(price(promotion()), 'en')).toContainEqual([ + 'First payment, then :price', + { price: '$179' }, + ]); + }); + + it('says how many months a repeating discount lasts', () => { + expect( + promotionNotes( + price( + promotion({ duration: 'repeating', duration_in_months: 3 }), + 'month', + ), + 'en', + ), + ).toContainEqual([ + 'For :months months, then :price', + { months: '3', price: '$179' }, + ]); + }); + + it('says nothing about duration for a one-time price or a forever discount', () => { + const keys = (p: Price) => promotionNotes(p, 'en').map(([key]) => key); + + expect(keys(price(promotion(), null))).toEqual([':left of :max left']); + expect(keys(price(promotion({ duration: 'forever' })))).toEqual([ + ':left of :max left', + ]); + }); +}); diff --git a/resources/js/lib/promotion.ts b/resources/js/lib/promotion.ts new file mode 100644 index 0000000..b809637 --- /dev/null +++ b/resources/js/lib/promotion.ts @@ -0,0 +1,59 @@ +import type { Price } from '../types'; +import { formatMoney } from './money'; + +/** A translation key and its replacements; each card translates with its own `t`. */ +export type Note = [string, Record]; + +/** + * The lines under a promoted price: how long the discount lasts on a + * subscription, how many are left, and until when. Empty without a promotion. + */ +export function promotionNotes( + price: Price, + locale: string | undefined, +): Note[] { + const promotion = price.promotion; + + if (!promotion || price.promotional_amount == null) return []; + + const notes: Note[] = []; + const regular = formatMoney(price.amount, price.currency, locale, { + wholeUnits: true, + }); + + // A one-time price is paid once, and a forever discount never ends. + if (price.interval && promotion.duration === 'once') { + notes.push(['First payment, then :price', { price: regular }]); + } else if (price.interval && promotion.duration === 'repeating') { + notes.push([ + 'For :months months, then :price', + { + months: String(promotion.duration_in_months ?? 1), + price: regular, + }, + ]); + } + + if (promotion.remaining != null && promotion.max_redemptions != null) { + notes.push([ + ':left of :max left', + { + left: String(promotion.remaining), + max: String(promotion.max_redemptions), + }, + ]); + } + + if (promotion.expires_at) { + notes.push([ + 'Until :date', + { + date: new Intl.DateTimeFormat(locale, { + dateStyle: 'medium', + }).format(new Date(promotion.expires_at)), + }, + ]); + } + + return notes; +} diff --git a/resources/js/react/app.tsx b/resources/js/react/app.tsx index e0c6a85..18f1170 100644 --- a/resources/js/react/app.tsx +++ b/resources/js/react/app.tsx @@ -2,10 +2,12 @@ import { registerGlobalComponent } from '@saucebase/react/lib/globalComponents'; import { registerIcon } from '@saucebase/react/lib/navigation'; import IconCreditCard from '~icons/lucide/credit-card'; import IconSparkles from '~icons/lucide/sparkles'; +import CheckoutSuccessToast from './components/CheckoutSuccessToast'; import PlanName from './components/PlanName'; export function setup() { registerIcon('billing', IconCreditCard); registerIcon('upgrade', IconSparkles); registerGlobalComponent('dashboard::user-menu.subtitle', PlanName); + registerGlobalComponent('app::page.before', CheckoutSuccessToast); } diff --git a/resources/js/react/components/CheckoutSuccessToast.tsx b/resources/js/react/components/CheckoutSuccessToast.tsx new file mode 100644 index 0000000..6f7f396 --- /dev/null +++ b/resources/js/react/components/CheckoutSuccessToast.tsx @@ -0,0 +1,40 @@ +import { router } from '@inertiajs/react'; +import { useT } from '@saucebase/react/i18n'; +import { useEffect } from 'react'; +import { toast } from 'sonner'; + +/** + * Congratulate whoever just came back from the payment page, on whichever section the + * merchant chose (`after_checkout_section`), so it is not the billing panel's. + * + * The parameter is dropped from the URL straight away, so a refresh or a later + * visit does not celebrate the same purchase again. + */ +export default function CheckoutSuccessToast() { + const t = useT(); + + useEffect(() => { + const url = new URL(window.location.href); + + if (url.searchParams.get('checkout') !== 'success') { + return; + } + + toast.success(t('You are all set!'), { + description: t('Your payment went through. Welcome aboard.'), + }); + + // Through the router, not history.replaceState: Inertia keeps its own + // copy of the URL and re-renders from it, so switching panel would + // toast again. + url.searchParams.delete('checkout'); + url.searchParams.delete('settings'); + router.replace({ + url: url.toString(), + preserveState: true, + preserveScroll: true, + }); + }, [t]); + + return null; +} diff --git a/resources/js/react/components/PlanFeatures.stories.tsx b/resources/js/react/components/PlanFeatures.stories.tsx new file mode 100644 index 0000000..8b06dc2 --- /dev/null +++ b/resources/js/react/components/PlanFeatures.stories.tsx @@ -0,0 +1,53 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import PlanFeatures from './PlanFeatures'; + +const features = [ + 'Unlimited projects', + 'Priority support', + 'Custom domains', + 'Audit log', + 'Single sign-on', +]; + +/** + * A plan's features on the billing settings page. Past `limit`, the rest fold behind a + * "+N more" button. + */ +const meta = preview.meta({ + title: 'Billing/PlanFeatures', + component: PlanFeatures, + args: { features, limit: 3 }, +}); +export default meta; + +/** More than the limit: the rest are folded. Opening them shows all. */ +export const Folded = meta.story({ + play: async ({ canvas, userEvent }) => { + await expect(canvas.queryByText('Audit log')).toBeNull(); + + await userEvent.click(canvas.getByRole('button', { name: '+2 more' })); + + await expect(canvas.getByText('Audit log')).toBeVisible(); + await expect( + canvas.getByRole('button', { name: 'Show less' }), + ).toHaveAttribute('aria-expanded', 'true'); + }, +}); + +/** Within the limit: every feature, no button. */ +export const Short = meta.story({ + args: { features: features.slice(0, 2) }, + play: async ({ canvas }) => { + await expect(canvas.getAllByRole('listitem')).toHaveLength(2); + await expect(canvas.queryByRole('button')).toBeNull(); + }, +}); + +/** No features: nothing renders. */ +export const Empty = meta.story({ + args: { features: [] }, + play: async ({ canvas }) => { + await expect(canvas.queryByRole('list')).toBeNull(); + }, +}); diff --git a/resources/js/react/components/ProductCard.stories.tsx b/resources/js/react/components/ProductCard.stories.tsx new file mode 100644 index 0000000..fd4d056 --- /dev/null +++ b/resources/js/react/components/ProductCard.stories.tsx @@ -0,0 +1,137 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ProductCard from './ProductCard'; + +const pro = { + id: 2, + name: 'Pro', + slug: 'pro', + description: 'For teams that ship every week.', + features: ['Unlimited projects', 'Priority support', 'Custom domains'], + prices: [], +}; + +const monthly = { id: 20, amount: 2900, currency: 'usd', interval: 'month' }; + +/** + * One plan on the pricing page: name, price, and a button for what the visitor may do + * with it. The server decides the button (`action`); the card only shows it. Buying + * starts a checkout, which a story logs in the Actions panel instead. + */ +const meta = preview.meta({ + title: 'Billing/ProductCard', + component: ProductCard, + args: { product: pro, price: monthly, action: 'buy' }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], +}); +export default meta; + +/** A plan the visitor can buy. */ +export const Buy = meta.story({ + play: async ({ canvas }) => { + await expect(canvas.getByTestId('price-amount')).toHaveTextContent( + '$29', + ); + await expect( + canvas.getByRole('button', { name: 'Get started' }), + ).toBeEnabled(); + }, +}); + +/** The plan to pick: highlighted, with a badge. */ +export const Highlighted = meta.story({ + args: { product: { ...pro, is_highlighted: true } }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('product-badge')).toHaveTextContent( + 'Most popular', + ); + }, +}); + +/** On promotion: the regular price struck through, and how long the offer lasts. */ +export const Promotion = meta.story({ + args: { + price: { + ...monthly, + promotional_amount: 1900, + promotion: { + code: 'LAUNCH', + percent_off: 35, + amount_off: null, + currency: null, + duration: 'repeating', + duration_in_months: 3, + max_redemptions: 100, + remaining: 12, + expires_at: null, + }, + }, + }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('price-struck')).toHaveTextContent( + '$29', + ); + await expect(canvas.getByTestId('price-amount')).toHaveTextContent( + '$19', + ); + await expect(canvas.getByTestId('promotion-notes')).toHaveTextContent( + '12 of 100 left', + ); + }, +}); + +/** A free trial before the first payment. */ +export const Trial = meta.story({ + args: { product: { ...pro, trial_days: 14 }, action: 'trial' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('button', { name: 'Start 14-day free trial' }), + ).toBeEnabled(); + }, +}); + +/** The plan the visitor is on: nothing to do. */ +export const Current = meta.story({ + args: { action: 'current' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('button', { name: 'Current plan' }), + ).toBeDisabled(); + }, +}); + +/** A subscriber on another plan: a link to change plans. */ +export const Change = meta.story({ + args: { action: 'change' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('link', { name: 'Change plan' }), + ).toBeVisible(); + }, +}); + +/** No price: the visitor talks to sales. */ +export const Contact = meta.story({ + args: { + product: { + ...pro, + name: 'Enterprise', + slug: 'enterprise', + metadata: { cta_url: '#', cta_label: 'Talk to sales' }, + }, + price: undefined, + action: 'contact', + }, + play: async ({ canvas }) => { + await expect(canvas.getByText('Contact us')).toBeVisible(); + await expect( + canvas.getByRole('link', { name: 'Talk to sales' }), + ).toHaveAttribute('href', '#'); + }, +}); diff --git a/resources/js/react/components/ProductCard.tsx b/resources/js/react/components/ProductCard.tsx index fd4fa7c..8f24d1e 100644 --- a/resources/js/react/components/ProductCard.tsx +++ b/resources/js/react/components/ProductCard.tsx @@ -14,6 +14,7 @@ import type { } from '@modules/billing/resources/js/types'; import { getIntervalDisplay } from '../../lib/intervals'; import { formatMoney } from '../../lib/money'; +import { promotionNotes } from '../../lib/promotion'; export default function ProductCard({ product, @@ -33,6 +34,14 @@ export default function ProductCard({ formatMoney(amount, currency, locale, { wholeUnits: true }); const featured = !!product.metadata?.badge || product.is_highlighted; const [isAnimating, setIsAnimating] = useState(false); + // A promotion strikes the regular price through; otherwise the admin's own + // `original_price` metadata does, as before. + const promoted = price?.promotional_amount != null; + const struckPrice = promoted + ? price?.amount + : price?.metadata?.original_price; + const payable = promoted ? price!.promotional_amount! : price?.amount; + const notes = price ? promotionNotes(price, locale) : []; // The amount, not the price object: switching interval swaps the object on // every render, and only a changed figure is worth drawing attention to. @@ -41,7 +50,7 @@ export default function ProductCard({ const timer = setTimeout(() => setIsAnimating(false), 150); return () => clearTimeout(timer); - }, [price?.amount]); + }, [payable]); const ctaClasses = featured ? 'bg-primary hover:bg-primary/90 focus-visible:outline-primary text-white' @@ -161,18 +170,18 @@ export default function ProductCard({ {/* Price */}
- {/* Original price + discount badge */} - {price?.metadata?.original_price || price?.metadata?.badge ? ( + {/* Struck-through price + discount badge */} + {struckPrice || price?.metadata?.badge ? (
- {price.metadata?.original_price && ( - - {formatPrice( - price.metadata.original_price, - price.currency, - )} + {struckPrice && ( + + {formatPrice(struckPrice, price?.currency)} )} - {price.metadata?.badge && ( + {price?.metadata?.badge && ( {price.metadata.badge} @@ -190,8 +199,11 @@ export default function ProductCard({ > {price ? ( <> - - {formatPrice(price.amount, price.currency)} + + {formatPrice(payable!, price.currency)} {getIntervalDisplay(price.interval)} @@ -205,6 +217,16 @@ export default function ProductCard({
+ {/* Promotion: how long, how many left, until when */} + {notes.length > 0 && ( +

+ {notes.map(([key, params]) => t(key, params)).join(' · ')} +

+ )} + {/* Tagline from metadata */} {product.metadata?.tagline && (

diff --git a/resources/js/react/components/ProductSection.stories.tsx b/resources/js/react/components/ProductSection.stories.tsx new file mode 100644 index 0000000..74f0583 --- /dev/null +++ b/resources/js/react/components/ProductSection.stories.tsx @@ -0,0 +1,95 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ProductSection from './ProductSection'; + +const plan = (id: number, name: string, monthly: number, extra = {}) => ({ + id, + name, + slug: name.toLowerCase(), + description: null, + features: ['Unlimited projects', 'Priority support'], + prices: [ + { id: id * 10, amount: monthly, currency: 'usd', interval: 'month' }, + { + id: id * 10 + 1, + amount: monthly * 10, + currency: 'usd', + interval: 'year', + }, + ], + ...extra, +}); + +const products = [ + plan(1, 'Starter', 900), + plan(2, 'Pro', 2900, { is_highlighted: true }), + plan(3, 'Business', 7900), +]; + +/** + * The pricing page's plans: a card each, and a monthly/yearly switch when a plan is + * priced both ways. Each card's button comes from the server, per price + * (`priceActions`) or per plan without a price (`productActions`). + */ +const meta = preview.meta({ + title: 'Billing/ProductSection', + component: ProductSection, + args: { + products, + priceActions: { + 10: 'buy', + 11: 'buy', + 20: 'buy', + 21: 'buy', + 30: 'buy', + 31: 'buy', + }, + productActions: {}, + }, + // The heading and the footer are the page's: a story leaves them out. + argTypes: { + children: { control: false }, + footer: { control: false }, + }, + parameters: { layout: 'fullscreen' }, +}); +export default meta; + +/** Three plans, monthly. Switching to yearly shows the yearly prices. */ +export const Default = meta.story({ + play: async ({ canvas, userEvent }) => { + await expect( + canvas.getAllByTestId('price-amount')[0], + ).toHaveTextContent('$9'); + + await userEvent.click(canvas.getByRole('button', { name: 'Yearly' })); + + await expect( + canvas.getAllByTestId('price-amount')[0], + ).toHaveTextContent('$90'); + }, +}); + +/** One price per plan: no switch, every plan shows. */ +export const OnePricePerPlan = meta.story({ + args: { + products: products.map((product) => ({ + ...product, + prices: product.prices.slice(0, 1), + })), + }, + play: async ({ canvas }) => { + await expect( + canvas.queryByRole('button', { name: 'Yearly' }), + ).toBeNull(); + await expect(canvas.getAllByTestId('price-amount')).toHaveLength(3); + }, +}); + +/** No plan to show. */ +export const Empty = meta.story({ + args: { products: [] }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('pricing-empty')).toBeVisible(); + }, +}); diff --git a/resources/js/react/components/ProductSection.tsx b/resources/js/react/components/ProductSection.tsx index f0a4a9e..f7bd85a 100644 --- a/resources/js/react/components/ProductSection.tsx +++ b/resources/js/react/components/ProductSection.tsx @@ -9,15 +9,12 @@ import type { import { getIntervalLabel, matchesInterval, - normalizeInterval, pickInterval, + toggleIntervals, } from '../../lib/intervals'; import ProductCard from './ProductCard'; -// Sort order: one_time, day, week, month, year -const ORDER = ['one_time', 'day', 'week', 'month', 'year']; - function getToggleLabel(interval: string): string { if (interval === 'one_time') return 'One-time'; return getIntervalLabel(interval); @@ -47,19 +44,10 @@ export default function ProductSection({ : (productActions[product.id] ?? 'unavailable'); } - const availableIntervals = useMemo(() => { - const intervals = new Set(); - - for (const product of products ?? []) { - for (const price of product.prices) { - intervals.add(normalizeInterval(price.interval)); - } - } - - return Array.from(intervals).sort( - (a, b) => ORDER.indexOf(a) - ORDER.indexOf(b), - ); - }, [products]); + const availableIntervals = useMemo( + () => toggleIntervals(products ?? []), + [products], + ); const [chosenInterval, setChosenInterval] = useState('month'); // Derived while rendering, so the server's first paint selects an offered interval; @@ -71,8 +59,11 @@ export default function ProductSection({ (products ?? []) .map((product) => ({ ...product, - prices: product.prices.filter((price) => - matchesInterval(price.interval, billingInterval), + // No toggle: one price per plan, shown as it is. + prices: product.prices.filter( + (price) => + availableIntervals.length === 0 || + matchesInterval(price.interval, billingInterval), ), })) .filter( @@ -81,7 +72,7 @@ export default function ProductSection({ (productActions[product.id] ?? 'unavailable') !== 'unavailable', ), - [products, productActions, billingInterval], + [products, productActions, billingInterval, availableIntervals], ); const columns = diff --git a/resources/js/react/layouts/CheckoutLayout.stories.tsx b/resources/js/react/layouts/CheckoutLayout.stories.tsx new file mode 100644 index 0000000..fcedc6f --- /dev/null +++ b/resources/js/react/layouts/CheckoutLayout.stories.tsx @@ -0,0 +1,58 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import CheckoutLayout from './CheckoutLayout'; + +/** + * The checkout page's frame: what is being bought on the left (`summary`), what the + * buyer fills in on the right (the default slot), and a way back. + */ +const meta = preview.meta({ + title: 'Billing/CheckoutLayout', + component: CheckoutLayout, + args: { title: 'Checkout', backHref: '/pricing' }, + // Slots the story fills itself: their controls would do nothing. + argTypes: { + summary: { control: false }, + children: { control: false }, + }, + parameters: { layout: 'fullscreen' }, + render: (args) => ( + +

+ Subscribe to Pro +

+

+ $29{' '} + + /month + +

+ + } + > +
+ Payment details +
+ + ), +}); +export default meta; + +/** With a way back to the pricing page. */ +export const Default = meta.story({ + play: async ({ canvas }) => { + await expect(canvas.getByTestId('checkout-back')).toBeVisible(); + await expect(canvas.getByText('Payment details')).toBeVisible(); + }, +}); + +/** Without a page to go back to. */ +export const NoBack = meta.story({ + args: { backHref: undefined }, + play: async ({ canvas }) => { + await expect(canvas.queryByTestId('checkout-back')).toBeNull(); + }, +}); diff --git a/resources/js/react/pages/SettingsBilling.tsx b/resources/js/react/pages/SettingsBilling.tsx index 626b1df..9701188 100644 --- a/resources/js/react/pages/SettingsBilling.tsx +++ b/resources/js/react/pages/SettingsBilling.tsx @@ -7,8 +7,7 @@ import { formatDate } from '@saucebase/core/lib/dates'; import { useDialog } from '@saucebase/react/hooks/useDialog'; import { useT, useTranslation } from '@saucebase/react/i18n'; import { CreditCard, Loader2 } from 'lucide-react'; -import { useEffect, useMemo, useState } from 'react'; -import { toast } from 'sonner'; +import { useMemo, useState } from 'react'; import { getIntervalLabel } from '../../lib/intervals'; import { formatMoney } from '../../lib/money'; import type { @@ -126,35 +125,6 @@ export default function SettingsBilling({ [payments, lifetimePlans], ); - /** - * Congratulate whoever just came back from the payment page. - * - * The parameter is dropped from the URL straight away, so a refresh or a - * later visit to this panel does not celebrate the same purchase again. - */ - useEffect(() => { - const url = new URL(window.location.href); - - if (url.searchParams.get('checkout') !== 'success') { - return; - } - - toast.success(t('You are all set!'), { - description: t('Your subscription is active. Welcome aboard.'), - }); - - // Through the router, not history.replaceState: Inertia keeps its own - // copy of the URL and re-renders from it, so switching panel would - // toast again. - url.searchParams.delete('checkout'); - url.searchParams.delete('settings'); - router.replace({ - url: url.toString(), - preserveState: true, - preserveScroll: true, - }); - }, [t]); - async function handleCancelSubscription() { const confirmed = await confirm({ title: t('Cancel subscription'), @@ -643,6 +613,32 @@ export default function SettingsBilling({ {payment.name ?? '—'} + {payment.discount_amount > 0 && ( + + {payment.promotion_code + ? t( + 'Saved :amount with :code', + { + amount: formatMoney( + payment.discount_amount, + payment.currency, + locale, + ), + code: payment.promotion_code, + }, + ) + : t('Saved :amount', { + amount: formatMoney( + payment.discount_amount, + payment.currency, + locale, + ), + })} + + )} {formatMoney( diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts index 8058c84..c0cd95c 100644 --- a/resources/js/types/index.ts +++ b/resources/js/types/index.ts @@ -12,6 +12,23 @@ export interface ProductMetadata { [key: string]: any; } +/** + * A promotion that still holds, as the pricing page receives it (`Promotion` + * model). The provider enforces it; this is only what the card shows. + */ +export interface Promotion { + code: string; + percent_off: number | null; + amount_off: number | null; + currency: string | null; + duration: 'once' | 'repeating' | 'forever'; + duration_in_months: number | null; + max_redemptions: number | null; + /** Null when there is no cap. */ + remaining: number | null; + expires_at: string | null; +} + export interface Price { id: number; amount: number; @@ -21,6 +38,10 @@ export interface Price { provider_price_id?: string; is_active?: boolean; metadata?: PriceMetadata; + /** Loaded on the pricing page only, and only while it holds. */ + promotion?: Promotion | null; + /** What the buyer pays with the promotion; null when none applies. */ + promotional_amount?: number | null; } /** @@ -123,6 +144,8 @@ export interface OneTimePayment { currency: string; status: 'succeeded' | 'refunded'; paid_at: string | null; + discount_amount: number; + promotion_code: string | null; } export interface Invoice { diff --git a/resources/js/vue/app.ts b/resources/js/vue/app.ts index 86d35e9..b70b950 100644 --- a/resources/js/vue/app.ts +++ b/resources/js/vue/app.ts @@ -2,10 +2,12 @@ import { registerGlobalComponent } from '@saucebase/vue/lib/globalComponents'; import { registerIcon } from '@saucebase/vue/lib/navigation'; import IconCreditCard from '~icons/lucide/credit-card'; import IconSparkles from '~icons/lucide/sparkles'; +import CheckoutSuccessToast from './components/CheckoutSuccessToast.vue'; import PlanName from './components/PlanName.vue'; export function setup() { registerIcon('billing', IconCreditCard); registerIcon('upgrade', IconSparkles); registerGlobalComponent('dashboard::user-menu.subtitle', PlanName); + registerGlobalComponent('app::page.before', CheckoutSuccessToast); } diff --git a/resources/js/vue/components/CheckoutSuccessToast.vue b/resources/js/vue/components/CheckoutSuccessToast.vue new file mode 100644 index 0000000..cbfc97f --- /dev/null +++ b/resources/js/vue/components/CheckoutSuccessToast.vue @@ -0,0 +1,37 @@ + + + diff --git a/resources/js/vue/components/PlanFeatures.stories.ts b/resources/js/vue/components/PlanFeatures.stories.ts new file mode 100644 index 0000000..a35be0b --- /dev/null +++ b/resources/js/vue/components/PlanFeatures.stories.ts @@ -0,0 +1,53 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import PlanFeatures from './PlanFeatures.vue'; + +const features = [ + 'Unlimited projects', + 'Priority support', + 'Custom domains', + 'Audit log', + 'Single sign-on', +]; + +/** + * A plan's features on the billing settings page. Past `limit`, the rest fold behind a + * "+N more" button. + */ +const meta = preview.meta({ + title: 'Billing/PlanFeatures', + component: PlanFeatures, + args: { features, limit: 3 }, +}); +export default meta; + +/** More than the limit: the rest are folded. Opening them shows all. */ +export const Folded = meta.story({ + play: async ({ canvas, userEvent }) => { + await expect(canvas.queryByText('Audit log')).toBeNull(); + + await userEvent.click(canvas.getByRole('button', { name: '+2 more' })); + + await expect(canvas.getByText('Audit log')).toBeVisible(); + await expect( + canvas.getByRole('button', { name: 'Show less' }), + ).toHaveAttribute('aria-expanded', 'true'); + }, +}); + +/** Within the limit: every feature, no button. */ +export const Short = meta.story({ + args: { features: features.slice(0, 2) }, + play: async ({ canvas }) => { + await expect(canvas.getAllByRole('listitem')).toHaveLength(2); + await expect(canvas.queryByRole('button')).toBeNull(); + }, +}); + +/** No features: nothing renders. */ +export const Empty = meta.story({ + args: { features: [] }, + play: async ({ canvas }) => { + await expect(canvas.queryByRole('list')).toBeNull(); + }, +}); diff --git a/resources/js/vue/components/ProductCard.stories.ts b/resources/js/vue/components/ProductCard.stories.ts new file mode 100644 index 0000000..b11b9fa --- /dev/null +++ b/resources/js/vue/components/ProductCard.stories.ts @@ -0,0 +1,133 @@ +import preview from '@/.storybook/preview'; +import { expect } from 'storybook/test'; +import ProductCard from './ProductCard.vue'; + +const pro = { + id: 2, + name: 'Pro', + slug: 'pro', + description: 'For teams that ship every week.', + features: ['Unlimited projects', 'Priority support', 'Custom domains'], + prices: [], +}; + +const monthly = { id: 20, amount: 2900, currency: 'usd', interval: 'month' }; + +/** + * One plan on the pricing page: name, price, and a button for what the visitor may do + * with it. The server decides the button (`action`); the card only shows it. Buying + * starts a checkout, which a story logs in the Actions panel instead. + */ +const meta = preview.meta({ + title: 'Billing/ProductCard', + component: ProductCard, + args: { product: pro, price: monthly, action: 'buy' }, + decorators: [ + () => ({ template: '
' }), + ], +}); +export default meta; + +/** A plan the visitor can buy. */ +export const Buy = meta.story({ + play: async ({ canvas }) => { + await expect(canvas.getByTestId('price-amount')).toHaveTextContent( + '$29', + ); + await expect( + canvas.getByRole('button', { name: 'Get started' }), + ).toBeEnabled(); + }, +}); + +/** The plan to pick: highlighted, with a badge. */ +export const Highlighted = meta.story({ + args: { product: { ...pro, is_highlighted: true } }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('product-badge')).toHaveTextContent( + 'Most popular', + ); + }, +}); + +/** On promotion: the regular price struck through, and how long the offer lasts. */ +export const Promotion = meta.story({ + args: { + price: { + ...monthly, + promotional_amount: 1900, + promotion: { + code: 'LAUNCH', + percent_off: 35, + amount_off: null, + currency: null, + duration: 'repeating', + duration_in_months: 3, + max_redemptions: 100, + remaining: 12, + expires_at: null, + }, + }, + }, + play: async ({ canvas }) => { + await expect(canvas.getByTestId('price-struck')).toHaveTextContent( + '$29', + ); + await expect(canvas.getByTestId('price-amount')).toHaveTextContent( + '$19', + ); + await expect(canvas.getByTestId('promotion-notes')).toHaveTextContent( + '12 of 100 left', + ); + }, +}); + +/** A free trial before the first payment. */ +export const Trial = meta.story({ + args: { product: { ...pro, trial_days: 14 }, action: 'trial' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('button', { name: 'Start 14-day free trial' }), + ).toBeEnabled(); + }, +}); + +/** The plan the visitor is on: nothing to do. */ +export const Current = meta.story({ + args: { action: 'current' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('button', { name: 'Current plan' }), + ).toBeDisabled(); + }, +}); + +/** A subscriber on another plan: a link to change plans. */ +export const Change = meta.story({ + args: { action: 'change' }, + play: async ({ canvas }) => { + await expect( + canvas.getByRole('link', { name: 'Change plan' }), + ).toBeVisible(); + }, +}); + +/** No price: the visitor talks to sales. */ +export const Contact = meta.story({ + args: { + product: { + ...pro, + name: 'Enterprise', + slug: 'enterprise', + metadata: { cta_url: '#', cta_label: 'Talk to sales' }, + }, + price: undefined, + action: 'contact', + }, + play: async ({ canvas }) => { + await expect(canvas.getByText('Contact us')).toBeVisible(); + await expect( + canvas.getByRole('link', { name: 'Talk to sales' }), + ).toHaveAttribute('href', '#'); + }, +}); diff --git a/resources/js/vue/components/ProductCard.vue b/resources/js/vue/components/ProductCard.vue index e96cae8..f5d9b94 100644 --- a/resources/js/vue/components/ProductCard.vue +++ b/resources/js/vue/components/ProductCard.vue @@ -16,6 +16,7 @@ import { useAuth } from '@saucebase/vue/composables/useAuth'; import { useLocalization } from '@saucebase/vue/composables/useLocalization'; import { getIntervalDisplay } from '../../lib/intervals'; import { formatMoney } from '../../lib/money'; +import { promotionNotes } from '../../lib/promotion'; const props = defineProps<{ product: Product; @@ -102,7 +103,22 @@ function formatPrice(amount: number | string, currency?: string): string { return formatMoney(amount, currency, language.value, { wholeUnits: true }); } -const priceKey = computed(() => props.price?.amount); +// A promotion strikes the regular price through; otherwise the admin's own +// `original_price` metadata does, as before. +const promoted = computed(() => props.price?.promotional_amount != null); +const struckPrice = computed(() => + promoted.value + ? props.price?.amount + : props.price?.metadata?.original_price, +); +const payable = computed(() => + promoted.value ? props.price!.promotional_amount! : props.price?.amount, +); +const notes = computed(() => + props.price ? promotionNotes(props.price, language.value) : [], +); + +const priceKey = computed(() => payable.value); const isAnimating = ref(false); watch(priceKey, () => { @@ -154,21 +170,17 @@ watch(priceKey, () => {
- +
- {{ - formatPrice( - price.metadata.original_price, - price.currency, - ) - }} + {{ formatPrice(struckPrice, price?.currency) }} { >