diff --git a/README.md b/README.md index 2fc326c..28baccb 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ Run `npm run build` afterwards. ## Demo data ```bash -php artisan modules:seed --module=billing --demo +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`. diff --git a/Taskfile.yml b/Taskfile.yml index c0d9532..f34f43e 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -21,9 +21,9 @@ tasks: # ── Database ────────────────────────────────────────────────── - db:seed:demo: + db:seed:showcase: desc: Seed the Billing module with sample customers, subscriptions and payments - cmd: '{{.APP}} php artisan modules:seed --module=billing --demo' + cmd: '{{.APP}} php artisan modules:seed --module=billing --state=showcase' # ── Code Generation ──────────────────────────────────────────── diff --git a/composer.json b/composer.json index 57261dd..b830dcd 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": { - "saucebase/core": "^2.12.0", + "saucebase/core": "^3.0", "stripe/stripe-php": "^22.0" }, "license": "MIT", @@ -27,6 +27,9 @@ "vue", "react" ] + }, + "branch-alias": { + "dev-dev": "3.5.x-dev" } }, "autoload": { diff --git a/database/seeders/DemoBillingDatabaseSeeder.php b/database/seeders/ShowcaseBillingDatabaseSeeder.php similarity index 90% rename from database/seeders/DemoBillingDatabaseSeeder.php rename to database/seeders/ShowcaseBillingDatabaseSeeder.php index 742f1ef..f96a56f 100644 --- a/database/seeders/DemoBillingDatabaseSeeder.php +++ b/database/seeders/ShowcaseBillingDatabaseSeeder.php @@ -10,13 +10,13 @@ use Spatie\Permission\Models\Role; /** - * Sample billing content for the demo site, run by `modules:seed --demo`. + * Sample billing content for the demo site, run by `modules:seed --state=showcase`. * * None of it is install data: a real app defines its own plans. The plans are * created locally and pushed to the provider when its keys are present, which * is what makes the demo site's checkout work. */ -class DemoBillingDatabaseSeeder extends Seeder +class ShowcaseBillingDatabaseSeeder extends Seeder { public function run(): void { @@ -29,9 +29,9 @@ public function run(): void $staff->syncRoles('billing admin'); $this->call([ - DemoProductSeeder::class, - DemoCustomerSeeder::class, - DemoSubscriptionSeeder::class, + ShowcaseProductSeeder::class, + ShowcaseCustomerSeeder::class, + ShowcaseSubscriptionSeeder::class, ]); $this->pushToProvider(); @@ -70,7 +70,7 @@ private function pushToProvider(): void $prices = 0; try { - foreach (Product::whereIn('slug', DemoProductSeeder::SLUGS)->get() as $product) { + foreach (Product::whereIn('slug', ShowcaseProductSeeder::SLUGS)->get() as $product) { $report = $push->run($product); $products += $report->products; $prices += $report->prices; diff --git a/database/seeders/DemoCustomerSeeder.php b/database/seeders/ShowcaseCustomerSeeder.php similarity index 97% rename from database/seeders/DemoCustomerSeeder.php rename to database/seeders/ShowcaseCustomerSeeder.php index 5ebeb1d..ce9b690 100644 --- a/database/seeders/DemoCustomerSeeder.php +++ b/database/seeders/ShowcaseCustomerSeeder.php @@ -17,9 +17,9 @@ * * Signup dates run back over the last year on a rising curve, which is what gives * the revenue and subscription charts a shape worth looking at. They are laid out - * here, in one place, because DemoSubscriptionSeeder bills from them. + * here, in one place, because ShowcaseSubscriptionSeeder bills from them. */ -class DemoCustomerSeeder extends Seeder +class ShowcaseCustomerSeeder extends Seeder { /** * How many customers signed up each month, oldest month first. Twelve entries, diff --git a/database/seeders/DemoProductSeeder.php b/database/seeders/ShowcaseProductSeeder.php similarity index 95% rename from database/seeders/DemoProductSeeder.php rename to database/seeders/ShowcaseProductSeeder.php index 3440cdf..25a8a22 100644 --- a/database/seeders/DemoProductSeeder.php +++ b/database/seeders/ShowcaseProductSeeder.php @@ -16,12 +16,12 @@ * * They carry no provider IDs: claiming an ID we do not own would make the push * skip them and checkout fail against a price Stripe has never heard of. - * `DemoBillingDatabaseSeeder` pushes them once every seeder has run. + * `ShowcaseBillingDatabaseSeeder` pushes them once every seeder has run. * * A real app defines its own products, which is why these are demo content * rather than install data. */ -class DemoProductSeeder extends Seeder +class ShowcaseProductSeeder extends Seeder { /** The plans this seeder owns, and the only ones the demo may push. */ public const SLUGS = ['free', 'pro', 'team', 'lifetime', 'enterprise']; @@ -35,6 +35,11 @@ class DemoProductSeeder extends Seeder public function run(): void { foreach ($this->plans() as $order => $plan) { + // An app has one free plan. One it already has (a template's own) stays. + if ($plan['kind'] === PlanKind::Free && Product::where('kind', PlanKind::Free)->where('slug', '!=', $plan['slug'])->exists()) { + continue; + } + $product = Product::updateOrCreate( ['slug' => $plan['slug']], [ diff --git a/database/seeders/DemoSubscriptionSeeder.php b/database/seeders/ShowcaseSubscriptionSeeder.php similarity index 97% rename from database/seeders/DemoSubscriptionSeeder.php rename to database/seeders/ShowcaseSubscriptionSeeder.php index 4c2e83a..80c8e85 100644 --- a/database/seeders/DemoSubscriptionSeeder.php +++ b/database/seeders/ShowcaseSubscriptionSeeder.php @@ -25,10 +25,10 @@ * enough abandoned checkouts to keep the conversion rate short of a suspicious * 100%. * - * Runs after DemoCustomerSeeder and DemoProductSeeder, and does nothing without + * Runs after ShowcaseCustomerSeeder and ShowcaseProductSeeder, and does nothing without * them. */ -class DemoSubscriptionSeeder extends Seeder +class ShowcaseSubscriptionSeeder extends Seeder { /** Every seventeenth of those behind on payment ran out of time entirely. */ private const SUSPENDED_EVERY = 17; @@ -68,7 +68,7 @@ public function run(): void /** * The paid plans, cheapest first. Looked up by plan and interval rather than by - * Stripe price ID, so the demo account's IDs live only in DemoProductSeeder. + * Stripe price ID, so the demo account's IDs live only in ShowcaseProductSeeder. * * @return list */ diff --git a/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index bdb9c66..a4945ae 100644 --- a/resources/boost/skills/saucebase-billing-development/SKILL.md +++ b/resources/boost/skills/saucebase-billing-development/SKILL.md @@ -148,7 +148,7 @@ A new account takes the buyer's name and email; after that its details change on `PurchaseEligibility::assertCanBuy()` throws the refusal's message; `CheckoutController::create()` calls it before a session exists and `StartCheckout` again for the guest who signed in part-way (the session-reuse return runs first, so a checkout already paid at the provider still completes). It runs before payment, so two checkouts opened at once can both be paid; Stripe's *Limit customers to one subscription* closes that, listed in the README as optional. -**Pricing buttons come from the server.** `PlanActions::for()` sends `priceActions` (per displayed price) and `productActions` (per plan shown without a price). `buy` appears only where eligibility allows; the rest label a refusal — `change`, `later`, `included`, `current`, `unavailable` — plus `contact` for a `cta_url` and, for the Free plan, `signup` (guest), `current` (nothing paid) or `included` (paid plan). The cards only render what they are sent. +**Pricing buttons come from the server.** `PlanActions::for()` sends `priceActions` (per displayed price) and `productActions` (per plan shown without a price). `buy` appears only where eligibility allows (`buy_again` for a one-off the owner already paid for, refunds aside: another call, renewed package updates); the rest label a refusal — `change`, `later`, `included`, `current`, `unavailable` — plus `contact` for a `cta_url` and, for the Free plan, `signup` (guest), `current` (nothing paid) or `included` (paid plan). The cards only render what they are sent. **Lifetime replacing a subscription.** After a Lifetime checkout commits, `endSubscriptionReplacedByLifetime()` cancels the current subscription at period end — only if its plan is the one the Lifetime replaces. It runs on every delivery, since a failed provider call is retried and the retry finds the session already completed. Until the provider accepts the cancellation the subscription shows as renewing; once `cancelled_at` is set the panel says it ends, replaced by lifetime. The app freezes it: `billing.plan.change` 404s and resume is refused (`PurchaseEligibility::isReplacedByLifetime()`). That is app policy — the provider stays the source of truth, and a customer who resumes it in the provider's portal keeps an ordinary subscription. @@ -181,21 +181,21 @@ Everything else the merchant decides — provider, currency, checkout redirect, The install seeder, `DatabaseSeeder`, only creates the `manage billing` permission (granted to nobody), which every billing admin page and resource checks in `canAccess()` (Customers, Products, Subscriptions, the Billing dashboard and Billing settings) and every billing widget in `canView()`, since the stats widget also sits on the main dashboard. `access admin panel` alone only opens the panel; `admin` passes every check. Plans are not seeded: a real install defines its own in the admin panel. -Everything else the module seeds is demo content, run by `modules:seed --demo` through `DemoBillingDatabaseSeeder`, which calls one `Demo*Seeder` per kind of content, in dependency order: +Everything else the module seeds is demo content, run by `modules:seed --state=showcase` through `ShowcaseBillingDatabaseSeeder`, which calls one `Showcase*Seeder` per kind of content, in dependency order: | Seeder | What it makes | | --- | --- | -| `DemoProductSeeder` | 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. | -| `DemoCustomerSeeder` | 48 users, customers and cards, signing up on a rising curve over the last twelve months. | -| `DemoSubscriptionSeeder` | A subscription per customer, one payment and invoice per billing period since signup, plus abandoned checkouts. | +| `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. | +| `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 `Demo` prefix on each: it is what marks the data as the demo site's rather than an install's. +Keep the `Showcase` prefix on each: it marks the data as the showcase state's rather than an install's. -`DemoBillingDatabaseSeeder` 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 `DemoProductSeeder`: the runner draws a task line around each seeder and swallows its output. +`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. -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. `DemoSeederTest` covers the second. +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. -Signup dates drive the whole dashboard: `DemoCustomerSeeder::SIGNUPS_PER_MONTH` is the growth curve the revenue and subscription charts draw, and `DemoSubscriptionSeeder` bills forward from each signup date to today. +Signup dates drive the whole dashboard: `ShowcaseCustomerSeeder::SIGNUPS_PER_MONTH` is the growth curve the revenue and subscription charts draw, and `ShowcaseSubscriptionSeeder` bills forward from each signup date to today. Nothing in the test suites depends on the demo plans. `BillingTestHelper::createSubscriberFixtures()` creates the "Pro" product and its price itself, which is what the e2e specs assert against. diff --git a/resources/js/react/components/ProductCard.tsx b/resources/js/react/components/ProductCard.tsx index ba94026..fd4fa7c 100644 --- a/resources/js/react/components/ProductCard.tsx +++ b/resources/js/react/components/ProductCard.tsx @@ -47,7 +47,8 @@ export default function ProductCard({ ? 'bg-primary hover:bg-primary/90 focus-visible:outline-primary text-white' : 'text-foreground ring-border hover:bg-foreground/10 ring-1 ring-inset'; - const startsCheckout = action === 'buy' || action === 'trial'; + const startsCheckout = + action === 'buy' || action === 'buy_again' || action === 'trial'; const enabled = startsCheckout || action === 'signup' || action === 'owner_only'; @@ -72,10 +73,12 @@ export default function ProductCard({ } if (startsCheckout && price) { - const auth = page.props.auth as { - user?: unknown; - modal_enabled?: boolean; - } | undefined; + const auth = page.props.auth as + | { + user?: unknown; + modal_enabled?: boolean; + } + | undefined; if (!auth?.user && auth?.modal_enabled) { setIsStartingCheckout(true); @@ -110,6 +113,7 @@ export default function ProductCard({ later: t('Available when your current plan ends'), unavailable: t('Not available'), owner_only: t('Ask an owner'), + buy_again: t('Buy again'), trial: t('Start :days-day free trial', { days: String(product.trial_days ?? 0), }), diff --git a/resources/js/react/pages/Plans.tsx b/resources/js/react/pages/Plans.tsx index 0841eb8..e28222b 100644 --- a/resources/js/react/pages/Plans.tsx +++ b/resources/js/react/pages/Plans.tsx @@ -20,11 +20,11 @@ export default function Plans({ >

- {t('Pricing that ships with your app')} + {t('Choose your plan')}

{t( - "Every plan here runs on the Billing module against Stripe's sandbox. Try the checkout: you won't be charged.", + 'Start free and upgrade when you need more. Cancel anytime.', )}

diff --git a/resources/js/react/pages/SettingsBilling.tsx b/resources/js/react/pages/SettingsBilling.tsx index 594c281..626b1df 100644 --- a/resources/js/react/pages/SettingsBilling.tsx +++ b/resources/js/react/pages/SettingsBilling.tsx @@ -1,7 +1,7 @@ -import { DangerZone, EmptyState } from '@/components/ui/saucebase'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Card } from '@/components/ui/card'; +import { DangerZone, EmptyState } from '@/components/ui/saucebase'; import { router } from '@inertiajs/react'; import { formatDate } from '@saucebase/core/lib/dates'; import { useDialog } from '@saucebase/react/hooks/useDialog'; @@ -9,7 +9,6 @@ import { useT, useTranslation } from '@saucebase/react/i18n'; import { CreditCard, Loader2 } from 'lucide-react'; import { useEffect, useMemo, useState } from 'react'; import { toast } from 'sonner'; -import PlanFeatures from '../components/PlanFeatures'; import { getIntervalLabel } from '../../lib/intervals'; import { formatMoney } from '../../lib/money'; import type { @@ -19,6 +18,7 @@ import type { PaymentMethod, Subscription, } from '../../types'; +import PlanFeatures from '../components/PlanFeatures'; const longDate: Intl.DateTimeFormatOptions = { year: 'numeric', @@ -193,7 +193,9 @@ export default function SettingsBilling({

{!subscription && lifetimePlans.length ? t('Your plan and payments') - : t('Manage your subscription, payment method, and invoices')} + : t( + 'Manage your subscription, payment method, and invoices', + )}

{/* Lifetime plans are owned for good, alongside any subscription */} @@ -223,7 +225,11 @@ export default function SettingsBilling({ data-testid="lifetime-plan-amount" className="text-foreground font-semibold tabular-nums" > - {formatMoney(plan.amount, plan.currency, locale)} + {formatMoney( + plan.amount, + plan.currency, + locale, + )}

{t('Paid once')} @@ -235,7 +241,7 @@ export default function SettingsBilling({

{plan.paid_at && ( - <> + {t('Bought on :date', { date: formatDate( plan.paid_at, @@ -244,7 +250,7 @@ export default function SettingsBilling({ ), })}{' '} ·{' '} - + )} {t('Yours for good, no renewals.')}

@@ -254,11 +260,15 @@ export default function SettingsBilling({ {subscription ? (
{/* Current plan */} - +

{subscription.interval @@ -275,7 +285,8 @@ export default function SettingsBilling({ data-testid="plan-name" className="text-foreground text-lg font-semibold" > - {subscription.plan_name ?? t('Unknown Plan')} + {subscription.plan_name ?? + t('Unknown Plan')}

{subscription.amount !== null && ( @@ -290,7 +301,8 @@ export default function SettingsBilling({ )} {subscription.interval && ( - {(subscription.interval_count ?? 1) > 1 + {(subscription.interval_count ?? + 1) > 1 ? t('every :count :interval', { count: String( subscription.interval_count, @@ -604,6 +616,9 @@ export default function SettingsBilling({ {t('Date')} + + {t('Item')} + {t('Amount')} @@ -626,6 +641,9 @@ export default function SettingsBilling({ longDate, )} + + {payment.name ?? '—'} + {formatMoney( payment.amount, diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts index 12fa4b7..8058c84 100644 --- a/resources/js/types/index.ts +++ b/resources/js/types/index.ts @@ -26,11 +26,12 @@ export interface Price { /** * What a pricing card's button does, decided on the server (`PlanActions`). * Mirrors the PHP `PlanAction` enum; change one, change the other. `buy`, - * `trial`, `signup`, `change` and `contact` act; `owner_only` explains who can; the rest + * `buy_again`, `trial`, `signup`, `change` and `contact` act; `owner_only` explains who can; the rest * are disabled labels. */ export type PlanAction = | 'buy' + | 'buy_again' | 'signup' | 'change' | 'contact' @@ -116,6 +117,8 @@ export interface LifetimePlan { /** A one-time payment: a lifetime plan's only record, since it has no invoice. */ export interface OneTimePayment { id: number; + /** The plan bought; null once its price is gone. */ + name: string | null; amount: number; currency: string; status: 'succeeded' | 'refunded'; diff --git a/resources/js/vue/components/ProductCard.vue b/resources/js/vue/components/ProductCard.vue index 5ebc321..e96cae8 100644 --- a/resources/js/vue/components/ProductCard.vue +++ b/resources/js/vue/components/ProductCard.vue @@ -30,7 +30,10 @@ const ctaClass = computed(() => ); const startsCheckout = computed( - () => props.action === 'buy' || props.action === 'trial', + () => + props.action === 'buy' || + props.action === 'buy_again' || + props.action === 'trial', ); const enabled = computed( @@ -247,6 +250,9 @@ watch(priceKey, () => { +