Files
mytodos/app/Models/Organization.php
T

340 lines
9.6 KiB
PHP
Raw Normal View History

2026-10-04 20:34:19 -07:00
<?php
namespace App\Models;
use App\OrganizationRole;
2026-10-15 20:59:32 -07:00
use App\WorkspaceType;
2026-10-04 20:34:19 -07:00
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;
2026-10-15 20:59:32 -07:00
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
2026-10-04 20:34:19 -07:00
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;
/**
2026-10-15 20:59:32 -07:00
* An organization is a workspace: it owns the subscription, is the Stripe
* customer, and its members share access to the folders inside it. Every user
* is given a personal organization when their account is created; family and
* organization workspaces are created later.
2026-10-04 20:34:19 -07:00
*
* @property int $id
* @property string $name
2026-10-15 20:59:32 -07:00
* @property WorkspaceType $type
2026-10-04 20:34:19 -07:00
* @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
*/
2026-10-15 20:59:32 -07:00
#[Fillable(['name', 'type', 'personal_workspace', 'lifetime_access'])]
2026-10-04 20:34:19 -07:00
#[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 [
2026-10-15 20:59:32 -07:00
'type' => WorkspaceType::class,
2026-10-04 20:34:19 -07:00
'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();
}
2026-10-15 20:59:32 -07:00
/**
* @return HasMany<Folder, $this>
*/
public function folders(): HasMany
{
return $this->hasMany(Folder::class);
}
/**
* @return MorphMany<Invitation, $this>
*/
public function invitations(): MorphMany
{
return $this->morphMany(Invitation::class, 'inviteable');
}
public function isPersonal(): bool
{
return $this->type === WorkspaceType::Personal;
}
public function isFamily(): bool
{
return $this->type === WorkspaceType::Family;
}
public function isOrganization(): bool
{
return $this->type === WorkspaceType::Organization;
}
/**
* Get how many users this workspace may hold, or null for an unlimited
* organization.
*/
public function seatLimit(): ?int
{
return config("workspaces.seat_limits.{$this->type->value}");
}
/**
* Get how many users this workspace currently holds.
*/
public function memberCount(): int
{
return $this->users()->count();
}
/**
* Determine whether another member can join this workspace.
*
* Organization workspaces are provisioned separately and are therefore
* never constrained by a seat limit.
*/
public function canAddMember(): bool
{
$limit = $this->seatLimit();
return $limit === null || $this->memberCount() < $limit;
}
2026-10-04 20:34:19 -07:00
/**
* 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();
}
}