@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user