Files
mytodos/app/Models/Invitation.php
T
ecdown 177f122c10
tests / ci (push) Canceled after 0s
added roles and organizations
2026-10-15 20:59:32 -07:00

243 lines
6.6 KiB
PHP

<?php
namespace App\Models;
use App\FolderRole;
use App\OrganizationRole;
use Database\Factories\InvitationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* An invitation grants someone access to a folder or a workspace. The
* inviteable is polymorphic so folders and workspaces share the same flow; the
* token is the bearer credential the invitee exchanges for access, which is
* why it is mailed rather than shown.
*
* @property int $id
* @property int $inviter_id
* @property string $email
* @property string $role
* @property string $inviteable_type
* @property int $inviteable_id
* @property string $token
* @property Carbon|null $expires_at
* @property Carbon|null $accepted_at
* @property int|null $accepted_by_id
* @property Organization|Folder $inviteable
* @property User $inviter
* @property User|null $acceptedBy
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable([
'inviter_id',
'email',
'role',
'inviteable_type',
'inviteable_id',
'token',
'expires_at',
'accepted_at',
'accepted_by_id',
])]
class Invitation extends Model
{
/** @use HasFactory<InvitationFactory> */
use HasFactory;
/**
* How long an invitation stays redeemable after it is sent.
*/
public const EXPIRY_DAYS = 14;
/**
* Every invitation is addressed by a fresh token and gets a sensible
* expiry, so callers only ever supply the inviteable and the role.
*/
protected static function booted(): void
{
static::creating(function (Invitation $invitation): void {
$invitation->token ??= Str::random(64);
$invitation->expires_at ??= Carbon::now()->addDays(self::EXPIRY_DAYS);
});
}
/** @return MorphTo<Model, $this> */
public function inviteable(): MorphTo
{
return $this->morphTo();
}
/** @return BelongsTo<User, $this> */
public function inviter(): BelongsTo
{
return $this->belongsTo(User::class, 'inviter_id');
}
/** @return BelongsTo<User, $this> */
public function acceptedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'accepted_by_id');
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'expires_at' => 'datetime',
'accepted_at' => 'datetime',
];
}
/**
* Determine whether the invitation has been used.
*/
public function isAccepted(): bool
{
return $this->accepted_at !== null;
}
/**
* Determine whether the invitation has lapsed.
*/
public function isExpired(): bool
{
return $this->expires_at !== null && $this->expires_at->isPast();
}
/**
* Determine whether the invitation can still be redeemed.
*/
public function isValid(): bool
{
return ! $this->isAccepted() && ! $this->isExpired();
}
/**
* Scope the query to invitations that can still be redeemed.
*
* @param Builder<Invitation> $query
* @return Builder<Invitation>
*/
public function scopePending(Builder $query): Builder
{
return $query->whereNull('accepted_at')
->where(function (Builder $query): void {
$query->whereNull('expires_at')
->orWhere('expires_at', '>', now());
});
}
/**
* Determine whether this invitation grants access to a folder.
*/
public function isForFolder(): bool
{
return $this->inviteable_type === Folder::class;
}
/**
* Determine whether this invitation grants access to a workspace.
*/
public function isForWorkspace(): bool
{
return $this->inviteable_type === Organization::class;
}
/**
* Get the folder role this invitation grants, or null when it does not
* invite into a folder.
*/
public function folderRole(): ?FolderRole
{
return $this->isForFolder() ? FolderRole::tryFrom($this->role) : null;
}
/**
* Get the workspace role this invitation grants, or null when it does not
* invite into a workspace.
*/
public function organizationRole(): ?OrganizationRole
{
return $this->isForWorkspace() ? OrganizationRole::tryFrom($this->role) : null;
}
/**
* Get a human-readable label for the role this invitation grants.
*/
public function roleLabel(): string
{
return $this->folderRole()?->label()
?? $this->organizationRole()?->label()
?? $this->role;
}
/**
* Get the name of the person who sent the invitation.
*/
public function inviterName(): string
{
return $this->inviter->name;
}
/**
* Get the name of the folder or workspace the invitation is for.
*/
public function inviteableName(): string
{
if (! $this->isForFolder() && ! $this->isForWorkspace()) {
return '';
}
return (string) $this->inviteable->name;
}
/**
* Redeem the invitation for the given user, granting membership on the
* invited folder or workspace and recording who accepted it. Already
* accepted or expired invitations are left untouched.
*/
public function accept(User $user): void
{
if (! $this->isValid()) {
return;
}
$inviteable = $this->inviteable;
if ($inviteable instanceof Folder) {
$inviteable->shares()->syncWithoutDetaching([
$user->id => [
'role' => ($this->folderRole() ?? FolderRole::Viewer)->value,
'invited_by' => $this->inviter_id,
],
]);
} elseif ($inviteable instanceof Organization) {
$inviteable->users()->syncWithoutDetaching([
$user->id => [
'role' => ($this->organizationRole() ?? OrganizationRole::Member)->value,
],
]);
// Drop the invitee straight into the workspace they just joined.
$user->forceFill(['current_organization_id' => $inviteable->id])->save();
}
$this->forceFill([
'accepted_at' => now(),
'accepted_by_id' => $user->id,
])->save();
}
}