added pricing, orgs
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-04 20:34:19 -07:00
parent 999d5ad28d
commit 2ca3860557
52 changed files with 3467 additions and 47 deletions
+25
View File
@@ -4,8 +4,10 @@ namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
@@ -22,6 +24,7 @@ class CreateNewUser implements CreatesNewUsers
Validator::make($input, [
...$this->profileRules(),
'password' => $this->passwordRules(),
...$this->planRules(),
])->validate();
return User::create([
@@ -30,4 +33,26 @@ class CreateNewUser implements CreatesNewUsers
'password' => $input['password'],
]);
}
/**
* Get the validation rules for the chosen plan.
*
* The plan is only required when there is something configured to buy. This
* keeps registration working on a deployment that has not set a Stripe
* price yet, which would otherwise leave nobody able to create an account.
*
* @return array<string, array<int, mixed>>
*/
protected function planRules(): array
{
$plans = array_keys(Organization::availablePlans());
if ($plans === []) {
return [];
}
return [
'plan' => ['required', Rule::in($plans)],
];
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureSubscribed
{
/**
* Send users without an active subscription to the pricing page, where
* they can subscribe. Reads the local subscription rows only, so it does
* not call Stripe on every request.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->user()?->hasActiveSubscription() === true) {
return $next($request);
}
return redirect()->route('pricing');
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Responses;
use App\Models\Organization;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Laravel\Fortify\Fortify;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Sends a new account straight into checkout for the plan it signed up with.
*
* Fortify's default response redirects to the home route, which the
* "subscribed" middleware would then bounce to the pricing page. Reading the
* plan off the registration request keeps the account details and the plan
* choice in a single submission, so the user never sees an interstitial.
*/
class RegisterResponse implements RegisterResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* The signature is left untyped to stay compatible with Responsable, which
* declares the parameter without a type.
*
* @param Request $request
*/
public function toResponse($request): Response
{
if ($request->wantsJson()) {
return new JsonResponse('', 201);
}
$plan = $request->input('plan');
// A plan is only required when at least one is configured. Without a
// Stripe price there is nothing to sell, so registration still succeeds
// and the pricing page explains that no plans are available rather than
// making the application impossible to sign up for.
if (! is_string($plan) || ! Organization::isAvailablePlan($plan)) {
return $this->defaultRedirect($request);
}
$organization = $request->user()?->currentOrganization()->first();
if ($organization === null) {
return $this->defaultRedirect($request);
}
try {
return $organization->checkoutForPlan($plan)->redirect();
} catch (Throwable $e) {
// The account already exists by this point, so a Stripe outage must
// not turn a completed signup into an error page. Report it and fall
// back to the pricing page, where checkout can be retried.
report($e);
$request->session()->flash(
'billing.checkout_failed',
__('Your account was created, but we could not start checkout. Please try again to finish subscribing.'),
);
return redirect()->route('pricing');
}
}
/**
* Send the new account to the home route, as Fortify does by default.
*/
protected function defaultRedirect(Request $request): RedirectResponse
{
return redirect()->intended(Fortify::redirects('register'));
}
}
+273
View File
@@ -0,0 +1,273 @@
<?php
namespace App\Models;
use App\OrganizationRole;
use Database\Factories\OrganizationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Number;
use Laravel\Cashier\Billable;
use Laravel\Cashier\Checkout;
use Laravel\Cashier\Subscription;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* An organization owns the subscription and is the Stripe customer. Every user
* is given a personal organization when their account is created; group and
* company organizations are created later, which is why the model is not named
* after a person.
*
* @property int $id
* @property string $name
* @property bool $personal_workspace
* @property bool $lifetime_access
* @property string|null $stripe_id
* @property string|null $pm_type
* @property string|null $pm_last_four
* @property Carbon|null $trial_ends_at
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'personal_workspace', 'lifetime_access'])]
#[Hidden(['stripe_id'])]
class Organization extends Model
{
/** @use HasFactory<OrganizationFactory> */
use Billable, HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'personal_workspace' => 'boolean',
'lifetime_access' => 'boolean',
'trial_ends_at' => 'datetime',
];
}
/**
* @return BelongsToMany<User, $this>
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('role')
->withTimestamps();
}
/**
* Get the subscription type that Cashier stores this organization's
* subscriptions under.
*/
public function subscriptionType(): string
{
$type = config('plans.subscription_type');
return is_string($type) ? $type : 'default';
}
/**
* Get the organization's subscription, if it has one.
*/
public function currentSubscription(): ?Subscription
{
return $this->subscription($this->subscriptionType());
}
/**
* Determine whether the organization has perpetual access and therefore
* never needs to subscribe. Set for accounts that predate subscriptions.
*/
public function hasLifetimeAccess(): bool
{
return $this->lifetime_access;
}
/**
* Determine whether the organization may use the application, either
* because it has an active subscription, is trialing, is within a
* cancellation grace period, or was grandfathered in.
*
* This reads the local subscription rows, so it never calls Stripe.
*/
public function isEntitled(): bool
{
return $this->hasLifetimeAccess() || $this->subscribed($this->subscriptionType());
}
/**
* Get the plan the organization is currently subscribed to.
*
* @return array{name: string, price: string, interval: string, amount: int}|null
*/
public function currentPlan(): ?array
{
$price = $this->currentSubscription()?->stripe_price;
if ($price === null) {
return null;
}
foreach ($this->availablePlans() as $plan) {
if ($plan['price'] === $price) {
return $plan;
}
}
return null;
}
/**
* Get the plans that are ready to be sold, that is, the ones with a Stripe
* price configured.
*
* The amount is what the plan is advertised at on the pricing and signup
* pages. It lives in the settings table rather than the configuration
* because an administrator can change it, while the Stripe price id it is
* sold against cannot be swapped once subscribers exist.
*
* @return array<string, array{name: string, price: string, interval: string, amount: int}>
*/
public static function availablePlans(): array
{
$plans = config('plans.plans');
if (! is_array($plans)) {
return [];
}
$available = [];
foreach ($plans as $key => $plan) {
$price = is_array($plan) ? ($plan['price'] ?? null) : null;
if (is_string($price) && $price !== '') {
$available[$key] = [
'name' => is_string($plan['name'] ?? null) ? $plan['name'] : (string) $key,
'price' => $price,
'interval' => is_string($plan['interval'] ?? null) ? $plan['interval'] : 'month',
'amount' => static::planAmount((string) $key),
];
}
}
return $available;
}
/**
* Get the amount, in minor units, that the given plan is advertised at.
*/
public static function planAmount(string $key): int
{
return Setting::amount(Setting::planAmountKey($key), static::defaultPlanAmount());
}
/**
* Get the amount a plan falls back to when it has no stored amount, which
* is the conventional price for a single-product plan.
*/
protected static function defaultPlanAmount(): int
{
return 1000;
}
/**
* Format an amount, in minor units, as a price for display.
*/
public static function formatAmount(int $amount): string
{
$value = $amount / 100;
$formatted = Number::currency($value, in: config('cashier.currency'));
if ($formatted !== false) {
return $formatted;
}
// Number::currency() returns false for a currency intl does not
// recognise, so fall back to a plain number rather than rendering a
// blank price next to the plan.
return number_format($value, 2);
}
/**
* Determine whether the given plan key is configured and can be purchased.
*/
public static function isAvailablePlan(string $key): bool
{
return array_key_exists($key, static::availablePlans());
}
/**
* Get the trial to grant a new subscription, in days.
*
* Stripe rejects a Checkout trial shorter than 48 hours, so a configured
* value below that is reported as no trial at all rather than sent and
* failed.
*/
public static function trialDays(): int
{
$days = config('plans.trial_days');
return is_int($days) && $days >= 2 ? $days : 0;
}
/**
* Get the options used for a Checkout session, so that starting a
* subscription from the pricing page and from signup behave identically.
*
* @return array<string, mixed>
*/
public static function checkoutOptions(): array
{
return [
'success_url' => route('subscription.confirmed', [
'session_id' => '{CHECKOUT_SESSION_ID}',
]),
'cancel_url' => route('pricing'),
'allow_promotion_codes' => true,
];
}
/**
* Start a Checkout session for the given plan key.
*
* @throws HttpException if the plan is not configured
*/
public function checkoutForPlan(string $plan): Checkout
{
$price = static::availablePlans()[$plan]['price'] ?? null;
if ($price === null) {
abort(422, 'That plan is not available.');
}
$builder = $this->newSubscription($this->subscriptionType(), $price);
if (static::trialDays() > 0) {
$builder = $builder->trialDays(static::trialDays());
}
return $builder->checkout(static::checkoutOptions());
}
/**
* Determine whether the user holds the given role in this organization.
*/
public function userHasRole(User $user, OrganizationRole $role): bool
{
return $this->users()
->where('users.id', $user->id)
->wherePivot('role', $role->value)
->exists();
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Models;
use Database\Factories\SettingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $key
* @property string|null $value
*/
#[Fillable(['key', 'value'])]
class Setting extends Model
{
/** @use HasFactory<SettingFactory> */
use HasFactory;
/**
* The setting key holding the advertised amount, in minor units, of the
* given plan.
*/
public static function planAmountKey(string $plan): string
{
return "plans.{$plan}.amount";
}
/**
* Get a setting's value, falling back to the given default when the
* setting is absent or blank.
*/
public static function get(string $key, ?string $default = null): ?string
{
$value = static::query()->where('key', $key)->value('value');
return $value === null || $value === '' ? $default : $value;
}
/**
* Get a setting's value as an integer amount in minor units.
*
* A value that is not a valid amount is treated as unset rather than shown
* as zero, so a bad edit cannot silently advertise a free plan.
*/
public static function amount(string $key, int $default): int
{
$value = static::get($key);
return is_numeric($value) && (int) $value >= 0 ? (int) $value : $default;
}
/**
* Create or update a setting's value.
*/
public static function put(string $key, string $value): void
{
static::query()->updateOrCreate(['key' => $key], ['value' => $value]);
}
/**
* Convert a price typed in major units, such as "12.5", into the minor
* units amounts are stored in.
*
* The value is split as a string rather than multiplied, so that a price
* with cents is not subject to floating point drift.
*/
public static function toMinorUnits(string $amount): int
{
[$whole, $fraction] = array_pad(explode('.', str_replace(',', '.', trim($amount)), 2), 2, '');
$fraction = substr(str_pad($fraction, 2, '0'), 0, 2);
return (int) $whole * 100 + (int) $fraction;
}
}
+60 -1
View File
@@ -3,10 +3,13 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\OrganizationRole;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
@@ -17,6 +20,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
/**
* @property int $id
* @property int|null $current_organization_id
* @property string $name
* @property string $email
* @property Carbon|null $email_verified_at
@@ -30,13 +34,68 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'email', 'password', 'is_admin', 'notes_limit'])]
#[Fillable(['name', 'email', 'password', 'is_admin', 'notes_limit', 'current_organization_id'])]
#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
class User extends Authenticatable implements PasskeyUser
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable, PasskeyAuthenticatable, TwoFactorAuthenticatable;
/**
* Give every new account a personal organization to hold its subscription.
* The entitlement check silently depends on one existing, so this happens
* here rather than being left to each place that creates a user.
*/
protected static function booted(): void
{
static::created(function (User $user): void {
$user->createPersonalOrganization();
});
}
/**
* @return BelongsTo<Organization, $this>
*/
public function currentOrganization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'current_organization_id');
}
/**
* @return BelongsToMany<Organization, $this>
*/
public function organizations(): BelongsToMany
{
return $this->belongsToMany(Organization::class)
->withPivot('role')
->withTimestamps();
}
/**
* Create a personal organization owned by this user and make it current.
*/
public function createPersonalOrganization(): Organization
{
$organization = Organization::create([
'name' => $this->name."'s Workspace",
'personal_workspace' => true,
]);
$this->organizations()->attach($organization, ['role' => OrganizationRole::Owner->value]);
$this->forceFill(['current_organization_id' => $organization->id])->save();
return $organization;
}
/**
* Determine whether the current organization may use the application. A
* user without one is never entitled.
*/
public function hasActiveSubscription(): bool
{
return $this->currentOrganization()->first()?->isEntitled() ?? false;
}
/**
* Get the attributes that should be cast.
*
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App;
enum OrganizationRole: string
{
case Owner = 'owner';
case Member = 'member';
/**
* Get the human-friendly label for the role.
*/
public function label(): string
{
return match ($this) {
self::Owner => 'Owner',
self::Member => 'Member',
};
}
}
+27 -1
View File
@@ -2,11 +2,15 @@
namespace App\Providers;
use App\Http\Responses\RegisterResponse;
use App\Models\Organization;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
class AppServiceProvider extends ServiceProvider
{
@@ -15,7 +19,19 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->registerFortifyResponses();
}
/**
* Swap Fortify's registration response for one that starts checkout for the
* plan the account signed up with.
*/
protected function registerFortifyResponses(): void
{
$this->app->singleton(
RegisterResponseContract::class,
RegisterResponse::class,
);
}
/**
@@ -24,6 +40,16 @@ class AppServiceProvider extends ServiceProvider
public function boot(): void
{
$this->configureDefaults();
$this->configureCashier();
}
/**
* Make organizations, rather than users, the Stripe customer. This also
* determines the foreign key Cashier uses on the subscriptions table.
*/
protected function configureCashier(): void
{
Cashier::useCustomerModel(Organization::class);
}
/**