Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Comment thread
roble marked this conversation as resolved.
Resolved

// Days of free trial this plan offers, once per customer.
$table->unsignedSmallInteger('trial_days')->nullable();
Expand Down
4 changes: 3 additions & 1 deletion database/seeders/DemoProductSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
'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,
Expand All @@ -72,7 +73,7 @@
}

/**
* @return list<array{slug: string, name: string, kind: PlanKind, trial_days?: int, entitlements: array<string, mixed>, replaces?: string, description: string, features: list<string>, metadata: array<string, string>, prices: list<array{interval: ?string, amount: int, metadata?: array<string, string>}>}>
* @return list<array{slug: string, name: string, kind: PlanKind, trial_days?: int, entitlements: array<string, mixed>, trial_entitlements?: array<string, mixed>, replaces?: string, description: string, features: list<string>, metadata: array<string, string>, prices: list<array{interval: ?string, amount: int, metadata?: array<string, string>}>}>

Check warning on line 76 in database/seeders/DemoProductSeeder.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 351 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_billing&issues=AaGjCJ0NPcG4IqagdESF&open=AaGjCJ0NPcG4IqagdESF&pullRequest=37
*/
private function plans(): array
{
Expand Down Expand Up @@ -100,6 +101,7 @@
'kind' => PlanKind::Subscription,
'trial_days' => 14,
'entitlements' => self::PRO_ENTITLEMENTS,
'trial_entitlements' => ['features' => ['custom_domains' => false], 'limits' => ['api_requests' => 10000]],

Check warning on line 104 in database/seeders/DemoProductSeeder.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 123 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_billing&issues=AaGjCJ0NPcG4IqagdESG&open=AaGjCJ0NPcG4IqagdESG&pullRequest=37
'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' => [
Expand Down
2 changes: 2 additions & 0 deletions resources/boost/skills/saucebase-billing-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 18 additions & 5 deletions resources/js/react/components/PlanFeatures.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -10,24 +11,36 @@ 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;
}

return (
<ul className="text-muted-foreground space-y-1 text-sm">
{features.slice(0, limit).map((feature) => (
{visibleFeatures.map((feature) => (
<li key={feature} className="flex items-center gap-2">
<Check className="text-primary size-4 shrink-0" />
{feature}
</li>
))}
{features.length > limit && (
<li className="pl-6">
{t('+:count more', {
count: String(features.length - limit),
})}
<button
type="button"
aria-expanded={expanded}
data-testid="plan-features-toggle"
className="hover:text-foreground cursor-pointer hover:underline"
onClick={() => setExpanded(!expanded)}
>
{expanded
? t('Show less')
: t('+:count more', {
count: String(features.length - limit),
})}
</button>
</li>
)}
</ul>
Expand Down
29 changes: 22 additions & 7 deletions resources/js/vue/components/PlanFeatures.vue
Original file line number Diff line number Diff line change
@@ -1,31 +1,46 @@
<script setup lang="ts">
import { Check } from '@lucide/vue';
import { computed, ref } from 'vue';

/** 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. */
const props = withDefaults(
defineProps<{ features: string[]; limit?: number }>(),
{
limit: 3,
},
);
const expanded = ref(false);
const visibleFeatures = computed(() =>
expanded.value ? props.features : props.features.slice(0, props.limit),
);
</script>

<template>
<ul v-if="features.length" class="text-muted-foreground space-y-1 text-sm">
<li
v-for="feature in features.slice(0, props.limit)"
v-for="feature in visibleFeatures"
:key="feature"
class="flex items-center gap-2"
>
<Check class="text-primary size-4 shrink-0" />
{{ feature }}
</li>
<li v-if="features.length > props.limit" class="pl-6">
{{
$t('+:count more', {
count: String(features.length - props.limit),
})
}}
<button
type="button"
:aria-expanded="expanded"
data-testid="plan-features-toggle"
class="hover:text-foreground cursor-pointer hover:underline"
@click="expanded = !expanded"
>
{{
expanded
? $t('Show less')
: $t('+:count more', {
count: String(features.length - props.limit),
})
}}
</button>
</li>
</ul>
</template>
21 changes: 21 additions & 0 deletions src/Data/Entitlements.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, bool>, limits?: array<string, int|null>}|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]);
Expand Down
6 changes: 5 additions & 1 deletion src/Filament/Resources/Products/Pages/EditProduct.php
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
}

/**
Expand Down
105 changes: 61 additions & 44 deletions src/Filament/Resources/Products/Schemas/ProductForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@
{
$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) {
Expand All @@ -71,7 +71,7 @@
* The form's rows back in the stored shape; an empty list stores nothing.
*
* @param array<array-key, array{key?: string, type?: string, unlimited?: bool, limit?: int|string|null}>|null $rows
* @return array{features: array<string, true>, limits: array<string, int|null>}|null
* @return array{features: array<string, bool>, limits: array<string, int|null>}|null
*/
private static function storedEntitlements(?array $rows): ?array
{
Expand All @@ -81,13 +81,61 @@
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.
Expand Down Expand Up @@ -189,50 +237,19 @@
->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.')),

Check warning on line 247 in src/Filament/Resources/Products/Schemas/ProductForm.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 155 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_billing&issues=AaGjCJ4PPcG4IqagdESH&open=AaGjCJ4PPcG4IqagdESH&pullRequest=37

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.'))

Check warning on line 251 in src/Filament/Resources/Products/Schemas/ProductForm.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 214 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_billing&issues=AaGjCJ4PPcG4IqagdESI&open=AaGjCJ4PPcG4IqagdESI&pullRequest=37
->visible(fn (Get $get) => self::kindIs($get('kind'), PlanKind::Subscription) && filled($get('trial_days'))),

Check warning on line 252 in src/Filament/Resources/Products/Schemas/ProductForm.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 137 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_billing&issues=AaGjCJ4PPcG4IqagdESJ&open=AaGjCJ4PPcG4IqagdESJ&pullRequest=37
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
]),

]],
Expand Down
Loading
Loading