diff --git a/README.md b/README.md index aeb6dfc..2fc326c 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-rea - **Stripe checkout**, straight to Stripe or through your own checkout page - **Subscriptions** that cancel at period end and can be resumed - **Customer portal** for cards, invoices and plan changes -- **Free trials**, one per customer, with or without a card up front +- **Free trials**, one per customer, with or without a card up front, optionally with their own entitlements (fewer API requests, a feature off) - **Grace period** after a failed payment, with emails at each step - **Plan kinds**: free, subscription, lifetime and one-off - **Entitlements**: each plan turns features on and sets limits your app checks diff --git a/database/migrations/1000_00_00_000001_create_products_table.php b/database/migrations/1000_00_00_000001_create_products_table.php index 140183e..3540556 100644 --- a/database/migrations/1000_00_00_000001_create_products_table.php +++ b/database/migrations/1000_00_00_000001_create_products_table.php @@ -27,6 +27,7 @@ public function up(): void // What buying it gives, and what it grants: see PlanKind and Entitlements $table->string('kind')->default('subscription'); $table->json('entitlements')->nullable(); + $table->json('trial_entitlements')->nullable(); // Days of free trial this plan offers, once per customer. $table->unsignedSmallInteger('trial_days')->nullable(); diff --git a/database/seeders/DemoProductSeeder.php b/database/seeders/DemoProductSeeder.php index a59d59e..3440cdf 100644 --- a/database/seeders/DemoProductSeeder.php +++ b/database/seeders/DemoProductSeeder.php @@ -50,6 +50,7 @@ public function run(): void 'metadata' => $plan['metadata'], 'kind' => $plan['kind'], 'entitlements' => $plan['entitlements'], + 'trial_entitlements' => $plan['trial_entitlements'] ?? null, 'replaces_product_id' => isset($plan['replaces']) ? Product::where('slug', $plan['replaces'])->value('id') : null, @@ -72,7 +73,7 @@ public function run(): void } /** - * @return list, replaces?: string, description: string, features: list, metadata: array, prices: list}>}> + * @return list, trial_entitlements?: array, replaces?: string, description: string, features: list, metadata: array, prices: list}>}> */ private function plans(): array { @@ -100,6 +101,7 @@ private function plans(): array 'kind' => PlanKind::Subscription, 'trial_days' => 14, 'entitlements' => self::PRO_ENTITLEMENTS, + 'trial_entitlements' => ['features' => ['custom_domains' => false], 'limits' => ['api_requests' => 10000]], 'description' => 'No limits on projects, and the tools to run them in production.', 'features' => ['Unlimited projects', '1M API requests / month', 'Custom domains', 'Webhooks', 'Priority email support'], 'metadata' => [ diff --git a/resources/boost/skills/saucebase-billing-development/SKILL.md b/resources/boost/skills/saucebase-billing-development/SKILL.md index 0bcee59..0858db9 100644 --- a/resources/boost/skills/saucebase-billing-development/SKILL.md +++ b/resources/boost/skills/saucebase-billing-development/SKILL.md @@ -123,6 +123,8 @@ A `Product` is a plan, and its `slug` is the plan's stable ID in code. Every pla 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. +**Trial entitlements.** A Subscription plan with `trial_days` may carry `trial_entitlements`, same shape except a feature may be `false`. While `Subscription::onTrial()` (`trial_ends_at` in the future), `Product::entitlements(trial: true)` (what `Billable` asks for) is the plan's with them applied by `Entitlements::override()`: listed features switch on or off, listed limits replace, the rest is the plan's. Empty means the trial gets the plan. `Billable` passes `trial: $subscription->onTrial()` for the subscription's plan only, so a trial only narrows its own plan: Free and owned lifetime plans still count in full. Access switches when the trial ends, computed per request with no event. The admin shows a second repeater (with *Feature off*) once a trial is set. + **Invariants, enforced in `Product::assertValid()` on every save** (admin, catalog import, code): - 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. diff --git a/resources/js/react/components/PlanFeatures.tsx b/resources/js/react/components/PlanFeatures.tsx index b8f29c8..b3d46d6 100644 --- a/resources/js/react/components/PlanFeatures.tsx +++ b/resources/js/react/components/PlanFeatures.tsx @@ -1,7 +1,8 @@ import { useTranslation } from '@saucebase/react/i18n'; import { Check } from 'lucide-react'; +import { useState } from 'react'; -/** A plan's marketing features, as on its pricing card: the first few, then a count. */ +/** A plan's marketing features, with an expandable preview. */ export default function PlanFeatures({ features, limit = 3, @@ -10,6 +11,8 @@ export default function PlanFeatures({ limit?: number; }) { const { t } = useTranslation(); + const [expanded, setExpanded] = useState(false); + const visibleFeatures = expanded ? features : features.slice(0, limit); if (!features.length) { return null; @@ -17,7 +20,7 @@ export default function PlanFeatures({ return (
    - {features.slice(0, limit).map((feature) => ( + {visibleFeatures.map((feature) => (
  • {feature} @@ -25,9 +28,19 @@ export default function PlanFeatures({ ))} {features.length > limit && (
  • - {t('+:count more', { - count: String(features.length - limit), - })} +
  • )}
diff --git a/resources/js/vue/components/PlanFeatures.vue b/resources/js/vue/components/PlanFeatures.vue index f0b38d0..9ea725e 100644 --- a/resources/js/vue/components/PlanFeatures.vue +++ b/resources/js/vue/components/PlanFeatures.vue @@ -1,19 +1,24 @@ diff --git a/src/Data/Entitlements.php b/src/Data/Entitlements.php index bedad95..478f5f9 100644 --- a/src/Data/Entitlements.php +++ b/src/Data/Entitlements.php @@ -52,6 +52,27 @@ public function merge(self $other): self return new self($this->features + $other->features, $limits); } + /** + * This plan as a trial sees it: each listed feature switched on or off, each + * listed limit replaced. Anything not listed stays as the plan has it. + * + * @param array{features?: array, limits?: array}|null $override + */ + public function override(?array $override): self + { + $features = $this->features; + + foreach ($override['features'] ?? [] as $key => $on) { + if ($on) { + $features[$key] = true; + } else { + unset($features[$key]); + } + } + + return new self($features, array_replace($this->limits, $override['limits'] ?? [])); + } + public function allows(string $feature): bool { return isset($this->features[$feature]); diff --git a/src/Filament/Resources/Products/Pages/EditProduct.php b/src/Filament/Resources/Products/Pages/EditProduct.php index 578bea8..c0bee21 100644 --- a/src/Filament/Resources/Products/Pages/EditProduct.php +++ b/src/Filament/Resources/Products/Pages/EditProduct.php @@ -30,7 +30,11 @@ class EditProduct extends EditRecord */ protected function mutateFormDataBeforeFill(array $data): array { - return [...$data, 'entitlements' => ProductForm::entitlementRows($data['entitlements'] ?? null)]; + return [ + ...$data, + 'entitlements' => ProductForm::entitlementRows($data['entitlements'] ?? null), + 'trial_entitlements' => ProductForm::entitlementRows($data['trial_entitlements'] ?? null), + ]; } /** diff --git a/src/Filament/Resources/Products/Schemas/ProductForm.php b/src/Filament/Resources/Products/Schemas/ProductForm.php index 2e4f758..a134a8f 100644 --- a/src/Filament/Resources/Products/Schemas/ProductForm.php +++ b/src/Filament/Resources/Products/Schemas/ProductForm.php @@ -56,8 +56,8 @@ public static function entitlementRows(?array $stored): array { $rows = []; - foreach (array_keys($stored['features'] ?? []) as $key) { - $rows[] = ['key' => $key, 'type' => 'feature']; + foreach ($stored['features'] ?? [] as $key => $on) { + $rows[] = ['key' => $key, 'type' => $on ? 'feature' : 'off']; } foreach ($stored['limits'] ?? [] as $key => $limit) { @@ -71,7 +71,7 @@ public static function entitlementRows(?array $stored): array * The form's rows back in the stored shape; an empty list stores nothing. * * @param array|null $rows - * @return array{features: array, limits: array}|null + * @return array{features: array, limits: array}|null */ private static function storedEntitlements(?array $rows): ?array { @@ -81,13 +81,61 @@ private static function storedEntitlements(?array $rows): ?array if (($row['type'] ?? null) === 'limit') { $stored['limits'][$row['key']] = ($row['unlimited'] ?? false) ? null : (int) $row['limit']; } else { - $stored['features'][$row['key']] = true; + $stored['features'][$row['key']] = ($row['type'] ?? null) !== 'off'; } } return $stored === ['features' => [], 'limits' => []] ? null : $stored; } + /** + * One row per entitlement. A trial's rows may also switch a feature off. + */ + private static function entitlementsRepeater(string $name, bool $trial = false): Repeater + { + return Repeater::make($name) + ->schema([ + TextInput::make('key') + ->label(__('Key')) + ->required() + ->regex('/^\S(.*\S)?$/u') + ->maxLength(255) + ->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'))), + Select::make('type') + ->label(__('Type')) + ->options($trial + ? ['feature' => __('Feature on'), 'off' => __('Feature off'), 'limit' => __('Limit')] + : ['feature' => __('Feature'), 'limit' => __('Limit')]) + ->default('feature') + ->required() + ->live(), + Toggle::make('unlimited') + ->label(__('Unlimited')) + ->live() + ->visible(fn (Get $get) => $get('type') === 'limit'), + TextInput::make('limit') + ->label(__('Limit')) + ->integer() + ->minValue(0) + ->required(fn (Get $get) => $get('type') === 'limit' && ! $get('unlimited')) + ->visible(fn (Get $get) => $get('type') === 'limit' && ! $get('unlimited')), + ]) + ->table([ + TableColumn::make(__('Key')), + TableColumn::make(__('Type')), + TableColumn::make(__('Unlimited')), + TableColumn::make(__('Limit')), + ]) + ->defaultItems(0) + ->addActionLabel(__('Add entitlement')) + // Replaces the repeater's own mutation, which would turn the + // stored shape back into a list of rows. + ->mutateDehydratedStateUsing(fn (?array $state) => self::storedEntitlements($state)); + } + /** * The edit form: the four groups as tabs, so one change doesn't mean * scrolling the whole plan. `CreateProduct` walks the same groups as a wizard. @@ -189,50 +237,19 @@ private static function groups(): array ->integer() ->minValue(1) ->maxValue(730) + // Trial entitlements only show once a plan has trial days. + ->live(onBlur: true) ->visible(fn (Get $get) => self::kindIs($get('kind'), PlanKind::Subscription)) ->helperText(__('Each customer gets one trial, ever. Whether payment details are collected first is a billing setting.')), - Repeater::make('entitlements') + self::entitlementsRepeater('entitlements') ->label(__('Entitlements')) - ->helperText(__('Features the plan turns on and limits the app enforces. Changes apply to existing customers straight away.')) - ->schema([ - TextInput::make('key') - ->label(__('Key')) - ->required() - ->regex('/^\S(.*\S)?$/u') - ->maxLength(255) - ->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'))), - Select::make('type') - ->label(__('Type')) - ->options(['feature' => __('Feature'), 'limit' => __('Limit')]) - ->default('feature') - ->required() - ->live(), - Toggle::make('unlimited') - ->label(__('Unlimited')) - ->live() - ->visible(fn (Get $get) => $get('type') === 'limit'), - TextInput::make('limit') - ->label(__('Limit')) - ->integer() - ->minValue(0) - ->required(fn (Get $get) => $get('type') === 'limit' && ! $get('unlimited')) - ->visible(fn (Get $get) => $get('type') === 'limit' && ! $get('unlimited')), - ]) - ->table([ - TableColumn::make(__('Key')), - TableColumn::make(__('Type')), - TableColumn::make(__('Unlimited')), - TableColumn::make(__('Limit')), - ]) - ->defaultItems(0) - ->addActionLabel(__('Add entitlement')) - // Replaces the repeater's own mutation, which would turn the - // stored shape back into a list of rows. - ->mutateDehydratedStateUsing(fn (?array $state) => self::storedEntitlements($state)), + ->helperText(__('Features the plan turns on and limits the app enforces. Changes apply to existing customers straight away.')), + + self::entitlementsRepeater('trial_entitlements', trial: true) + ->label(__('Trial entitlements')) + ->helperText(__('What changes during the free trial: switch features on or off, or set other limits. Anything not listed is the plan\'s. Changes apply to current trials straight away.')) + ->visible(fn (Get $get) => self::kindIs($get('kind'), PlanKind::Subscription) && filled($get('trial_days'))), ]), ]], diff --git a/src/Filament/Resources/Products/Schemas/ProductInfolist.php b/src/Filament/Resources/Products/Schemas/ProductInfolist.php index 784c910..2837199 100644 --- a/src/Filament/Resources/Products/Schemas/ProductInfolist.php +++ b/src/Filament/Resources/Products/Schemas/ProductInfolist.php @@ -16,21 +16,24 @@ class ProductInfolist { /** - * One line per entitlement, features first: `exports: On`, - * `projects: Unlimited`, `api_requests: 1,000,000`. + * One line per entitlement, features first: `exports: On`, `webhooks: Off` + * (trials only), `projects: Unlimited`, `api_requests: 1,000,000`. * + * @param array{features?: array, limits?: array}|null $stored * @return list */ - private static function entitlementLines(Product $record): array + private static function entitlementLines(?array $stored): array { - $entitlements = $record->entitlements()->toArray(); - return [ - ...array_map(fn (string $key) => $key.': '.__('On'), array_keys($entitlements['features'])), + ...array_map( + fn (string $key, bool $on) => $key.': '.($on ? __('On') : __('Off')), + array_keys($stored['features'] ?? []), + $stored['features'] ?? [], + ), ...array_map( fn (string $key, ?int $limit) => $key.': '.($limit === null ? __('Unlimited') : number_format($limit)), - array_keys($entitlements['limits']), - $entitlements['limits'], + array_keys($stored['limits'] ?? []), + $stored['limits'] ?? [], ), ]; } @@ -96,11 +99,19 @@ public static function configure(Schema $schema): Schema TextEntry::make('entitlement_list') ->label(__('Entitlements')) - ->state(fn (Product $record) => self::entitlementLines($record)) + ->state(fn (Product $record) => self::entitlementLines($record->entitlements()->toArray())) ->listWithLineBreaks() ->bulleted() ->placeholder(__('No entitlements')) ->columnSpanFull(), + + TextEntry::make('trial_entitlement_list') + ->label(__('Trial entitlements')) + ->state(fn (Product $record) => self::entitlementLines($record->trial_entitlements)) + ->listWithLineBreaks() + ->bulleted() + ->visible(fn (Product $record) => $record->trial_days !== null && filled($record->trial_entitlements)) + ->columnSpanFull(), ]) ->columns(3), diff --git a/src/Models/Product.php b/src/Models/Product.php index 631ac48..fb6776b 100644 --- a/src/Models/Product.php +++ b/src/Models/Product.php @@ -32,6 +32,7 @@ * @property bool $is_active * @property PlanKind $kind * @property array|null $entitlements + * @property array{features?: array, limits?: array}|null $trial_entitlements * @property int|null $trial_days * @property int|null $replaces_product_id * @property Carbon|null $created_at @@ -91,6 +92,7 @@ protected static function booted(): void 'is_active', 'kind', 'entitlements', + 'trial_entitlements', 'trial_days', 'replaces_product_id', ]; @@ -115,6 +117,7 @@ protected function casts(): array 'deleted_at' => 'datetime', 'kind' => PlanKind::class, 'entitlements' => 'array', + 'trial_entitlements' => 'array', 'trial_days' => 'integer', ]; } @@ -163,12 +166,14 @@ public function scopeDisplayable(Builder $query): Builder ->with(['prices' => fn ($prices) => $prices->where('is_active', true)]); } - public function entitlements(): Entitlements + /** What the plan grants; during a free trial, with `trial_entitlements` on top. */ + public function entitlements(bool $trial = false): Entitlements { /** @var array{features?: array, limits?: array}|null $stored */ $stored = $this->entitlements; + $entitlements = Entitlements::fromArray($stored); - return Entitlements::fromArray($stored); + return $trial ? $entitlements->override($this->trial_entitlements) : $entitlements; } /** @@ -220,28 +225,38 @@ private function assertValid(): void 'trial_days' => ['nullable', 'integer', 'min:1', 'max:730'], ])->validate(); - Validator::make(['entitlements' => $this->entitlements ?? []], [ - 'entitlements' => ['array:features,limits'], - 'entitlements.features' => ['array'], - 'entitlements.features.*' => ['accepted'], - 'entitlements.limits' => ['array'], - 'entitlements.limits.*' => ['nullable', 'integer', 'min:0'], - ])->after(function ($validator): void { + // A trial's override may also switch a feature off; a plan only lists what it turns on. + $this->assertValidEntitlements('entitlements', 'accepted'); + $this->assertValidEntitlements('trial_entitlements', 'boolean'); + + if ($this->exists && $this->isDirty(self::LOCKED_WHEN_SOLD) && $this->isSold()) { + throw ValidationException::withMessages([ + 'kind' => __('This plan has been sold, so its kind, slug and replacement are fixed. Create a new plan instead.'), + ]); + } + } + + /** @throws ValidationException */ + private function assertValidEntitlements(string $attribute, string $featureRule): void + { + $stored = $this->{$attribute} ?? []; + + Validator::make([$attribute => $stored], [ + $attribute => ['array:features,limits'], + "{$attribute}.features" => ['array'], + "{$attribute}.features.*" => [$featureRule], + "{$attribute}.limits" => ['array'], + "{$attribute}.limits.*" => ['nullable', 'integer', 'min:0'], + ])->after(function ($validator) use ($attribute, $stored): void { foreach (['features', 'limits'] as $group) { // The shape rules above report anything that is not a list. - foreach (array_keys((array) ($this->entitlements[$group] ?? [])) as $key) { + foreach (array_keys((array) ($stored[$group] ?? [])) as $key) { if (strlen((string) $key) > 255 || ! preg_match('/^\S(.*\S)?$/u', (string) $key)) { - $validator->errors()->add('entitlements', __('Entitlement keys can\'t start or end with a space.')); + $validator->errors()->add($attribute, __('Entitlement keys can\'t start or end with a space.')); } } } })->validate(); - - if ($this->exists && $this->isDirty(self::LOCKED_WHEN_SOLD) && $this->isSold()) { - throw ValidationException::withMessages([ - 'kind' => __('This plan has been sold, so its kind, slug and replacement are fixed. Create a new plan instead.'), - ]); - } } /** diff --git a/src/Models/Subscription.php b/src/Models/Subscription.php index 69f888f..f2f749f 100644 --- a/src/Models/Subscription.php +++ b/src/Models/Subscription.php @@ -115,6 +115,11 @@ public function grantsAccess(): bool }; } + public function onTrial(): bool + { + return $this->trial_ends_at?->isFuture() ?? false; + } + /** * @return BelongsTo */ diff --git a/src/Traits/Billable.php b/src/Traits/Billable.php index f66f8d0..f0a63bc 100644 --- a/src/Traits/Billable.php +++ b/src/Traits/Billable.php @@ -60,10 +60,10 @@ public function billingAccount(): ?Customer public function entitlements(): Entitlements { $entitlements = Product::where('kind', PlanKind::Free)->first()?->entitlements() ?? Entitlements::none(); - $subscribed = $this->accessGrantingSubscription()?->price?->plan; + $subscription = $this->accessGrantingSubscription(); - if ($subscribed) { - $entitlements = $entitlements->merge($subscribed->entitlements()); + if ($subscription?->price?->plan) { + $entitlements = $entitlements->merge($subscription->price->plan->entitlements(trial: $subscription->onTrial())); } foreach ($this->heldLifetimePurchases() as $purchase) { diff --git a/tests/Feature/DemoSeederTest.php b/tests/Feature/DemoSeederTest.php index 934b5f6..1066274 100644 --- a/tests/Feature/DemoSeederTest.php +++ b/tests/Feature/DemoSeederTest.php @@ -5,10 +5,12 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Modules\Billing\Database\Seeders\DatabaseSeeder; use Modules\Billing\Database\Seeders\DemoBillingDatabaseSeeder; +use Modules\Billing\Database\Seeders\DemoProductSeeder; use Modules\Billing\Enums\SubscriptionStatus; use Modules\Billing\Models\Customer; use Modules\Billing\Models\Invoice; use Modules\Billing\Models\Payment; +use Modules\Billing\Models\Product; use Modules\Billing\Models\Subscription; use Tests\TestCase; @@ -41,4 +43,16 @@ public function test_seeding_twice_leaves_the_same_data(): void $this->assertSame($first, [Customer::count(), Subscription::count(), Payment::count()]); } + + /** Pro's trial shows the feature: fewer API requests, no custom domains. */ + public function test_the_pro_trial_is_narrower_than_pro(): void + { + $this->seed(DemoProductSeeder::class); + + $trial = Product::where('slug', 'pro')->sole()->entitlements(trial: true); + + $this->assertFalse($trial->allows('custom_domains')); + $this->assertTrue($trial->allows('webhooks')); + $this->assertSame(10000, $trial->limit('api_requests')); + } } diff --git a/tests/Feature/EntitlementResolutionTest.php b/tests/Feature/EntitlementResolutionTest.php index aa5bffc..d59f96a 100644 --- a/tests/Feature/EntitlementResolutionTest.php +++ b/tests/Feature/EntitlementResolutionTest.php @@ -188,4 +188,35 @@ public function test_a_current_subscription_is_a_paid_plan(): void $this->assertTrue($this->user->hasPaidPlan()); } + + /** A trial gets the plan with its trial entitlements on top; afterwards, the plan. */ + public function test_a_trial_gets_the_plans_trial_entitlements(): void + { + $plan = Product::factory()->create([ + 'entitlements' => ['features' => ['exports' => true, 'webhooks' => true], 'limits' => ['api_requests' => 1000000]], + 'trial_entitlements' => ['features' => ['webhooks' => false], 'limits' => ['api_requests' => 1000]], + ]); + $subscription = $this->subscribeTo($plan, attributes: ['trial_starts_at' => now()->subDay(), 'trial_ends_at' => now()->addDays(13)]); + + $this->assertTrue($this->user->canUseFeature('exports')); + $this->assertFalse($this->user->canUseFeature('webhooks')); + $this->assertSame(1000, $this->user->planLimit('api_requests')); + + $subscription->update(['trial_ends_at' => now()->subMinute()]); + + $this->assertTrue($this->user->fresh()->canUseFeature('webhooks')); + $this->assertSame(1000000, $this->user->fresh()->planLimit('api_requests')); + } + + /** What else the owner holds still counts in full: a trial only narrows its own plan. */ + public function test_a_trial_never_takes_away_what_another_plan_grants(): void + { + $this->buy(Product::factory()->lifetime()->create(['entitlements' => ['features' => ['webhooks' => true]]])); + $this->subscribeTo( + Product::factory()->create(['entitlements' => ['features' => ['webhooks' => true]], 'trial_entitlements' => ['features' => ['webhooks' => false]]]), + attributes: ['trial_starts_at' => now(), 'trial_ends_at' => now()->addDays(7)], + ); + + $this->assertTrue($this->user->canUseFeature('webhooks')); + } } diff --git a/tests/Feature/PlanAdminTest.php b/tests/Feature/PlanAdminTest.php index 33dca18..70a124e 100644 --- a/tests/Feature/PlanAdminTest.php +++ b/tests/Feature/PlanAdminTest.php @@ -104,4 +104,26 @@ public function test_an_entitlement_key_has_no_edge_spaces(): void $this->assertNull($plan->fresh()->entitlements); } + + /** Trial rows can also switch a feature off; they load back as they were saved. */ + public function test_trial_entitlements_are_edited_like_entitlements(): void + { + $plan = Product::factory()->create(['trial_days' => 14]); + + Livewire::test(EditProduct::class, ['record' => $plan->getKey()]) + ->fillForm(['trial_entitlements' => [ + ['key' => 'webhooks', 'type' => 'off'], + ['key' => 'api_requests', 'type' => 'limit', 'unlimited' => false, 'limit' => 1000], + ]]) + ->call('save') + ->assertHasNoFormErrors(); + + $stored = ['features' => ['webhooks' => false], 'limits' => ['api_requests' => 1000]]; + $this->assertSame($stored, $plan->fresh()->trial_entitlements); + + $page = Livewire::test(EditProduct::class, ['record' => $plan->getKey()]); + $this->assertSame(['off', 'limit'], array_column(array_values($page->get('data.trial_entitlements')), 'type')); + $page->call('save')->assertHasNoFormErrors(); + $this->assertSame($stored, $plan->fresh()->trial_entitlements); + } } diff --git a/tests/Feature/PlanRulesTest.php b/tests/Feature/PlanRulesTest.php index 714e04f..1d97712 100644 --- a/tests/Feature/PlanRulesTest.php +++ b/tests/Feature/PlanRulesTest.php @@ -167,4 +167,19 @@ public function test_a_plan_may_have_no_trial(): void { $this->assertNull(Product::factory()->create(['trial_days' => null])->trial_days); } + + /** Trial entitlements may switch a feature off, which plan entitlements never store. */ + public function test_trial_entitlements_may_turn_a_feature_off(): void + { + $plan = Product::factory()->create(['trial_entitlements' => ['features' => ['exports' => false], 'limits' => ['projects' => 1]]]); + + $this->assertSame(['features' => ['exports' => false], 'limits' => ['projects' => 1]], $plan->fresh()->trial_entitlements); + } + + public function test_trial_entitlements_follow_the_same_key_and_limit_rules(): void + { + $this->expectException(ValidationException::class); + + Product::factory()->create(['trial_entitlements' => ['limits' => [' projects' => -1]]]); + } } diff --git a/tests/Unit/EntitlementsTest.php b/tests/Unit/EntitlementsTest.php index db2a0c0..1dedccb 100644 --- a/tests/Unit/EntitlementsTest.php +++ b/tests/Unit/EntitlementsTest.php @@ -64,4 +64,26 @@ public function test_it_says_whether_a_limit_is_set_at_all(): void $this->assertFalse($entitlements->declares('seats')); $this->assertFalse(Entitlements::none()->declares('members')); } + + /** A trial's override: listed features switch on or off, listed limits replace; the rest is the plan's. */ + public function test_an_override_changes_only_what_it_lists(): void + { + $plan = Entitlements::fromArray(['features' => ['exports' => true, 'sso' => true], 'limits' => ['projects' => null, 'seats' => 5]]); + + $trial = $plan->override(['features' => ['sso' => false, 'beta' => true], 'limits' => ['projects' => 3]]); + + $this->assertTrue($trial->allows('exports')); + $this->assertFalse($trial->allows('sso')); + $this->assertTrue($trial->allows('beta')); + $this->assertSame(3, $trial->limit('projects')); + $this->assertSame(5, $trial->limit('seats')); + } + + public function test_an_empty_override_changes_nothing(): void + { + $plan = Entitlements::fromArray(['features' => ['exports' => true], 'limits' => ['projects' => 3]]); + + $this->assertSame($plan->toArray(), $plan->override(null)->toArray()); + $this->assertSame($plan->toArray(), $plan->override([])->toArray()); + } } diff --git a/tests/e2e/tests/settings-billing/settings-billing.lifetime.spec.ts b/tests/e2e/tests/settings-billing/settings-billing.lifetime.spec.ts index a98ceac..5d50aad 100644 --- a/tests/e2e/tests/settings-billing/settings-billing.lifetime.spec.ts +++ b/tests/e2e/tests/settings-billing/settings-billing.lifetime.spec.ts @@ -31,6 +31,16 @@ test.describe('Settings Billing Lifetime', () => { await expect(plan).toContainText('Bought on'); await expect(plan).toContainText('Unlimited projects'); await expect(plan).toContainText('+1 more'); + await expect(plan).not.toContainText('Priority support'); + + const featuresToggle = plan.getByTestId('plan-features-toggle'); + await expect(featuresToggle).toHaveAttribute('aria-expanded', 'false'); + await featuresToggle.click(); + await expect(plan).toContainText('Priority support'); + await expect(featuresToggle).toHaveAttribute('aria-expanded', 'true'); + await featuresToggle.press('Enter'); + await expect(plan).not.toContainText('Priority support'); + await expect(featuresToggle).toHaveAttribute('aria-expanded', 'false'); // One purchase: the card says it all, so no table repeats it. await expect(page.getByTestId('payments')).toHaveCount(0);