From b82b4c24bf5ba5d32074c07f7382fbfc356338e1 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 23 Nov 2026 12:32:16 +0000 Subject: [PATCH 1/9] fix: show the interval toggle only when a plan has more than one interval With one price per plan (a yearly subscription next to a one-off), the toggle only hid plans from each other. They now show side by side. Co-Authored-By: Claude Fable 5.2 --- resources/js/lib/intervals.test.ts | 20 ++++++++++++ resources/js/lib/intervals.ts | 29 +++++++++++++++++ .../js/react/components/ProductSection.tsx | 31 +++++++------------ .../js/vue/components/ProductSection.vue | 28 ++++++----------- 4 files changed, 69 insertions(+), 39 deletions(-) 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/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/vue/components/ProductSection.vue b/resources/js/vue/components/ProductSection.vue index cb76f69..3e91bb3 100644 --- a/resources/js/vue/components/ProductSection.vue +++ b/resources/js/vue/components/ProductSection.vue @@ -9,7 +9,7 @@ import type { import { getIntervalLabel, matchesInterval, - normalizeInterval, + toggleIntervals, } from '../../lib/intervals'; import ProductCard from './ProductCard.vue'; @@ -25,22 +25,9 @@ function planAction(product: Product): PlanAction { : (props.productActions[product.id] ?? 'unavailable'); } -const availableIntervals = computed(() => { - if (!props.products) return []; - - const intervals = new Set(); - for (const product of props.products) { - for (const price of product.prices) { - intervals.add(normalizeInterval(price.interval)); - } - } - - // Sort order: one_time, day, week, month, year - const order = ['one_time', 'day', 'week', 'month', 'year']; - return Array.from(intervals).sort( - (a, b) => order.indexOf(a) - order.indexOf(b), - ); -}); +const availableIntervals = computed(() => + toggleIntervals(props.products ?? []), +); const billingInterval = ref('month'); @@ -64,8 +51,11 @@ const filteredProducts = computed(() => { return props.products .map((product) => ({ ...product, - prices: product.prices.filter((price) => - matchesInterval(price.interval, billingInterval.value), + // No toggle: one price per plan, shown as it is. + prices: product.prices.filter( + (price) => + availableIntervals.value.length === 0 || + matchesInterval(price.interval, billingInterval.value), ), })) .filter( From 1fc849778b79e4cf7b4b20579ee49638c677b2f7 Mon Sep 17 00:00:00 2001 From: roble Date: Mon, 23 Nov 2026 14:25:28 +0000 Subject: [PATCH 2/9] feat: promotions shown on the pricing page, applied at checkout (sc-1240) A Stripe promotion code, attached in the admin to the prices that show it (one per price). The card strikes the regular price through, shows the promotional one, how long it lasts, how many are left and until when. Checkout sends the code; the completed checkout counts the redemption once, and billing:sync-catalog sets the count back to Stripe's. It ends on its own at the cap or the date. If Stripe ran out first, checkout opens at the regular price and says so. Payments record the discount and code. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 ++ database/factories/PromotionFactory.php | 33 +++ ...0_00_02_000001_create_promotions_table.php | 63 ++++++ .../saucebase-billing-development/SKILL.md | 12 +- resources/js/lib/promotion.test.ts | 87 ++++++++ resources/js/lib/promotion.ts | 59 ++++++ resources/js/react/components/ProductCard.tsx | 46 ++-- resources/js/react/pages/SettingsBilling.tsx | 26 +++ resources/js/types/index.ts | 23 ++ resources/js/vue/components/ProductCard.vue | 44 +++- resources/js/vue/pages/SettingsBilling.vue | 24 +++ src/Actions/CompleteCheckout.php | 12 ++ src/Actions/StartCheckout.php | 11 + src/Contracts/PaymentGatewayInterface.php | 7 + src/Data/PromotionData.php | 29 +++ src/Data/Webhook/CheckoutSessionData.php | 4 + .../Customers/Schemas/CustomerInfolist.php | 31 +++ .../Promotions/Pages/ManagePromotions.php | 53 +++++ .../Promotions/PromotionResource.php | 127 +++++++++++ src/Models/Payment.php | 5 + src/Models/Price.php | 32 +++ src/Models/Product.php | 7 +- src/Models/Promotion.php | 140 +++++++++++++ src/Services/CatalogSync.php | 20 ++ src/Services/Gateways/StripeEventMapper.php | 41 ++++ src/Services/Gateways/StripeGateway.php | 48 ++++- src/Settings/BillingSection.php | 2 + tests/Feature/BillingPanelTest.php | 17 ++ tests/Feature/CatalogSyncTest.php | 44 ++++ tests/Feature/NeutralGatewayTest.php | 11 + tests/Feature/PromotionAdminTest.php | 130 ++++++++++++ tests/Feature/PromotionCheckoutTest.php | 139 ++++++++++++ tests/Feature/PromotionPricingTest.php | 116 ++++++++++ tests/Feature/PromotionRedemptionTest.php | 112 ++++++++++ tests/Feature/StripePromotionRequestTest.php | 198 ++++++++++++++++++ tests/Support/BillingTestHelper.php | 24 +++ tests/e2e/tests/plans/plans.spec.ts | 16 ++ 37 files changed, 1771 insertions(+), 36 deletions(-) create mode 100644 database/factories/PromotionFactory.php create mode 100644 database/migrations/1000_00_02_000001_create_promotions_table.php create mode 100644 resources/js/lib/promotion.test.ts create mode 100644 resources/js/lib/promotion.ts create mode 100644 src/Data/PromotionData.php create mode 100644 src/Filament/Resources/Promotions/Pages/ManagePromotions.php create mode 100644 src/Filament/Resources/Promotions/PromotionResource.php create mode 100644 src/Models/Promotion.php create mode 100644 tests/Feature/PromotionAdminTest.php create mode 100644 tests/Feature/PromotionCheckoutTest.php create mode 100644 tests/Feature/PromotionPricingTest.php create mode 100644 tests/Feature/PromotionRedemptionTest.php create mode 100644 tests/Feature/StripePromotionRequestTest.php diff --git a/README.md b/README.md index 28baccb..f163112 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 @@ -97,6 +98,19 @@ Locally, forward them with `stripe listen --all-snapshot --forward-to localhost/ 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 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. + ## 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. 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..8bf9ed8 --- /dev/null +++ b/database/migrations/1000_00_02_000001_create_promotions_table.php @@ -0,0 +1,63 @@ +id(); + + $table->string('provider'); + $table->string('provider_promotion_code_id'); + $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/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index a4c4e81..ad37159 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` | @@ -156,6 +156,14 @@ 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()` (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. +- **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`). 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/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/pages/SettingsBilling.tsx b/resources/js/react/pages/SettingsBilling.tsx index 626b1df..6c91f48 100644 --- a/resources/js/react/pages/SettingsBilling.tsx +++ b/resources/js/react/pages/SettingsBilling.tsx @@ -643,6 +643,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/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) }} { >