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
+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.
*