diff --git a/composer.json b/composer.json index cdf6683..823688a 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": { - "saucebase/core": "^2.8.1", + "saucebase/core": "^2.11.0", "stripe/stripe-php": "^22.0" }, "license": "MIT", diff --git a/database/migrations/1000_00_01_000001_add_dashboard_indexes.php b/database/migrations/1000_00_01_000001_add_dashboard_indexes.php new file mode 100644 index 0000000..da1300d --- /dev/null +++ b/database/migrations/1000_00_01_000001_add_dashboard_indexes.php @@ -0,0 +1,32 @@ + $table->index(['status', 'currency', 'created_at'])); + Schema::table('subscriptions', function (Blueprint $table): void { + $table->index('created_at'); + $table->index('cancelled_at'); + }); + Schema::table('checkout_sessions', fn (Blueprint $table) => $table->index(['status', 'created_at'])); + } + + public function down(): void + { + Schema::table('payments', fn (Blueprint $table) => $table->dropIndex(['status', 'currency', 'created_at'])); + Schema::table('subscriptions', function (Blueprint $table): void { + $table->dropIndex(['created_at']); + $table->dropIndex(['cancelled_at']); + }); + Schema::table('checkout_sessions', fn (Blueprint $table) => $table->dropIndex(['status', 'created_at'])); + } +}; diff --git a/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index 0858db9..fb51319 100644 --- a/resources/boost/skills/saucebase-billing-development/SKILL.md +++ b/resources/boost/skills/saucebase-billing-development/SKILL.md @@ -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` (date range stats), `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` | | 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` | @@ -119,7 +119,7 @@ A `Product` is a plan, and its `slug` is the plan's stable ID in code. Every pla | `Free` | never sold ($0 prices only, for display) | its entitlements, to everyone | | `Subscription` | recurring prices | its entitlements while it grants access: Active, or PastDue inside its grace window. `trial_days` offers a free trial, once per customer | | `Lifetime` | one-time price | its entitlements until the payment is fully refunded; `replaces_product_id` names the subscription plan it replaces | -| `OneOff` | one-time price | nothing — a service or something the app handles itself | +| `OneOff` | one-time price | nothing itself — a service, or what a module reads off the payment (Packages grants its packages) | Entitlements are `{features: {key: true}, limits: {key: int|null}}` on the plan (`Data\Entitlements`; null is unlimited, a missing limit is 0), edited in the admin's *Plan* step (create wizard) or tab (edit), one table row each. `EditProduct::mutateFormDataBeforeFill()` turns them into rows before the form hydrates: converting later lets the repeater read `features`/`limits` as rows and write stray `unlimited` keys. The app asks the owner: `$user->canUseFeature('exports')`, `$user->planLimit('projects')`; counting projects stays the app's job. Resolution (`Billable::entitlements()`) merges the Free plan, the current subscription's plan and every lifetime plan owned — features combine, the higher limit wins. The Free plan always merges in, so a paid plan can never lower a free limit: intended. Plans are read `withTrashed()` through `Price::plan()`, so archiving or deleting a plan never takes back what was bought. Editing a plan's entitlements changes existing customers' access immediately. @@ -129,7 +129,7 @@ Entitlements are `{features: {key: true}, limits: {key: int|null}}` on the plan - One Free plan at most — a unique index on the generated `free_plan` column. It cannot be deleted; edit it in place. - `replaces_product_id` only on a Lifetime plan, pointing at a Subscription plan other than itself. - `kind`, `slug` and `replaces_product_id` are frozen once the plan is sold (`isSold()`: a Pending or Completed checkout session, a payment, or a subscription on its prices). Checkout creates the session under a `lockForUpdate` on the plan row, and `EditProduct` saves under the same lock in a transaction, so an edit cannot slip in between handoff and payment. -- Entitlement keys are free text up to 255 characters, with no space at either end (`max_projects`, `export data`, `packages:vendor/name`); limits are whole numbers ≥ 0 or null. The key field suggests core's `billing` capabilities (`Capabilities::group('billing')`, a native datalist): modules declare them with `Capabilities::add('billing', …)` in `routes/capabilities.php` (Packages adds `packages:` per package); any other key can still be typed. +- Entitlement keys are free text up to 255 characters, with no space at either end (`max_projects`, `export data`, `packages:vendor/name`); limits are whole numbers ≥ 0 or null. The key field is a searchable select over core's `billing` capabilities, shown by label (`ProductForm::entitlementSearch()`/`entitlementLabel()`): modules and the app declare them with `Capabilities::add('billing', …)` in `routes/capabilities.php` (Packages adds "Package: …" per published package, and `package_updates_days`; an entry's `type: limit` sets the row's type). A typed key the catalogue doesn't list is offered as itself and saves, with a warning naming it after save (`ProductForm::warnAboutUnknownKeys()`); a stored one loads as its key. **Who owns plans.** `Contracts\BillingOwner` (`billingCustomer()`, `billingAccount()`, `entitlements()`, `hasPaidPlan()`, `canUseFeature()`, `planLimit()`, `canManageBilling()`, `notify()`), implemented by `User` through `Billable`. `customers` points at its owner through a polymorphic `owner_type`/`owner_id`, both strings so integer users and ULID workspaces share one column; `Billable::billingCustomer()` is `Models\Relations\OwnerAccount`, a `MorphOne` that binds the owner's key as a string (lazy, eager and create) so MySQL keeps the index, while `whereHas`/`withCount` compare the real columns. On PostgreSQL that column comparison (varchar = bigint) has no operator, so `OwnerAccount` casts the owner's key to text there. There is no subscriber role: check entitlements. @@ -271,7 +271,7 @@ purpose allows it by pattern, e.g. - `Price::amount` is stored in minor currency units (cents) — always divide by 100 for display; `Currency::formatAmount()` handles this - The User model needs `implements BillingOwner` and `use Billable` (`patches/user.patch`, same pattern as Auth's `Sociable`) — entitlement checks and `$user->billingAccount()` fail without them - Products use SoftDeletes; always scope to `active()` or `displayable()` when listing plans -- **Billing history outlives the account.** A polymorphic owner can't have a foreign key, so `Billable` clears `owner_type`/`owner_id` when its owner is deleted (a soft delete keeps the link; only a force delete lets go) and the subscriptions, payments and invoices stay put. That hook needs model events: **delete owners through the model** — a query-builder or bulk delete leaves a dangling `owner_id`. The listener uses `$customer->owner?->notify()`; the admin shows *Account deleted* where the name would be +- **Billing history outlives the account.** A polymorphic owner can't have a foreign key, so `Billable` clears `owner_type`/`owner_id` when its owner is deleted (a soft delete keeps the link; only a force delete lets go) and the subscriptions, payments and invoices stay put. That hook needs model events: **delete owners through the model** — a query-builder or bulk delete leaves a dangling `owner_id`. The listener uses `$customer->owner?->notify()`; the admin shows *Account deleted* where the name would be. Any delete, soft or force, also queues `CancelSubscription` for a current subscription not already cancelled (at period end; a restored owner can Resume), since nobody is left to cancel it. A test that deletes a subscribed owner fakes the queue, or the cancel reaches the provider - `subscriptions.price_id` is `restrictOnDelete`, not cascade: products cascade to prices and the admin can force-delete a product, so cascading would take paid subscriptions with it. Archive the plan instead - `Product` refuses a **force** delete while any of its prices has a `provider_price_id`. Prices cascade from products in the database, and a cascade does not fire the price's own model event, so without this the provider would be silently desynced - `Price` refuses deletion while `provider_price_id` is set — the provider's prices are immutable and subscriptions bill on them, so archive there and sync diff --git a/resources/views/filament/pages/billing-dashboard.blade.php b/resources/views/filament/pages/billing-dashboard.blade.php deleted file mode 100644 index adfba66..0000000 --- a/resources/views/filament/pages/billing-dashboard.blade.php +++ /dev/null @@ -1,36 +0,0 @@ - -
- {{-- Stats cards with filter anchored above-right on desktop --}} -
- {{-- Filter bar: normal flow on mobile, absolute into header row on desktop --}} -
-
- - - @foreach ($this->getPresetOptions() as $value => $label) - - @endforeach - - - - @if ($preset === 'custom') - - - - → - - - - @endif -
-
- - @livewire(\Modules\Billing\Filament\Widgets\BillingSaasStatsWidget::class) -
- - @livewire(\Modules\Billing\Filament\Widgets\RevenueChartWidget::class) - @livewire(\Modules\Billing\Filament\Widgets\SubscriptionsChartWidget::class) - @livewire(\Modules\Billing\Filament\Widgets\ConversionChartWidget::class) - -
-
diff --git a/src/Enums/PlanKind.php b/src/Enums/PlanKind.php index 79908e9..09c4fde 100644 --- a/src/Enums/PlanKind.php +++ b/src/Enums/PlanKind.php @@ -19,7 +19,7 @@ enum PlanKind: string implements HasLabel /** Grants its entitlements for good, until fully refunded. */ case Lifetime = 'lifetime'; - /** Paid once, grants nothing: a service or anything the app handles itself. */ + /** Paid once. Grants only what a module reads off a one-time payment, such as packages; else a service the app handles. */ case OneOff = 'one_off'; public function getLabel(): string @@ -32,6 +32,17 @@ public function getLabel(): string }; } + /** What the kind means, for admins: the form, the view page and the guide all show this. */ + public function description(): string + { + return match ($this) { + self::Free => __('Every customer gets this plan\'s features automatically. It can\'t be bought, and you can only have one.'), + self::Subscription => __('Customers pay on a recurring schedule and keep the features while the subscription is active.'), + self::Lifetime => __('Customers pay once and keep the features unless the payment is fully refunded.'), + self::OneOff => __('Customers pay once. Use it for services such as an onboarding call, or to sell packages. It gives no other features.'), + }; + } + /** Whether its prices renew; the others are sold with one-time prices. */ public function isRecurring(): bool { diff --git a/src/Filament/Pages/BillingDashboard.php b/src/Filament/Pages/BillingDashboard.php index e9e6fe8..dd585a1 100644 --- a/src/Filament/Pages/BillingDashboard.php +++ b/src/Filament/Pages/BillingDashboard.php @@ -3,32 +3,24 @@ namespace Modules\Billing\Filament\Pages; use BackedEnum; -use Carbon\Carbon; -use Filament\Pages\Page; use Filament\Support\Icons\Heroicon; -use Livewire\Attributes\Url; - -class BillingDashboard extends Page +use Modules\Billing\Filament\Widgets\BillingHealthWidget; +use Modules\Billing\Filament\Widgets\BillingSaasStatsWidget; +use Modules\Billing\Filament\Widgets\ConversionChartWidget; +use Modules\Billing\Filament\Widgets\RevenueByPlanChartWidget; +use Modules\Billing\Filament\Widgets\RevenueChartWidget; +use Modules\Billing\Filament\Widgets\SubscriptionsChartWidget; +use Saucebase\Core\Filament\Pages\Dashboard; + +/** Core's dashboard, period picker included, with billing's own widgets. */ +class BillingDashboard extends Dashboard { + protected static string $routePath = 'billing-dashboard'; + protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChartBarSquare; protected static ?int $navigationSort = 200; - protected string $view = 'billing::filament.pages.billing-dashboard'; - - #[Url] - public string $preset = '30d'; - - #[Url] - public ?string $customStart = null; - - #[Url] - public ?string $customEnd = null; - - public string $startDate = ''; - - public string $endDate = ''; - public static function canAccess(): bool { return auth()->user()?->can('manage billing') ?? false; @@ -44,89 +36,25 @@ public static function getNavigationLabel(): string return __('Dashboard'); } - public function mount(): void - { - if ($this->preset === 'custom' && $this->customStart && $this->customEnd) { - $start = Carbon::parse($this->customStart)->startOfDay()->toDateTimeString(); - $end = Carbon::parse($this->customEnd)->endOfDay()->toDateTimeString(); - $this->startDate = $start; - $this->endDate = $end; - $this->dispatch('billing-filter-updated', start: $start, end: $end); - } else { - $this->applyPreset($this->preset !== 'custom' ? $this->preset : '30d'); - } - } - - public function updatedPreset(string $value): void + public function getTitle(): string { - if ($value !== 'custom') { - $this->applyPreset($value); - } else { - $this->customStart = null; - $this->customEnd = null; - } - } - - public function updatedCustomStart(): void - { - if ($this->customStart && $this->customEnd) { - $start = Carbon::parse($this->customStart)->startOfDay()->toDateTimeString(); - $end = Carbon::parse($this->customEnd)->endOfDay()->toDateTimeString(); - $this->startDate = $start; - $this->endDate = $end; - $this->dispatch('billing-filter-updated', start: $start, end: $end); - } - } - - public function updatedCustomEnd(): void - { - if ($this->customStart && $this->customEnd) { - $start = Carbon::parse($this->customStart)->startOfDay()->toDateTimeString(); - $end = Carbon::parse($this->customEnd)->endOfDay()->toDateTimeString(); - $this->startDate = $start; - $this->endDate = $end; - $this->dispatch('billing-filter-updated', start: $start, end: $end); - } + return __('Billing'); } - /** - * @return array - */ - public function getPresetOptions(): array + public function getWidgets(): array { return [ - 'today' => __('Today'), - '7d' => __('Last 7 days'), - '30d' => __('Last 30 days'), - '90d' => __('Last 3 months'), - '12m' => __('Last 12 months'), - 'custom' => __('Custom range'), + BillingSaasStatsWidget::class, + BillingHealthWidget::class, + RevenueChartWidget::class, + SubscriptionsChartWidget::class, + ConversionChartWidget::class, + RevenueByPlanChartWidget::class, ]; } - private function applyPreset(string $preset): void + public function getColumns(): int|array { - [$start, $end] = $this->computeDateRange($preset); - $this->startDate = $start; - $this->endDate = $end; - $this->dispatch('billing-filter-updated', start: $start, end: $end); - } - - /** - * @return array{string, string} - */ - private function computeDateRange(string $preset): array - { - $end = now(); - $start = match ($preset) { - 'today' => now()->startOfDay(), - '7d' => now()->subDays(7)->startOfDay(), - '30d' => now()->subDays(30)->startOfDay(), - '90d' => now()->subDays(90)->startOfDay(), - '12m' => now()->subMonths(12)->startOfDay(), - default => now()->subDays(30)->startOfDay(), - }; - - return [$start->toDateTimeString(), $end->toDateTimeString()]; + return 2; } } diff --git a/src/Filament/Resources/Products/Pages/CreateProduct.php b/src/Filament/Resources/Products/Pages/CreateProduct.php index 4309d23..ac40cbe 100644 --- a/src/Filament/Resources/Products/Pages/CreateProduct.php +++ b/src/Filament/Resources/Products/Pages/CreateProduct.php @@ -7,6 +7,7 @@ use Filament\Schemas\Components\Wizard\Step; use Modules\Billing\Filament\Resources\Products\ProductResource; use Modules\Billing\Filament\Resources\Products\Schemas\ProductForm; +use Modules\Billing\Models\Product; class CreateProduct extends CreateRecord { @@ -20,6 +21,15 @@ protected function getSteps(): array return ProductForm::steps(); } + protected function afterCreate(): void + { + $record = $this->getRecord(); + + if ($record instanceof Product) { + ProductForm::warnAboutUnknownKeys($record); + } + } + protected function getHeaderActions(): array { return [ProductForm::guideAction()]; diff --git a/src/Filament/Resources/Products/Pages/EditProduct.php b/src/Filament/Resources/Products/Pages/EditProduct.php index c0bee21..25388bf 100644 --- a/src/Filament/Resources/Products/Pages/EditProduct.php +++ b/src/Filament/Resources/Products/Pages/EditProduct.php @@ -8,6 +8,7 @@ use Filament\Actions\ViewAction; use Filament\Resources\Pages\EditRecord; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\DB; use Modules\Billing\Filament\Actions\PushProductAction; use Modules\Billing\Filament\Resources\Products\ProductResource; use Modules\Billing\Filament\Resources\Products\Schemas\ProductForm; @@ -51,6 +52,19 @@ protected function handleRecordUpdate(Model $record, array $data): Model return parent::handleRecordUpdate($record, $data); } + /** + * Saved either way: an app may check a key it never declared. The warning catches a typo. + * It says "Saved", so it waits for the commit: a listener can still roll the save back. + */ + protected function afterSave(): void + { + $record = $this->getRecord(); + + if ($record instanceof Product) { + DB::afterCommit(fn () => ProductForm::warnAboutUnknownKeys($record)); + } + } + protected function getHeaderActions(): array { return [ diff --git a/src/Filament/Resources/Products/Schemas/ProductForm.php b/src/Filament/Resources/Products/Schemas/ProductForm.php index d4c0608..730ecba 100644 --- a/src/Filament/Resources/Products/Schemas/ProductForm.php +++ b/src/Filament/Resources/Products/Schemas/ProductForm.php @@ -10,6 +10,7 @@ use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; +use Filament\Notifications\Notification; use Filament\Schemas\Components\Component; use Filament\Schemas\Components\Grid; use Filament\Schemas\Components\Section; @@ -17,6 +18,7 @@ use Filament\Schemas\Components\Tabs\Tab; use Filament\Schemas\Components\Text; use Filament\Schemas\Components\Utilities\Get; +use Filament\Schemas\Components\Utilities\Set; use Filament\Schemas\Components\Wizard\Step; use Filament\Schemas\Schema; use Modules\Billing\Enums\Currency; @@ -40,9 +42,14 @@ private static function priceManagedByGateway(Get $get): bool return filled($get('provider_price_id')); } + private static function kindOf(mixed $state): ?PlanKind + { + return $state instanceof PlanKind ? $state : PlanKind::tryFrom((string) $state); + } + private static function kindIs(mixed $state, PlanKind $kind): bool { - return ($state instanceof PlanKind ? $state : PlanKind::tryFrom((string) $state)) === $kind; + return self::kindOf($state) === $kind; } /** @param array $state A price row: its currency is the enum once saved, a string while unsaved. */ @@ -100,6 +107,69 @@ private static function storedEntitlements(?array $rows): ?array return $stored === ['features' => [], 'limits' => []] ? null : $stored; } + /** @return array> core's `billing` capabilities, by key */ + private static function catalogue(): array + { + return app(Capabilities::class)->group('billing'); + } + + /** A key's label, or the key itself when the catalogue doesn't list it. */ + public static function entitlementLabel(string $key): string + { + return self::catalogue()[$key]['label'] ?? $key; + } + + /** + * Catalogue entries matching the search by label or key, then what was typed, so a key + * the catalogue doesn't list can still be used. The typed option says it's a raw key: it + * can read like a catalogue label ("Seats") without carrying that entry's type. + * + * @return array + */ + public static function entitlementSearch(string $search): array + { + $search = trim($search); + $matches = collect(self::catalogue()) + ->filter(fn (array $entry, string $key): bool => $search === '' || str_contains(mb_strtolower($entry['label'].' '.$key), mb_strtolower($search))) + ->map(fn (array $entry): string => $entry['label']) + ->all(); + + return $search === '' || isset($matches[$search]) + ? $matches + : [...$matches, $search => __('Use the key ":key"', ['key' => $search])]; + } + + /** + * The keys of a stored entitlements value the catalogue doesn't list, for a warning. + * + * @param array{features?: array, limits?: array}|null $stored + * @return list + */ + public static function unknownKeys(?array $stored): array + { + $keys = [...array_keys($stored['features'] ?? []), ...array_keys($stored['limits'] ?? [])]; + + return array_values(array_diff($keys, array_keys(self::catalogue()))); + } + + /** Tell the admin which keys the catalogue doesn't list, so a typo doesn't sell nothing unnoticed. */ + public static function warnAboutUnknownKeys(Product $product): void + { + $unknown = array_values(array_unique([ + ...self::unknownKeys($product->entitlements), + ...self::unknownKeys($product->trial_entitlements), + ])); + + if ($unknown !== []) { + Notification::make() + ->warning() + ->title(__('Not in the catalogue: :keys', ['keys' => implode(', ', $unknown)])) + ->body(__('Saved. Check the spelling, or declare the key in routes/capabilities.php so it can be picked.')) + ->persistent() + ->send(); + } + } + /** * One row per entitlement. A trial's rows may also switch a feature off. */ @@ -107,15 +177,30 @@ private static function entitlementsRepeater(string $name, bool $trial = false): { return Repeater::make($name) ->schema([ - TextInput::make('key') + // Picked by label from what the modules offer (core's `billing` capabilities); + // a typed key the catalogue doesn't list still works, and saving warns about it. + Select::make('key') ->label(__('Key')) ->required() - ->regex('/^\S(.*\S)?$/u') - ->maxLength(255) + ->searchable() + ->getSearchResultsUsing(fn (string $search): array => self::entitlementSearch($search)) + ->getOptionLabelUsing(fn (?string $value): ?string => $value === null ? null : self::entitlementLabel($value)) + ->rules(['string', 'max:255', 'regex:/^\S(.*\S)?$/u']) ->distinct() - ->placeholder('max_projects') - // What the modules offer (core's `billing` capabilities); any other key still works. - ->datalist(fn (): array => array_keys(app(Capabilities::class)->group('billing'))), + ->placeholder(__('Search, or type a key such as max_projects')) + ->live() + // A catalogue entry sets its type: `type: limit` (`package_updates_days`) a + // limit, anything else a feature, so a package never saves as a limit. A key + // the catalogue doesn't list keeps what the admin chose. + ->afterStateUpdated(function (?string $state, Get $get, Set $set): void { + $entry = self::catalogue()[$state] ?? null; + + if ($entry !== null) { + $limit = ($entry['type'] ?? null) === 'limit'; + // A trial row's `off` is still a feature: keep it. + $set('type', $limit ? 'limit' : ($get('type') === 'off' ? 'off' : 'feature')); + } + }), Select::make('type') ->label(__('Type')) ->options($trial @@ -230,9 +315,10 @@ private static function groups(): array ->required() ->live() ->disabled(fn (?Product $record) => $record?->isSold() ?? false) - ->helperText(fn (?Product $record) => $record?->isSold() - ? __('Fixed: this plan has been sold. Create a new plan to change it.') - : __('Free is everyone\'s baseline and is never sold. One-off plans grant nothing.')), + ->helperText(fn (Get $get, ?Product $record) => trim( + ($record?->isSold() ? __('Fixed: this plan has been sold. Create a new plan to change it.').' ' : '') + .self::kindOf($get('kind'))?->description(), + )), Select::make('replaces_product_id') ->label(__('Replaces plan')) @@ -273,7 +359,7 @@ private static function groups(): array ->relationship() ->label(__('Prices')) ->deleteAction(fn (Action $action) => $action->hidden( - fn (array $arguments, Repeater $component) => filled($component->getItemState($arguments['item'])['provider_price_id'] ?? null), + fn (array $arguments, Repeater $component) => filled($component->getRawItemState($arguments['item'])['provider_price_id'] ?? null), )) ->schema([ Grid::make(3)->schema([ @@ -421,7 +507,8 @@ public static function guideAction(): Action ]), Section::make(__('2. Plan')) ->schema([ - Text::make(__('Kind decides what buying it means. Free: everyone\'s baseline, never sold, one at most. Subscription: recurring prices, grants its entitlements while paid (and through the grace period). Lifetime: one payment, grants its entitlements until fully refunded. One-off: one payment, grants nothing; for services the app handles itself.')), + Text::make(__('Kind decides what buying it means.')), + ...array_map(fn (PlanKind $kind) => Text::make($kind->getLabel().': '.$kind->description()), PlanKind::cases()), Text::make(__('A lifetime plan can replace a subscription plan: buying it ends that subscription at the end of its period.')), Text::make(__('Kind, slug and replaced plan are fixed once the plan is sold. To change them, create a new plan and hide this one.')), Text::make(__('A trial is offered once per customer, ever.')), diff --git a/src/Filament/Resources/Products/Schemas/ProductInfolist.php b/src/Filament/Resources/Products/Schemas/ProductInfolist.php index 2837199..a4ca50c 100644 --- a/src/Filament/Resources/Products/Schemas/ProductInfolist.php +++ b/src/Filament/Resources/Products/Schemas/ProductInfolist.php @@ -10,6 +10,7 @@ use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; use Filament\Support\Enums\Alignment; +use Modules\Billing\Enums\PlanKind; use Modules\Billing\Models\Price; use Modules\Billing\Models\Product; @@ -45,48 +46,17 @@ public static function configure(Schema $schema): Schema ->components([ Grid::make(1) ->schema([ - Section::make(__('Basic Information')) + Section::make(__('Plan')) ->schema([ TextEntry::make('name') ->label(__('Name')) ->columnSpanFull(), - TextEntry::make('slug') - ->label(__('Slug')) - ->copyable() - ->columnSpanFull(), - - TextEntry::make('sku') - ->label(__('SKU')) - ->copyable(), - - TextEntry::make('description') - ->label(__('Description')) - ->html() - ->columnSpanFull(), - - TextEntry::make('created_at') - ->label(__('Created At')) - ->dateTime(), - - TextEntry::make('updated_at') - ->label(__('Updated At')) - ->dateTime(), - - TextEntry::make('deleted_at') - ->label(__('Deleted At')) - ->dateTime() - ->icon('heroicon-o-trash') - ->color('danger') - ->hidden(fn ($record) => $record->deleted_at === null), - ]) - ->columns(2), - - Section::make(__('Plan')) - ->schema([ TextEntry::make('kind') ->label(__('Kind')) - ->badge(), + ->badge() + ->belowContent(fn (Product $record) => $record->kind->description()) + ->columnSpanFull(), TextEntry::make('replaces.name') ->label(__('Replaces plan')) @@ -103,6 +73,8 @@ public static function configure(Schema $schema): Schema ->listWithLineBreaks() ->bulleted() ->placeholder(__('No entitlements')) + // A one-off plan gives none by design: an empty line would read as missing. + ->hidden(fn (Product $record) => $record->kind === PlanKind::OneOff && blank(self::entitlementLines($record->entitlements()->toArray()))) ->columnSpanFull(), TextEntry::make('trial_entitlement_list') @@ -113,7 +85,7 @@ public static function configure(Schema $schema): Schema ->visible(fn (Product $record) => $record->trial_days !== null && filled($record->trial_entitlements)) ->columnSpanFull(), ]) - ->columns(3), + ->columns(2), Section::make(__('Pricing')) ->schema([ @@ -195,6 +167,40 @@ public static function configure(Schema $schema): Schema ->hidden(fn ($record) => ! empty($record->features)), ])->collapsible(), + Section::make(__('Details')) + ->schema([ + TextEntry::make('slug') + ->label(__('Slug')) + ->copyable() + ->columnSpanFull(), + + TextEntry::make('sku') + ->label(__('SKU')) + ->copyable(), + + TextEntry::make('description') + ->label(__('Description')) + ->html() + ->columnSpanFull(), + + TextEntry::make('created_at') + ->label(__('Created At')) + ->dateTime(), + + TextEntry::make('updated_at') + ->label(__('Updated At')) + ->dateTime(), + + TextEntry::make('deleted_at') + ->label(__('Deleted At')) + ->dateTime() + ->icon('heroicon-o-trash') + ->color('danger') + ->hidden(fn ($record) => $record->deleted_at === null), + ]) + ->columns(2) + ->collapsible(), + Section::make(__('Metadata')) ->schema([ KeyValueEntry::make('metadata') diff --git a/src/Filament/Traits/GroupsByMonth.php b/src/Filament/Traits/GroupsByMonth.php deleted file mode 100644 index 7c8ddf0..0000000 --- a/src/Filament/Traits/GroupsByMonth.php +++ /dev/null @@ -1,42 +0,0 @@ -getModel()->getConnection()->getDriverName()) { - 'pgsql' => "to_char(created_at, 'YYYY-MM')", - 'sqlite' => "strftime('%Y-%m', created_at)", - default => "date_format(created_at, '%Y-%m')", - }; - } - - /** - * Every month in the range, so a month with nothing in it still shows. - * - * @return array - */ - protected function monthlyBuckets(int|float $empty = 0): array - { - $buckets = []; - $cursor = Carbon::parse($this->startDate)->startOfMonth(); - $end = Carbon::parse($this->endDate)->endOfMonth(); - - while ($cursor <= $end) { - $buckets[$cursor->format('Y-m')] = $empty; - $cursor->addMonth(); - } - - return $buckets; - } -} diff --git a/src/Filament/Widgets/BillingAttentionWidget.php b/src/Filament/Widgets/BillingAttentionWidget.php new file mode 100644 index 0000000..9bf80dc --- /dev/null +++ b/src/Filament/Widgets/BillingAttentionWidget.php @@ -0,0 +1,55 @@ +getCachedStats()); + } + + public static function canView(): bool + { + return (auth()->user()?->can('manage billing') ?? false) + && ((new BillingMetrics)->pastDue() > 0 || self::recentlyFailed() > 0); + } + + protected function getStats(): array + { + $pastDue = (new BillingMetrics)->pastDue(); + $failed = self::recentlyFailed(); + + return array_values(array_filter([ + $pastDue > 0 ? Stat::make(__('Past due subscriptions'), $pastDue) + ->description(__('Waiting on a payment')) + ->color('warning') + ->url(SubscriptionResource::getUrl('index')) : null, + $failed > 0 ? Stat::make(__('Failed payments'), $failed) + ->description(__('Last 7 days')) + ->color('danger') : null, + ])); + } + + private static function recentlyFailed(): int + { + return Payment::where('status', PaymentStatus::Failed)->where('created_at', '>=', now()->subDays(7))->count(); + } +} diff --git a/src/Filament/Widgets/BillingHealthWidget.php b/src/Filament/Widgets/BillingHealthWidget.php new file mode 100644 index 0000000..89f69a2 --- /dev/null +++ b/src/Filament/Widgets/BillingHealthWidget.php @@ -0,0 +1,56 @@ +user()?->can('manage billing') ?? false; + } + + protected function getStats(): array + { + $metrics = new BillingMetrics; + $period = $this->period(); + $previous = $period->previous(); + $money = fn (int|float $amount): string => Currency::default()->formatAmount((int) $amount); + $percent = fn (int|float $rate): string => $rate.'%'; + + $active = $metrics->activeAt($period->end); + $activeBefore = $metrics->activeAt($period->start); + + return [ + TrendStat::make(__('Active subscriptions'), $active, $activeBefore), + $this->rate(__('Churn'), $metrics->churnRate($period), $metrics->churnRate($previous), $percent, lowerIsBetter: true), + TrendStat::make(__('ARPU'), $metrics->arpuAt($period->end), $metrics->arpuAt($period->start), format: $money), + $this->rate(__('Checkout conversion'), $metrics->conversionRate($period), $metrics->conversionRate($previous), $percent), + TrendStat::make(__('Refunds'), $metrics->refunds($period), $metrics->refunds($previous), lowerIsBetter: true, format: $money), + TrendStat::make(__('Failed payments'), $metrics->failedPayments($period), $metrics->failedPayments($previous), lowerIsBetter: true), + ]; + } + + /** A rate with nothing to divide by is a dash, not 0%. */ + private function rate(string $label, ?float $now, ?float $before, \Closure $format, bool $lowerIsBetter = false): Stat + { + return $now === null + ? Stat::make($label, '—')->description(__('Not enough data in this period'))->color('gray') + : TrendStat::make($label, $now, $before ?? 0, lowerIsBetter: $lowerIsBetter, format: $format); + } +} diff --git a/src/Filament/Widgets/BillingSaasStatsWidget.php b/src/Filament/Widgets/BillingSaasStatsWidget.php index 4d701eb..dbaf739 100644 --- a/src/Filament/Widgets/BillingSaasStatsWidget.php +++ b/src/Filament/Widgets/BillingSaasStatsWidget.php @@ -2,127 +2,51 @@ namespace Modules\Billing\Filament\Widgets; -use Filament\Widgets\StatsOverviewWidget as BaseWidget; +use Filament\Widgets\StatsOverviewWidget; use Filament\Widgets\StatsOverviewWidget\Stat; -use Livewire\Attributes\On; -use Modules\Billing\Enums\CheckoutSessionStatus; use Modules\Billing\Enums\Currency; -use Modules\Billing\Enums\PaymentStatus; -use Modules\Billing\Enums\SubscriptionStatus; -use Modules\Billing\Models\CheckoutSession; -use Modules\Billing\Models\Payment; -use Modules\Billing\Models\Subscription; - -class BillingSaasStatsWidget extends BaseWidget +use Modules\Billing\Filament\Resources\Products\ProductResource; +use Modules\Billing\Models\Product; +use Modules\Billing\Support\BillingMetrics; +use Saucebase\Core\Filament\Concerns\ReadsPeriod; +use Saucebase\Core\Filament\TrendStat; + +/** Revenue, MRR and new subscriptions: on both the main dashboard (stats band, 12, full width) and billing's. */ +class BillingSaasStatsWidget extends StatsOverviewWidget { - protected static ?int $sort = 1; + use ReadsPeriod; - protected ?string $pollingInterval = null; + protected static ?int $sort = 12; - public string $startDate = ''; + protected ?string $pollingInterval = null; - public string $endDate = ''; + protected int|string|array $columnSpan = 'full'; public static function canView(): bool { return auth()->user()?->can('manage billing') ?? false; } - public function mount(): void + protected function getStats(): array { - $this->startDate = now()->subDays(30)->startOfDay()->toDateTimeString(); - $this->endDate = now()->toDateTimeString(); - } + if (! Product::exists()) { + return [ + Stat::make(__('Billing'), __('Set up billing')) + ->description(__('Add your first plan to start selling')) + ->descriptionIcon('heroicon-m-arrow-right') + ->url(ProductResource::getUrl('create')), + ]; + } - #[On('billing-filter-updated')] - public function billingFilterUpdated(string $start, string $end): void - { - $this->startDate = $start; - $this->endDate = $end; - $this->cachedStats = null; - } + $metrics = new BillingMetrics; + $period = $this->period(); + $previous = $period->previous(); + $money = fn (int|float $amount): string => Currency::default()->formatAmount((int) $amount); - protected function getStats(): array - { return [ - $this->mrrStat(), - $this->activeSubscriptionsStat(), - $this->totalRevenueStat(), - $this->conversionRateStat(), + TrendStat::make(__('Revenue'), $metrics->revenue($period), $metrics->revenue($previous), $metrics->revenueSeries($period), format: $money), + TrendStat::make(__('MRR'), $metrics->mrrAt($period->end), $metrics->mrrAt($period->start), format: $money), + TrendStat::make(__('New subscriptions'), $metrics->newSubscriptions($period), $metrics->newSubscriptions($previous), $metrics->newSubscriptionsSeries($period)), ]; } - - private function mrrStat(): Stat - { - // One currency only: amounts in different currencies do not add up. - $mrr = (int) Subscription::query() - ->where('status', SubscriptionStatus::Active) - ->whereHas('price', fn ($query) => $query->where('currency', Currency::default())) - ->with('price') - ->get() - ->sum(function (Subscription $subscription): float { - $price = $subscription->price; - - if (! $price || ! $price->interval) { - return 0; - } - - $divisor = match ($price->interval) { - 'month' => $price->interval_count ?? 1, - 'year' => ($price->interval_count ?? 1) * 12, - default => 1, - }; - - return $price->amount / $divisor; - }); - - return Stat::make(__('MRR'), Currency::default()->formatAmount($mrr)) - ->description(__('Recurring monthly revenue')) - ->descriptionIcon('heroicon-m-arrow-trending-up') - ->color('success'); - } - - private function activeSubscriptionsStat(): Stat - { - $count = Subscription::where('status', SubscriptionStatus::Active)->count(); - - return Stat::make(__('Active Subscriptions'), number_format($count)) - ->description(__('Active right now')) - ->descriptionIcon('heroicon-m-user-group') - ->color('info'); - } - - private function totalRevenueStat(): Stat - { - $total = (int) Payment::where('status', PaymentStatus::Succeeded) - ->where('currency', Currency::default()) - ->whereBetween('created_at', [$this->startDate, $this->endDate]) - ->sum('amount'); - - return Stat::make(__('Total Revenue'), Currency::default()->formatAmount($total)) - ->description(__('Succeeded :currency payments in period', ['currency' => Currency::default()->value])) - ->descriptionIcon('heroicon-m-banknotes') - ->color('warning'); - } - - private function conversionRateStat(): Stat - { - $result = CheckoutSession::whereBetween('created_at', [$this->startDate, $this->endDate]) - ->whereIn('status', [ - CheckoutSessionStatus::Completed->value, - CheckoutSessionStatus::Abandoned->value, - CheckoutSessionStatus::Expired->value, - ]) - ->selectRaw('SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as completed, COUNT(*) as total', [CheckoutSessionStatus::Completed->value]) - ->first(); - - $total = $result ? (int) $result->getAttribute('total') : 0; - $completed = $result ? (int) $result->getAttribute('completed') : 0; - $rate = $total > 0 ? round($completed / $total * 100, 1) : 0; - - return Stat::make(__('Checkout Conversion Rate'), $rate.'%') - ->description(__('Completed checkouts in period')) - ->descriptionIcon('heroicon-m-shopping-cart') - ->color('info'); - } } diff --git a/src/Filament/Widgets/ConversionChartWidget.php b/src/Filament/Widgets/ConversionChartWidget.php index 21036e0..e654a2f 100644 --- a/src/Filament/Widgets/ConversionChartWidget.php +++ b/src/Filament/Widgets/ConversionChartWidget.php @@ -2,17 +2,14 @@ namespace Modules\Billing\Filament\Widgets; -use Carbon\Carbon; -use Filament\Support\RawJs; use Filament\Widgets\ChartWidget; -use Livewire\Attributes\On; -use Modules\Billing\Enums\CheckoutSessionStatus; -use Modules\Billing\Filament\Traits\GroupsByMonth; -use Modules\Billing\Models\CheckoutSession; +use Modules\Billing\Support\BillingMetrics; +use Saucebase\Core\Filament\Concerns\ReadsPeriod; +/** Billing dashboard only. Buckets by day, week or month, following the period. */ class ConversionChartWidget extends ChartWidget { - use GroupsByMonth; + use ReadsPeriod; protected static bool $isDiscovered = false; @@ -20,31 +17,14 @@ class ConversionChartWidget extends ChartWidget protected ?string $maxHeight = '300px'; - public string $startDate = ''; - - public string $endDate = ''; - public static function canView(): bool { return auth()->user()?->can('manage billing') ?? false; } - public function mount(): void - { - $this->startDate = now()->subDays(30)->startOfDay()->toDateTimeString(); - $this->endDate = now()->toDateTimeString(); - - parent::mount(); - } - public function getHeading(): string { - return __('Checkout Conversion Rate Over Time'); - } - - public function getDescription(): string - { - return __('Monthly checkout session conversion percentage'); + return __('Checkout conversion (%)'); } protected function getType(): string @@ -52,85 +32,19 @@ protected function getType(): string return 'line'; } - protected function getOptions(): array|RawJs|null - { - return RawJs::make(<<<'JS' - { - scales: { - y: { - ticks: { - callback: (value) => value + '%', - }, - min: 0, - max: 100, - }, - }, - } - JS); - } - - #[On('billing-filter-updated')] - public function billingFilterUpdated(string $start, string $end): void - { - $this->startDate = $start; - $this->endDate = $end; - $this->cachedData = null; - $this->updateChartData(); - } - - /** - * @return array - */ + /** @return array */ protected function getData(): array { - $buckets = $this->monthlyBuckets(0.0); - - try { - $query = CheckoutSession::query(); - - $rows = $query->whereBetween('created_at', [$this->startDate, $this->endDate]) - ->whereIn('status', [ - CheckoutSessionStatus::Completed->value, - CheckoutSessionStatus::Abandoned->value, - CheckoutSessionStatus::Expired->value, - ]) - ->selectRaw( - $this->monthOf($query).' as month, SUM(CASE WHEN status = ? THEN 1 ELSE 0 END) as completed, COUNT(*) as total', - [CheckoutSessionStatus::Completed->value] - ) - ->groupBy('month') - ->orderBy('month') - ->get(); - - foreach ($rows as $row) { - $month = (string) $row->getAttribute('month'); - $total = (int) $row->getAttribute('total'); - $completed = (int) $row->getAttribute('completed'); - if (array_key_exists($month, $buckets) && $total > 0) { - $buckets[$month] = round($completed / $total * 100, 1); - } - } - } catch (\Throwable $e) { - report($e); - } - - $labels = array_map( - fn (string $month) => Carbon::parse($month.'-01')->format('M Y'), - array_keys($buckets) - ); + $period = $this->period(); return [ - 'datasets' => [ - [ - 'label' => __('Conversion Rate'), - 'data' => array_values($buckets), - 'borderColor' => 'rgb(245, 158, 11)', - 'backgroundColor' => 'rgba(245, 158, 11, 0.1)', - 'tension' => 0.3, - 'fill' => false, - ], - ], - 'labels' => $labels, + 'datasets' => [[ + 'label' => __('Conversion'), + 'data' => (new BillingMetrics)->conversionSeries($period), + 'borderColor' => 'rgb(245, 158, 11)', + 'tension' => 0.3, + ]], + 'labels' => array_values($period->labels()), ]; } } diff --git a/src/Filament/Widgets/RevenueByPlanChartWidget.php b/src/Filament/Widgets/RevenueByPlanChartWidget.php new file mode 100644 index 0000000..bd259a8 --- /dev/null +++ b/src/Filament/Widgets/RevenueByPlanChartWidget.php @@ -0,0 +1,53 @@ +user()?->can('manage billing') ?? false; + } + + public function getHeading(): string + { + return __('Revenue by plan'); + } + + protected function getType(): string + { + return 'doughnut'; + } + + /** @return array */ + protected function getData(): array + { + $plans = (new BillingMetrics)->revenueByPlan($this->period()); + + return [ + 'datasets' => [[ + 'label' => __('Revenue'), + 'data' => array_map(fn (int $minor): float => round($minor / 100, 2), array_values($plans)), + 'backgroundColor' => array_map(fn (int $i): string => self::COLORS[$i % count(self::COLORS)], array_keys(array_values($plans))), + ]], + // A numeric plan name comes back as an int key. + 'labels' => array_map(fn (int|string $plan): string => $plan === '' ? __('Other') : (string) $plan, array_keys($plans)), + ]; + } +} diff --git a/src/Filament/Widgets/RevenueChartWidget.php b/src/Filament/Widgets/RevenueChartWidget.php index bf48a55..acef58c 100644 --- a/src/Filament/Widgets/RevenueChartWidget.php +++ b/src/Filament/Widgets/RevenueChartWidget.php @@ -2,16 +2,14 @@ namespace Modules\Billing\Filament\Widgets; -use Carbon\Carbon; use Filament\Widgets\ChartWidget; -use Livewire\Attributes\On; -use Modules\Billing\Enums\PaymentStatus; -use Modules\Billing\Filament\Traits\GroupsByMonth; -use Modules\Billing\Models\Payment; +use Modules\Billing\Support\BillingMetrics; +use Saucebase\Core\Filament\Concerns\ReadsPeriod; +/** Billing dashboard only. Buckets by day, week or month, following the period. */ class RevenueChartWidget extends ChartWidget { - use GroupsByMonth; + use ReadsPeriod; protected static bool $isDiscovered = false; @@ -19,31 +17,14 @@ class RevenueChartWidget extends ChartWidget protected ?string $maxHeight = '300px'; - public string $startDate = ''; - - public string $endDate = ''; - public static function canView(): bool { return auth()->user()?->can('manage billing') ?? false; } - public function mount(): void - { - $this->startDate = now()->subDays(30)->startOfDay()->toDateTimeString(); - $this->endDate = now()->toDateTimeString(); - - parent::mount(); - } - public function getHeading(): string { - return __('Revenue Over Time'); - } - - public function getDescription(): string - { - return __('Monthly revenue from succeeded payments'); + return __('Revenue'); } protected function getType(): string @@ -51,59 +32,19 @@ protected function getType(): string return 'line'; } - #[On('billing-filter-updated')] - public function billingFilterUpdated(string $start, string $end): void - { - $this->startDate = $start; - $this->endDate = $end; - $this->cachedData = null; - $this->updateChartData(); - } - - /** - * @return array - */ + /** @return array */ protected function getData(): array { - $buckets = $this->monthlyBuckets(); - - try { - $query = Payment::query(); - - $rows = $query->where('status', PaymentStatus::Succeeded) - ->whereBetween('created_at', [$this->startDate, $this->endDate]) - ->selectRaw($this->monthOf($query).' as month, SUM(amount) as total') - ->groupBy('month') - ->orderBy('month') - ->get(); - - foreach ($rows as $row) { - $month = (string) $row->getAttribute('month'); - if (array_key_exists($month, $buckets)) { - $buckets[$month] = (int) $row->getAttribute('total'); - } - } - } catch (\Throwable $e) { - report($e); - } - - $labels = array_map( - fn (string $month) => Carbon::parse($month.'-01')->format('M Y'), - array_keys($buckets) - ); + $period = $this->period(); return [ - 'datasets' => [ - [ - 'label' => __('Revenue'), - 'data' => array_values($buckets), - 'borderColor' => 'rgb(99, 102, 241)', - 'backgroundColor' => 'rgba(99, 102, 241, 0.1)', - 'tension' => 0.3, - 'fill' => false, - ], - ], - 'labels' => $labels, + 'datasets' => [[ + 'label' => __('Revenue'), + 'data' => array_map(fn (int|float $minor): float => round($minor / 100, 2), (new BillingMetrics)->revenueSeries($period)), + 'borderColor' => 'rgb(99, 102, 241)', + 'tension' => 0.3, + ]], + 'labels' => array_values($period->labels()), ]; } } diff --git a/src/Filament/Widgets/SubscriptionsChartWidget.php b/src/Filament/Widgets/SubscriptionsChartWidget.php index ff66cfe..8e5ae54 100644 --- a/src/Filament/Widgets/SubscriptionsChartWidget.php +++ b/src/Filament/Widgets/SubscriptionsChartWidget.php @@ -2,15 +2,14 @@ namespace Modules\Billing\Filament\Widgets; -use Carbon\Carbon; use Filament\Widgets\ChartWidget; -use Livewire\Attributes\On; -use Modules\Billing\Filament\Traits\GroupsByMonth; -use Modules\Billing\Models\Subscription; +use Modules\Billing\Support\BillingMetrics; +use Saucebase\Core\Filament\Concerns\ReadsPeriod; +/** Billing dashboard only. Buckets by day, week or month, following the period. */ class SubscriptionsChartWidget extends ChartWidget { - use GroupsByMonth; + use ReadsPeriod; protected static bool $isDiscovered = false; @@ -18,31 +17,14 @@ class SubscriptionsChartWidget extends ChartWidget protected ?string $maxHeight = '300px'; - public string $startDate = ''; - - public string $endDate = ''; - public static function canView(): bool { return auth()->user()?->can('manage billing') ?? false; } - public function mount(): void - { - $this->startDate = now()->subDays(30)->startOfDay()->toDateTimeString(); - $this->endDate = now()->toDateTimeString(); - - parent::mount(); - } - public function getHeading(): string { - return __('New Subscriptions Over Time'); - } - - public function getDescription(): string - { - return __('Monthly count of new subscriptions created'); + return __('New subscriptions'); } protected function getType(): string @@ -50,58 +32,19 @@ protected function getType(): string return 'line'; } - #[On('billing-filter-updated')] - public function billingFilterUpdated(string $start, string $end): void - { - $this->startDate = $start; - $this->endDate = $end; - $this->cachedData = null; - $this->updateChartData(); - } - - /** - * @return array - */ + /** @return array */ protected function getData(): array { - $buckets = $this->monthlyBuckets(); - - try { - $query = Subscription::query(); - - $rows = $query->whereBetween('created_at', [$this->startDate, $this->endDate]) - ->selectRaw($this->monthOf($query).' as month, COUNT(*) as total') - ->groupBy('month') - ->orderBy('month') - ->get(); - - foreach ($rows as $row) { - $month = (string) $row->getAttribute('month'); - if (array_key_exists($month, $buckets)) { - $buckets[$month] = (int) $row->getAttribute('total'); - } - } - } catch (\Throwable $e) { - report($e); - } - - $labels = array_map( - fn (string $month) => Carbon::parse($month.'-01')->format('M Y'), - array_keys($buckets) - ); + $period = $this->period(); return [ - 'datasets' => [ - [ - 'label' => __('New Subscriptions'), - 'data' => array_values($buckets), - 'borderColor' => 'rgb(16, 185, 129)', - 'backgroundColor' => 'rgba(16, 185, 129, 0.1)', - 'tension' => 0.3, - 'fill' => false, - ], - ], - 'labels' => $labels, + 'datasets' => [[ + 'label' => __('New subscriptions'), + 'data' => (new BillingMetrics)->newSubscriptionsSeries($period), + 'borderColor' => 'rgb(16, 185, 129)', + 'tension' => 0.3, + ]], + 'labels' => array_values($period->labels()), ]; } } diff --git a/src/Support/BillingMetrics.php b/src/Support/BillingMetrics.php new file mode 100644 index 0000000..1d8fd18 --- /dev/null +++ b/src/Support/BillingMetrics.php @@ -0,0 +1,252 @@ + this instance's answers, so one widget asking twice queries once */ + private array $answered = []; + + private ?Currency $currency = null; + + /** Net of refunds, from payments made in the period. */ + public function revenue(Period $period): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return (int) $this->payments($period)->sum(DB::raw($this->net())); + }); + } + + /** @return list */ + public function revenueSeries(Period $period): array + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return $period->series($this->paidPayments(), "sum({$this->net()})"); + }); + } + + /** Refunded so far on payments made in the period (refunds keep no date of their own). */ + public function refunds(Period $period): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return (int) $this->payments($period)->sum('amount_refunded'); + }); + } + + public function failedPayments(Period $period): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return Payment::where('status', PaymentStatus::Failed) + ->whereBetween('created_at', [$period->start, $period->end]) + ->count(); + }); + } + + /** @return array plan name ('' for payments without one) => net revenue, largest first */ + public function revenueByPlan(Period $period): array + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return $this->payments($period) + ->leftJoin('prices', 'prices.id', '=', 'payments.price_id') + ->leftJoin('products', 'products.id', '=', 'prices.product_id') + ->selectRaw('products.name as plan, sum(payments.amount - payments.amount_refunded) as total') + ->groupBy('products.name') + ->orderByDesc('total') + ->toBase() + ->get() + ->mapWithKeys(fn (object $row): array => [(string) $row->plan => (int) $row->total]) + ->all(); + }); + } + + public function mrrAt(DateTimeInterface $at): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($at) { + $monthly = "case prices.interval when 'day' then prices.amount * 365.0 / 12 when 'week' then prices.amount * 52.0 / 12 when 'year' then prices.amount / 12.0 else prices.amount * 1.0 end / coalesce(prices.interval_count, 1)"; + + return (int) round((float) $this->activeQuery($at) + ->join('prices', 'prices.id', '=', 'subscriptions.price_id') + ->whereNotNull('prices.interval') + ->where('prices.currency', $this->currency()) + ->sum(DB::raw($monthly))); + }); + } + + /** Average monthly revenue per subscription, both in the default currency; 0 with none. */ + public function arpuAt(DateTimeInterface $at): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($at) { + $count = $this->activeQuery($at) + ->join('prices', 'prices.id', '=', 'subscriptions.price_id') + ->whereNotNull('prices.interval') + ->where('prices.currency', $this->currency()) + ->count(); + + return $count ? intdiv($this->mrrAt($at), $count) : 0; + }); + } + + public function activeAt(DateTimeInterface $at): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($at) { + return $this->activeQuery($at)->count(); + }); + } + + public function newSubscriptions(Period $period): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return Subscription::whereBetween('created_at', [$period->start, $period->end])->count(); + }); + } + + /** @return list */ + public function newSubscriptionsSeries(Period $period): array + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return $period->series(Subscription::query()); + }); + } + + public function cancelled(Period $period): int + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + return Subscription::whereBetween('cancelled_at', [$period->start, $period->end])->count(); + }); + } + + /** Cancelled in the period, as a share of those active when it started; null with none active. */ + public function churnRate(Period $period): ?float + { + $active = $this->activeAt($period->start); + + return $active === 0 ? null : round($this->cancelled($period) / $active * 100, 1); + } + + /** Waiting on a payment right now. Not cached: the attention widget must be current, and it's one indexed count. */ + public function pastDue(): int + { + return Subscription::where('status', SubscriptionStatus::PastDue)->count(); + } + + /** Completed checkouts out of those that finished (pending ones are still open); null with none. */ + public function conversionRate(Period $period): ?float + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + $row = $this->finishedCheckouts() + ->whereBetween('created_at', [$period->start, $period->end]) + ->selectRaw("{$this->completed()} as completed, count(*) as total") + ->toBase() + ->first(); + + return (int) $row?->total === 0 ? null : round($row->completed / $row->total * 100, 1); + }); + } + + /** @return list */ + public function conversionSeries(Period $period): array + { + return $this->remember(__FUNCTION__, func_get_args(), function () use ($period) { + $completed = $period->series($this->finishedCheckouts(), $this->completed()); + $total = $period->series($this->finishedCheckouts()); + + return array_map(fn ($done, $all) => $all ? round($done / $all * 100, 1) : 0, $completed, $total); + }); + } + + /** + * Each widget loads in its own request, so answers are also cached for a few minutes + * (fresh for 5, then served while they refresh, up to 10) for the next widget and visit. + */ + private function remember(string $method, array $arguments, \Closure $compute): mixed + { + $key = 'billing:metrics:'.$method.':'.$this->currency()->value.':'.implode(',', array_map( + fn (mixed $argument): string => match (true) { + $argument instanceof Period => $argument->start->toDateTimeString().'..'.$argument->end->toDateTimeString(), + $argument instanceof DateTimeInterface => $argument->format('Y-m-d H:i:s'), + default => (string) $argument, + }, + $arguments, + )); + + if (! array_key_exists($key, $this->answered)) { + $this->answered[$key] = Cache::flexible($key, [300, 600], $compute); + } + + return $this->answered[$key]; + } + + /** Read once: it's a settings lookup. */ + private function currency(): Currency + { + return $this->currency ??= Currency::default(); + } + + /** @return Builder */ + private function payments(Period $period): Builder + { + return $this->paidPayments()->whereBetween('payments.created_at', [$period->start, $period->end]); + } + + /** Succeeded and refunded payments: a refund lowers revenue by what it gave back. */ + private function paidPayments(): Builder + { + return Payment::query() + ->whereIn('payments.status', [PaymentStatus::Succeeded, PaymentStatus::Refunded]) + ->where('payments.currency', $this->currency()); + } + + private function net(): string + { + return 'payments.amount - payments.amount_refunded'; + } + + /** + * Started by `$at` and not yet ended. Pending never started. A suspension ends it at + * `grace_ends_at`, which suspending always sets. Without its own date, a suspended or + * cancelled one ended by its last update (`updated_at`), never "still running". + */ + private function activeQuery(DateTimeInterface $at): Builder + { + $suspended = SubscriptionStatus::Suspended->value; + $cancelled = SubscriptionStatus::Cancelled->value; + $endedAt = "coalesce(subscriptions.ends_at, subscriptions.cancelled_at, case subscriptions.status when '{$suspended}' then coalesce(subscriptions.grace_ends_at, subscriptions.updated_at) when '{$cancelled}' then subscriptions.updated_at end)"; + + return Subscription::query() + ->where('subscriptions.status', '!=', SubscriptionStatus::Pending) + ->where('subscriptions.created_at', '<=', $at) + ->where(fn (Builder $query) => $query + ->whereRaw("{$endedAt} is null") + ->orWhereRaw("{$endedAt} > ?", [$at])); + } + + private function finishedCheckouts(): Builder + { + return CheckoutSession::whereIn('status', [CheckoutSessionStatus::Completed, CheckoutSessionStatus::Abandoned, CheckoutSessionStatus::Expired]); + } + + private function completed(): string + { + return "sum(case when status = '".CheckoutSessionStatus::Completed->value."' then 1 else 0 end)"; + } +} diff --git a/src/Traits/Billable.php b/src/Traits/Billable.php index f0a63bc..8ee3257 100644 --- a/src/Traits/Billable.php +++ b/src/Traits/Billable.php @@ -5,6 +5,7 @@ use App\Models\User; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Relations\MorphOne; +use Modules\Billing\Actions\CancelSubscription; use Modules\Billing\Data\Entitlements; use Modules\Billing\Enums\PlanKind; use Modules\Billing\Models\Customer; @@ -29,11 +30,23 @@ trait Billable public static function bootBillable(): void { static::deleted(function (self $owner): void { + // Nobody is left to cancel it, and a deleted owner can't reach billing. Queued so + // an unreachable provider retries instead of failing the delete. A soft delete + // cancels too: restoring keeps paying to the period end, and Resume undoes it. + $subscription = $owner->billingAccount()?->currentSubscription(); + if ($subscription && ! $subscription->cancelled_at) { + dispatch(fn () => app(CancelSubscription::class) + ->handle($subscription)) + ->afterCommit(); + } + if (method_exists($owner, 'isForceDeleting') && ! $owner->isForceDeleting()) { return; } - $owner->billingCustomer()->getQuery()->update(['owner_type' => null, 'owner_id' => null]); + $owner->billingCustomer() + ->getQuery() + ->update(['owner_type' => null, 'owner_id' => null]); }); } diff --git a/tests/Feature/BillingHistorySurvivesTest.php b/tests/Feature/BillingHistorySurvivesTest.php index 7705eb0..7372f6e 100644 --- a/tests/Feature/BillingHistorySurvivesTest.php +++ b/tests/Feature/BillingHistorySurvivesTest.php @@ -3,6 +3,7 @@ namespace Modules\Billing\Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Queue; use Modules\Billing\Models\Customer; use Modules\Billing\Models\Invoice; use Modules\Billing\Models\Payment; @@ -16,6 +17,7 @@ class BillingHistorySurvivesTest extends TestCase /** What was charged has to stay answerable after the account is gone. */ public function test_deleting_a_user_detaches_the_customer_and_keeps_the_history(): void { + Queue::fake(); // The cancel it queues is OwnerDeletionCancelsTest's. $user = $this->createUser(); $customer = Customer::factory()->for($user, 'owner')->create(); $subscription = Subscription::factory()->create(['customer_id' => $customer->id]); diff --git a/tests/Feature/BillingMetricsTest.php b/tests/Feature/BillingMetricsTest.php new file mode 100644 index 0000000..ecfbb84 --- /dev/null +++ b/tests/Feature/BillingMetricsTest.php @@ -0,0 +1,192 @@ +metrics = new BillingMetrics; + $this->week = Period::fromFilters(['period' => '7d']); // Oct 31 – Nov 6 + } + + private function subscription(Price $price, string $createdAt, array $attributes = []): Subscription + { + $subscription = Subscription::factory()->create(['price_id' => $price->id, ...$attributes]); + $subscription->forceFill(['created_at' => $createdAt])->save(); + + return $subscription; + } + + public function test_revenue_is_net_of_refunds_and_in_the_default_currency(): void + { + Payment::factory()->create(['amount' => 1000, 'created_at' => '2026-11-01']); + Payment::factory()->partiallyRefunded()->create(['amount' => 1000, 'amount_refunded' => 500, 'created_at' => '2026-11-02']); + Payment::factory()->refunded()->create(['amount' => 1000, 'amount_refunded' => 1000, 'created_at' => '2026-11-03']); + Payment::factory()->failed()->create(['amount' => 1000, 'created_at' => '2026-11-03']); + Payment::factory()->create(['amount' => 1000, 'currency' => 'BRL', 'created_at' => '2026-11-03']); + Payment::factory()->create(['amount' => 1000, 'created_at' => '2026-10-01']); // outside + + $this->assertSame(1500, $this->metrics->revenue($this->week)); + $this->assertSame(1500, $this->metrics->refunds($this->week)); + $this->assertSame(1500, array_sum($this->metrics->revenueSeries($this->week))); + $this->assertSame(1, $this->metrics->failedPayments($this->week)); + } + + public function test_mrr_turns_each_interval_into_a_monthly_amount(): void + { + $this->subscription(Price::factory()->create(['amount' => 1000, 'interval' => 'month']), '2026-01-01'); + $this->subscription(Price::factory()->create(['amount' => 12000, 'interval' => 'year']), '2026-01-01'); + $this->subscription(Price::factory()->create(['amount' => 3000, 'interval' => 'month', 'interval_count' => 3]), '2026-01-01'); + $this->subscription(Price::factory()->create(['amount' => 1000, 'interval' => 'month', 'currency' => 'BRL']), '2026-01-01'); + + $this->assertSame(3000, $this->metrics->mrrAt(now())); + } + + /** History is estimated from when each subscription started and ended. */ + public function test_mrr_and_active_subscriptions_at_a_past_date(): void + { + $price = Price::factory()->create(['amount' => 1000, 'interval' => 'month']); + $this->subscription($price, '2026-01-01'); + $this->subscription($price, '2026-11-02'); // started since + $this->subscription($price, '2026-01-01', ['status' => 'cancelled', 'cancelled_at' => '2026-11-01', 'ends_at' => '2026-11-03']); + $this->subscription($price, '2026-01-01', ['status' => 'pending']); + + $start = $this->week->start; + + $this->assertSame(2000, $this->metrics->mrrAt($start)); + $this->assertSame(2, $this->metrics->activeAt($start)); + $this->assertSame(2000, $this->metrics->mrrAt(now())); + $this->assertSame(2, $this->metrics->activeAt(now())); + } + + /** MRR is in the default currency, so the count it's divided by is too. */ + public function test_arpu_divides_by_subscriptions_in_the_same_currency(): void + { + $this->subscription(Price::factory()->create(['amount' => 1000, 'interval' => 'month']), '2026-01-01'); + $this->subscription(Price::factory()->create(['amount' => 1000, 'interval' => 'month', 'currency' => 'BRL']), '2026-01-01'); + + $this->assertSame(1000, $this->metrics->arpuAt(now())); + $this->assertSame(0, $this->metrics->arpuAt(Carbon::parse('2025-01-01'))); + } + + /** Suspension records when it happened (`grace_ends_at`): before that, the subscription counted. */ + public function test_a_suspended_subscription_counts_until_it_was_suspended(): void + { + $price = Price::factory()->create(['amount' => 1000, 'interval' => 'month']); + $this->subscription($price, '2026-01-01', ['status' => 'suspended', 'grace_ends_at' => '2026-11-02 12:00:00']); + + $this->assertSame(1, $this->metrics->activeAt(Carbon::parse('2026-11-01'))); + $this->assertSame(1000, $this->metrics->mrrAt(Carbon::parse('2026-11-01'))); + $this->assertSame(0, $this->metrics->activeAt(now())); + } + + /** A provider can report Cancelled with no dates: it ended by its last update, not never. */ + public function test_a_cancelled_subscription_without_dates_ends_at_its_last_update(): void + { + $subscription = $this->subscription(Price::factory()->create(['amount' => 1000, 'interval' => 'month']), '2026-01-01', ['status' => 'cancelled']); + $subscription->forceFill(['updated_at' => '2026-11-02 12:00:00'])->saveQuietly(); + + $this->assertSame(1, $this->metrics->activeAt(Carbon::parse('2026-11-01'))); + $this->assertSame(0, $this->metrics->activeAt(now())); + } + + public function test_churn_is_cancellations_over_subscriptions_active_at_the_start(): void + { + $price = Price::factory()->create(['interval' => 'month']); + foreach (range(1, 3) as $i) { + $this->subscription($price, '2026-01-01'); + } + $this->subscription($price, '2026-01-01', ['status' => 'cancelled', 'cancelled_at' => '2026-11-01', 'ends_at' => '2026-12-01']); + + $this->assertSame(1, $this->metrics->cancelled($this->week)); + $this->assertSame(25.0, $this->metrics->churnRate($this->week)); + $this->assertNull($this->metrics->churnRate(Period::fromFilters(['period' => 'custom', 'start' => '2025-01-01', 'end' => '2025-01-07']))); + } + + public function test_new_subscriptions_and_past_due(): void + { + $price = Price::factory()->create(['interval' => 'month']); + $this->subscription($price, '2026-11-05'); + $this->subscription($price, '2026-11-05', ['status' => 'past_due']); + $this->subscription($price, '2026-01-01'); + + $this->assertSame(2, $this->metrics->newSubscriptions($this->week)); + $this->assertSame(2, array_sum($this->metrics->newSubscriptionsSeries($this->week))); + $this->assertSame(1, $this->metrics->pastDue()); + } + + public function test_conversion_counts_finished_checkouts_only(): void + { + $price = Price::factory()->create(); + foreach ([CheckoutSessionStatus::Completed, CheckoutSessionStatus::Abandoned, CheckoutSessionStatus::Expired, CheckoutSessionStatus::Pending] as $status) { + CheckoutSession::create(['price_id' => $price->id, 'status' => $status, 'expires_at' => now()]) + ->forceFill(['created_at' => '2026-11-04'])->save(); + } + + $this->assertSame(33.3, $this->metrics->conversionRate($this->week)); + $this->assertNull($this->metrics->conversionRate($this->week->previous())); + $this->assertSame([0, 0, 0, 0, 33.3, 0, 0], $this->metrics->conversionSeries($this->week)); + } + + public function test_revenue_by_plan(): void + { + $price = Price::factory()->create(); + Payment::factory()->create(['amount' => 700, 'price_id' => $price->id, 'created_at' => '2026-11-01']); + Payment::factory()->create(['amount' => 300, 'created_at' => '2026-11-01']); + + // No translated text in the cache: the widget names the '' bucket in the reader's language. + $this->assertSame([$price->product->name => 700, '' => 300], $this->metrics->revenueByPlan($this->week)); + } + + /** Two cards asking the same thing cost one query. */ + public function test_the_same_figure_is_worked_out_once(): void + { + $this->metrics->mrrAt($this->week->start); + + DB::enableQueryLog(); + $this->metrics->mrrAt($this->week->start); + Cache::flush(); // the instance remembers, not only the cache + $this->metrics->mrrAt($this->week->start); + + $this->assertCount(0, DB::getQueryLog()); + } + + /** Every widget is its own request: the figures are cached a few minutes, so the next one reads them. */ + public function test_figures_are_cached_for_a_few_minutes(): void + { + Payment::factory()->create(['amount' => 1000, 'amount_refunded' => 0, 'created_at' => '2026-11-05']); + $first = (new BillingMetrics)->revenue($this->week); + + Payment::factory()->create(['amount' => 500, 'amount_refunded' => 0, 'created_at' => '2026-11-05']); + $cached = (new BillingMetrics)->revenue($this->week); + + $this->travel(11)->minutes(); + $expired = (new BillingMetrics)->revenue($this->week); + + $this->assertSame([1000, 1000, 1500], [$first, $cached, $expired]); + } +} diff --git a/tests/Feature/BillingPermissionTest.php b/tests/Feature/BillingPermissionTest.php index 78faf67..1709bc0 100644 --- a/tests/Feature/BillingPermissionTest.php +++ b/tests/Feature/BillingPermissionTest.php @@ -11,8 +11,10 @@ use Modules\Billing\Filament\Resources\Customers\CustomerResource; use Modules\Billing\Filament\Resources\Products\ProductResource; use Modules\Billing\Filament\Resources\Subscriptions\SubscriptionResource; +use Modules\Billing\Filament\Widgets\BillingHealthWidget; use Modules\Billing\Filament\Widgets\BillingSaasStatsWidget; use Modules\Billing\Filament\Widgets\ConversionChartWidget; +use Modules\Billing\Filament\Widgets\RevenueByPlanChartWidget; use Modules\Billing\Filament\Widgets\RevenueChartWidget; use Modules\Billing\Filament\Widgets\SubscriptionsChartWidget; use PHPUnit\Framework\Attributes\DataProvider; @@ -79,6 +81,8 @@ public static function widgets(): array 'revenue' => [RevenueChartWidget::class], 'subscriptions' => [SubscriptionsChartWidget::class], 'conversion' => [ConversionChartWidget::class], + 'health' => [BillingHealthWidget::class], + 'revenue by plan' => [RevenueByPlanChartWidget::class], ]; } diff --git a/tests/Feature/DashboardIndexesTest.php b/tests/Feature/DashboardIndexesTest.php new file mode 100644 index 0000000..6619ec8 --- /dev/null +++ b/tests/Feature/DashboardIndexesTest.php @@ -0,0 +1,32 @@ +}> */ + public static function indexes(): array + { + return [ + 'payments by status, currency and date' => ['payments', ['status', 'currency', 'created_at']], + 'subscriptions by date' => ['subscriptions', ['created_at']], + 'subscriptions by cancellation' => ['subscriptions', ['cancelled_at']], + 'checkouts by status and date' => ['checkout_sessions', ['status', 'created_at']], + ]; + } + + /** @param list $columns */ + #[DataProvider('indexes')] + public function test_the_dashboard_queries_are_indexed(string $table, array $columns): void + { + $this->assertContains($columns, array_column(Schema::getIndexes($table), 'columns')); + } +} diff --git a/tests/Feature/DashboardWidgetsTest.php b/tests/Feature/DashboardWidgetsTest.php index 6c9f10a..5aa94ce 100644 --- a/tests/Feature/DashboardWidgetsTest.php +++ b/tests/Feature/DashboardWidgetsTest.php @@ -2,107 +2,122 @@ namespace Modules\Billing\Tests\Feature; -use Filament\Widgets\StatsOverviewWidget\Stat; +use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Exceptions; -use Modules\Billing\Enums\CheckoutSessionStatus; -use Modules\Billing\Enums\PaymentStatus; +use Livewire\Livewire; +use Modules\Billing\Filament\Pages\BillingDashboard; +use Modules\Billing\Filament\Widgets\BillingAttentionWidget; +use Modules\Billing\Filament\Widgets\BillingHealthWidget; use Modules\Billing\Filament\Widgets\BillingSaasStatsWidget; use Modules\Billing\Filament\Widgets\ConversionChartWidget; +use Modules\Billing\Filament\Widgets\RevenueByPlanChartWidget; use Modules\Billing\Filament\Widgets\RevenueChartWidget; use Modules\Billing\Filament\Widgets\SubscriptionsChartWidget; -use Modules\Billing\Models\CheckoutSession; use Modules\Billing\Models\Payment; -use Modules\Billing\Models\Price; +use Modules\Billing\Models\Product; use Modules\Billing\Models\Subscription; use Tests\TestCase; /** - * The admin dashboard's numbers, on whichever database the app runs: the - * queries group by month and count matches in SQL, which each engine spells - * differently. A widget that fails reports it and shows an empty chart, so - * the tests also check nothing was reported. + * The cards and charts read the period from the dashboard's picker; the + * numbers themselves are BillingMetricsTest's. */ class DashboardWidgetsTest extends TestCase { use RefreshDatabase; + private const WEEK = ['pageFilters' => ['period' => '7d']]; + protected function setUp(): void { parent::setUp(); Exceptions::fake(); - $this->travelTo('2026-03-15 12:00:00'); + Carbon::setTestNow('2026-11-06 15:00:00'); + $admin = User::factory()->create(); + $admin->assignRole('admin'); + $this->actingAs($admin); } - /** - * @template T of object - * - * @param class-string $widget - * @return T - */ - private function widget(string $widget): object + public function test_the_billing_dashboard_has_the_period_picker_and_its_widgets(): void { - return tap(new $widget, function (object $widget): void { - $widget->startDate = '2026-01-01 00:00:00'; - $widget->endDate = '2026-03-31 23:59:59'; - }); + Livewire::test(BillingDashboard::class) + ->assertOk() + ->assertActionExists('filter'); + + $this->assertSame([ + BillingSaasStatsWidget::class, + BillingHealthWidget::class, + RevenueChartWidget::class, + SubscriptionsChartWidget::class, + ConversionChartWidget::class, + RevenueByPlanChartWidget::class, + ], (new BillingDashboard)->getWidgets()); } - /** @return list */ - private function chart(object $widget): array + public function test_the_headline_cards_compare_with_the_previous_period(): void { - return (fn () => $this->getData())->call($widget)['datasets'][0]['data']; + Product::factory()->create(); + Payment::factory()->create(['amount' => 3000, 'amount_refunded' => 0, 'created_at' => '2026-11-05']); + Payment::factory()->create(['amount' => 1000, 'amount_refunded' => 0, 'created_at' => '2026-10-28']); + + Livewire::test(BillingSaasStatsWidget::class, self::WEEK) + ->assertSee(['Revenue', '+200% vs previous period', 'MRR', 'New subscriptions']); + Exceptions::assertNothingReported(); } - private function checkout(CheckoutSessionStatus $status, string $at): void + /** A new install has no plans: one pointer to set billing up, not a row of zeros. */ + public function test_without_plans_the_headline_says_how_to_start(): void { - CheckoutSession::create(['price_id' => Price::factory()->create()->id, 'status' => $status, 'expires_at' => now()]) - ->forceFill(['created_at' => $at])->save(); + Livewire::test(BillingSaasStatsWidget::class, self::WEEK) + ->assertSee('Set up billing') + ->assertDontSee('MRR'); } - public function test_revenue_is_summed_per_month(): void + public function test_the_health_cards(): void { - Payment::factory()->create(['status' => PaymentStatus::Succeeded, 'amount' => 1000, 'created_at' => '2026-01-10']); - Payment::factory()->create(['status' => PaymentStatus::Succeeded, 'amount' => 500, 'created_at' => '2026-01-20']); - Payment::factory()->create(['status' => PaymentStatus::Succeeded, 'amount' => 700, 'created_at' => '2026-03-02']); - Payment::factory()->create(['status' => PaymentStatus::Failed, 'amount' => 9999, 'created_at' => '2026-03-03']); + Subscription::factory()->create(); - $this->assertSame([1500, 0, 700], $this->chart($this->widget(RevenueChartWidget::class))); + Livewire::test(BillingHealthWidget::class, self::WEEK) + ->assertSee(['Active subscriptions', 'Churn', 'ARPU', 'Checkout conversion', 'Refunds', 'Failed payments']); Exceptions::assertNothingReported(); } - public function test_new_subscriptions_are_counted_per_month(): void + public function test_charts_follow_the_period(): void { - Subscription::factory()->create(['created_at' => '2026-02-01']); - Subscription::factory()->create(['created_at' => '2026-02-28']); - Subscription::factory()->create(['created_at' => '2026-03-01']); + Payment::factory()->create(['amount' => 700, 'amount_refunded' => 0, 'created_at' => '2026-11-05']); + + foreach ([RevenueChartWidget::class, SubscriptionsChartWidget::class, ConversionChartWidget::class, RevenueByPlanChartWidget::class] as $chart) { + Livewire::test($chart, self::WEEK)->assertOk(); + } - $this->assertSame([0, 2, 1], $this->chart($this->widget(SubscriptionsChartWidget::class))); + $data = (fn () => $this->getData())->call(tap(new RevenueChartWidget, fn ($w) => $w->pageFilters = self::WEEK['pageFilters'])); + $this->assertCount(7, $data['labels']); + $this->assertSame(7.0, $data['datasets'][0]['data'][5]); // shown in major units Exceptions::assertNothingReported(); } - public function test_checkout_conversion_is_worked_out_per_month(): void + /** Shown only when something needs an admin. */ + public function test_attention_shows_only_with_something_to_do(): void { - $this->checkout(CheckoutSessionStatus::Completed, '2026-01-05'); - $this->checkout(CheckoutSessionStatus::Abandoned, '2026-01-06'); - $this->checkout(CheckoutSessionStatus::Completed, '2026-03-07'); - $this->checkout(CheckoutSessionStatus::Pending, '2026-03-08'); + $this->assertFalse(BillingAttentionWidget::canView()); - $this->assertSame([50.0, 0.0, 100.0], $this->chart($this->widget(ConversionChartWidget::class))); - Exceptions::assertNothingReported(); + Subscription::factory()->pastDue()->create(); + Payment::factory()->failed()->create(); + + $this->assertTrue(BillingAttentionWidget::canView()); + Livewire::test(BillingAttentionWidget::class)->assertSee(['Past due subscriptions', 'Failed payments']); } - public function test_the_overall_conversion_rate_counts_completed_checkouts(): void + /** A zero isn't something to attend to. */ + public function test_attention_lists_only_what_needs_doing(): void { - $this->checkout(CheckoutSessionStatus::Completed, '2026-01-05'); - $this->checkout(CheckoutSessionStatus::Expired, '2026-02-06'); - $this->checkout(CheckoutSessionStatus::Abandoned, '2026-03-06'); - $this->checkout(CheckoutSessionStatus::Completed, '2026-03-07'); - - /** @var list $stats */ - $stats = (fn () => $this->getStats())->call($this->widget(BillingSaasStatsWidget::class)); + Subscription::factory()->pastDue()->create(); - $this->assertSame('50%', $stats[3]->getValue()); + Livewire::test(BillingAttentionWidget::class) + ->assertSee('Past due subscriptions') + ->assertDontSee('Failed payments'); } } diff --git a/tests/Feature/EntitlementCatalogueTest.php b/tests/Feature/EntitlementCatalogueTest.php new file mode 100644 index 0000000..58973e3 --- /dev/null +++ b/tests/Feature/EntitlementCatalogueTest.php @@ -0,0 +1,118 @@ +create(); + $admin->assignRole('admin'); + $this->actingAs($admin); + + Capabilities::add('billing', [ + 'packages:acme/reports' => ['label' => 'Package: Reports'], + 'seats' => ['label' => 'Seats', 'type' => 'limit'], + ]); + } + + public function test_the_key_is_picked_by_label(): void + { + $this->assertSame('Package: Reports', ProductForm::entitlementLabel('packages:acme/reports')); + $this->assertArrayHasKey('packages:acme/reports', ProductForm::entitlementSearch('report')); + $this->assertSame('Package: Reports', ProductForm::entitlementSearch('report')['packages:acme/reports']); + } + + /** What is typed can be used as it is, for a key the catalogue doesn't list. */ + public function test_a_key_the_catalogue_does_not_list_can_still_be_typed(): void + { + $this->assertArrayHasKey('max_projects', ProductForm::entitlementSearch('max_projects')); + $this->assertSame('max_projects', ProductForm::entitlementLabel('max_projects')); + } + + /** Typing a catalogue label must not offer a second "Seats" that is only the typed text. */ + public function test_the_typed_option_reads_differently_from_a_catalogue_match(): void + { + $options = ProductForm::entitlementSearch('Seats'); + + $this->assertSame('Seats', $options['seats']); + $this->assertSame('Use the key "Seats"', $options['Seats']); + } + + /** The catalogue says what a key is: picking a feature after a limit must not keep Limit. */ + public function test_picking_a_key_sets_its_type_both_ways(): void + { + $plan = Product::factory()->create(['kind' => PlanKind::OneOff]); + $page = Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->fillForm(['entitlements' => [['key' => 'seats', 'type' => 'feature']]]); + $row = array_key_first($page->get('data.entitlements')); + + $page->set("data.entitlements.{$row}.key", 'seats') + ->assertSet("data.entitlements.{$row}.type", 'limit') + ->set("data.entitlements.{$row}.limit", 30) + ->set("data.entitlements.{$row}.key", 'packages:acme/reports') + ->assertSet("data.entitlements.{$row}.type", 'feature') + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertTrue($plan->fresh()->entitlements()->allows('packages:acme/reports')); + } + + public function test_a_one_off_plan_can_include_a_package(): void + { + $plan = Product::factory()->create(['kind' => PlanKind::OneOff]); + + Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->fillForm(['entitlements' => [['key' => 'packages:acme/reports', 'type' => 'feature']]]) + ->call('save') + ->assertHasNoFormErrors() + ->assertNotNotified(__('Not in the catalogue: :keys', ['keys' => 'packages:acme/reports'])); + + $this->assertTrue($plan->fresh()->entitlements()->allows('packages:acme/reports')); + } + + /** Existing keys load and save as they were, and an unknown one warns without blocking. */ + public function test_an_unknown_key_saves_with_a_warning(): void + { + $plan = Product::factory()->create(['entitlements' => ['features' => ['legacy_flag' => true], 'limits' => []]]); + + Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->call('save') + ->assertHasNoFormErrors() + ->assertNotified(__('Not in the catalogue: :keys', ['keys' => 'legacy_flag'])); + + $this->assertSame(['features' => ['legacy_flag' => true], 'limits' => []], $plan->fresh()->entitlements); + } + + /** The warning says "Saved": a listener rolling the save back must not leave it behind. */ + public function test_a_rolled_back_save_sends_no_warning(): void + { + $plan = Product::factory()->create(['entitlements' => ['features' => ['legacy_flag' => true], 'limits' => []]]); + Event::listen(RecordSaved::class, fn () => throw (new Halt)->rollBackDatabaseTransaction()); + + Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->call('save') + ->assertNotNotified(__('Not in the catalogue: :keys', ['keys' => 'legacy_flag'])); + } +} diff --git a/tests/Feature/OwnerDeletionCancelsTest.php b/tests/Feature/OwnerDeletionCancelsTest.php new file mode 100644 index 0000000..c0fd87f --- /dev/null +++ b/tests/Feature/OwnerDeletionCancelsTest.php @@ -0,0 +1,99 @@ +gateway = $this->createMock(PaymentGatewayInterface::class); + $manager = $this->createStub(PaymentGatewayManager::class); + $manager->method('driver')->willReturn($this->gateway); + app()->instance(PaymentGatewayManager::class, $manager); + } + + private function subscribedUser(array $attributes = []): array + { + $user = $this->createUser(); + $customer = Customer::factory()->for($user, 'owner')->create(); + $subscription = Subscription::factory()->create([ + 'customer_id' => $customer->id, + 'status' => SubscriptionStatus::Active, + ...$attributes, + ]); + + return [$user, $subscription]; + } + + public function test_deleting_the_owner_cancels_its_subscription(): void + { + [$user, $subscription] = $this->subscribedUser(); + $this->gateway->expects($this->once())->method('cancelSubscription'); + + $user->delete(); + + $this->assertNotNull($subscription->fresh()->cancelled_at); + } + + /** Queued: a provider outage retries the cancel instead of failing the delete. */ + public function test_the_cancel_is_queued(): void + { + Queue::fake(); + [$user, $subscription] = $this->subscribedUser(); + + $user->delete(); + + Queue::assertPushed(CallQueuedClosure::class); + $this->assertModelMissing($user); + $this->assertNull($subscription->fresh()->cancelled_at); + } + + public function test_a_subscription_already_cancelled_is_left_alone(): void + { + [$user] = $this->subscribedUser(['cancelled_at' => now()]); + $this->gateway->expects($this->never())->method('cancelSubscription'); + + $user->delete(); + } + + public function test_an_ended_subscription_is_left_alone(): void + { + [$user] = $this->subscribedUser(['status' => SubscriptionStatus::Cancelled]); + $this->gateway->expects($this->never())->method('cancelSubscription'); + + $user->delete(); + } + + public function test_an_owner_without_billing_deletes_as_before(): void + { + $user = $this->createUser(); + $this->gateway->expects($this->never())->method('cancelSubscription'); + + $user->delete(); + + $this->assertModelMissing($user); + } +} diff --git a/tests/Feature/PlanKindExplainedTest.php b/tests/Feature/PlanKindExplainedTest.php new file mode 100644 index 0000000..074ecab --- /dev/null +++ b/tests/Feature/PlanKindExplainedTest.php @@ -0,0 +1,105 @@ +create(); + $admin->assignRole('admin'); + $this->actingAs($admin); + } + + /** @return array */ + public static function kinds(): array + { + return array_combine( + array_map(fn (PlanKind $kind) => $kind->value, PlanKind::cases()), + array_map(fn (PlanKind $kind) => [$kind], PlanKind::cases()), + ); + } + + #[DataProvider('kinds')] + public function test_the_form_explains_the_selected_kind(PlanKind $kind): void + { + $page = Livewire::test(CreateProduct::class)->set('data.kind', $kind); + + $page->assertSee($kind->description()); + foreach (PlanKind::cases() as $other) { + if ($other !== $kind) { + $page->assertDontSee($other->description()); + } + } + } + + public function test_a_sold_plan_says_it_is_fixed_and_still_explains_its_kind(): void + { + $plan = Product::factory()->create(['kind' => PlanKind::Subscription]); + Subscription::factory()->create(['price_id' => Price::factory()->for($plan)->create()->id]); + + Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->assertSee('Fixed: this plan has been sold.') + ->assertSee(PlanKind::Subscription->description()); + } + + #[DataProvider('kinds')] + public function test_the_view_page_explains_the_kind(PlanKind $kind): void + { + $plan = Product::factory()->create(['kind' => $kind]); + + Livewire::test(ViewProduct::class, ['record' => $plan->getKey()]) + ->assertSee($kind->description()); + } + + /** What it is, gives and costs comes before the plan's IDs. */ + public function test_the_view_page_puts_kind_entitlements_and_prices_before_the_details(): void + { + $plan = Product::factory()->create([ + 'kind' => PlanKind::Subscription, + 'sku' => 'SKU-ORDER-CHECK', + 'entitlements' => ['features' => ['exports' => true], 'limits' => []], + ]); + Price::factory()->for($plan)->create(); + + Livewire::test(ViewProduct::class, ['record' => $plan->getKey()]) + ->assertSeeInOrder([PlanKind::Subscription->description(), 'exports: On', 'Price', 'SKU-ORDER-CHECK']); + } + + public function test_a_one_off_plan_without_entitlements_shows_no_empty_line(): void + { + $plan = Product::factory()->create(['kind' => PlanKind::OneOff, 'entitlements' => null]); + + Livewire::test(ViewProduct::class, ['record' => $plan->getKey()]) + ->assertDontSee('No entitlements'); + } + + public function test_a_one_off_plan_with_entitlements_lists_them(): void + { + $plan = Product::factory()->create([ + 'kind' => PlanKind::OneOff, + 'entitlements' => ['features' => ['packages:acme/widgets' => true], 'limits' => []], + ]); + + Livewire::test(ViewProduct::class, ['record' => $plan->getKey()]) + ->assertSee('packages:acme/widgets: On'); + } +} diff --git a/tests/Feature/ProductFormLayoutTest.php b/tests/Feature/ProductFormLayoutTest.php index 0faafcb..a69bfcc 100644 --- a/tests/Feature/ProductFormLayoutTest.php +++ b/tests/Feature/ProductFormLayoutTest.php @@ -56,6 +56,16 @@ public function test_a_plan_is_created_through_the_wizard(): void $this->assertTrue($plan->entitlements()->allows('export data')); } + /** A new price row is empty until filled: deciding whether it can be deleted mustn't validate it. */ + public function test_adding_a_price_row_does_not_validate_it(): void + { + Livewire::test(CreateProduct::class) + ->set('data.prices', ['new-row' => ['amount' => null, 'currency' => null]]) + ->goToWizardStep(3) + ->assertOk() + ->assertHasNoFormErrors(); + } + public function test_a_plan_with_a_price_opens_for_editing(): void { $plan = Product::factory()->create(); @@ -132,13 +142,13 @@ public function test_the_view_page_shows_prices_in_their_currency(): void } /** Keys the modules offer are suggested; anything else can still be typed. */ - public function test_entitlement_keys_suggest_the_billing_capabilities(): void + /** Picking is by label from the catalogue (EntitlementCatalogueTest); a key outside it still saves. */ + public function test_a_key_outside_the_billing_capabilities_still_saves(): void { app(Capabilities::class)->add('billing', fn (): array => ['webhooks' => ['label' => 'Webhooks']]); $plan = Product::factory()->create(['entitlements' => ['features' => ['custom key' => true]]]); Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) - ->assertSeeHtml('value="webhooks"') ->call('save') ->assertHasNoFormErrors();