added roles and organizations
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-15 20:59:32 -07:00
parent 2ca3860557
commit 177f122c10
57 changed files with 6378 additions and 247 deletions
+257 -7
View File
@@ -2,27 +2,38 @@
namespace App\Models;
use App\FolderRole;
use App\FolderVisibility;
use App\OrganizationRole;
use App\WorkspaceType;
use Database\Factories\FolderFactory;
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\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* @property int $id
* @property int $user_id
* @property int|null $organization_id
* @property string $name
* @property FolderVisibility $visibility
* @property string|null $color
* @property int|null $parent_id
* @property Folder|null $parent
* @property Organization|null $organization
* @property Collection<int, User> $shares
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['user_id', 'name', 'parent_id', 'color'])]
#[Fillable(['user_id', 'organization_id', 'name', 'visibility', 'parent_id', 'color'])]
class Folder extends Model
{
/** @use HasFactory<FolderFactory> */
@@ -33,12 +44,60 @@ class Folder extends Model
'sky', 'blue', 'indigo', 'violet', 'fuchsia', 'pink',
];
/**
* Folders always belong to a workspace and carry an explicit visibility.
* Much of the app inserts rows in bulk without Eloquent, so rather than
* enforcing these in the schema we fill them in here whenever they are
* missing.
*/
protected static function booted(): void
{
static::creating(function (Folder $folder): void {
// Sub-folders inherit the workspace of the parent, so creating a
// child inside a folder shared from another workspace never leaks
// it into the creator's current workspace.
if ($folder->organization_id === null && $folder->parent_id !== null) {
$folder->organization_id = Folder::query()
->whereKey($folder->parent_id)
->value('organization_id');
}
$folder->organization_id ??= User::query()
->whereKey($folder->user_id)
->value('current_organization_id');
if ($folder->organization_id !== null) {
$folder->organization_id = (int) $folder->organization_id;
}
$folder->visibility ??= Folder::defaultVisibilityFor((int) $folder->organization_id);
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'visibility' => FolderVisibility::class,
];
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/** @return BelongsTo<Organization, $this> */
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class);
}
/** @return BelongsTo<Folder, $this> */
public function parent(): BelongsTo
{
@@ -57,6 +116,20 @@ class Folder extends Model
return $this->hasMany(Todo::class);
}
/** @return BelongsToMany<User, $this> */
public function shares(): BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('role', 'invited_by')
->withTimestamps();
}
/** @return MorphMany<Invitation, $this> */
public function invitations(): MorphMany
{
return $this->morphMany(Invitation::class, 'inviteable');
}
/**
* Scope the query to folders owned by the given user.
*
@@ -79,6 +152,144 @@ class Folder extends Model
return $query->whereNull('parent_id');
}
/**
* Scope the query to folders the given user can access. Pass a workspace
* id to narrow the workspace-wide folders to the active workspace while
* still surfacing folders explicitly shared with the user from anywhere.
*
* @param Builder<Folder> $query
* @return Builder<Folder>
*/
public function scopeVisibleTo(Builder $query, User|int $user, ?int $workspaceId = null): Builder
{
$userId = $user instanceof User ? $user->id : $user;
return $query->where(function (Builder $query) use ($userId, $workspaceId): void {
$query->where(function (Builder $owned) use ($userId, $workspaceId): void {
$owned->where('folders.user_id', $userId);
if ($workspaceId !== null) {
$owned->where('folders.organization_id', $workspaceId);
}
})
->orWhereHas('shares', function (Builder $shares) use ($userId): void {
$shares->where('folder_user.user_id', $userId);
})
->orWhere(function (Builder $member) use ($userId, $workspaceId): void {
$member->where('folders.visibility', FolderVisibility::Workspace->value);
if ($workspaceId !== null) {
$member->where('folders.organization_id', $workspaceId);
return;
}
$memberships = DB::table('organization_user')
->where('organization_user.user_id', $userId)
->select('organization_user.organization_id');
$member->whereIn('folders.organization_id', $memberships);
});
});
}
/**
* Get the visibility new folders should adopt in the given workspace.
* Personal workspaces keep folders private; shared workspaces default new
* folders to workspace-wide access. Falls back to private when the
* workspace cannot be found.
*/
public static function defaultVisibilityFor(int $organizationId): FolderVisibility
{
$type = Organization::query()->whereKey($organizationId)->value('type');
$workspaceType = $type instanceof WorkspaceType
? $type
: WorkspaceType::tryFrom(is_string($type) ? $type : '');
return $workspaceType?->defaultFolderVisibility() ?? FolderVisibility::Private;
}
/**
* Get the role explicitly granted to the user on this folder, or null
* when the folder has not been shared with them.
*/
public function sharedRoleFor(User $user): ?FolderRole
{
$share = $this->relationLoaded('shares')
? $this->shares->firstWhere('id', $user->id)
: $this->shares()->whereKey($user->id)->first();
if ($share === null) {
return null;
}
return FolderRole::tryFrom((string) $share->pivot->role);
}
/**
* Get the role the user holds through a workspace membership on this
* folder, or null when they are not a member or the folder is private.
*
* @internal Only meaningful for folders shared with the workspace.
*/
public function workspaceMembershipRoleFor(User $user): ?FolderRole
{
if ($this->organization_id === null) {
return null;
}
$role = OrganizationRole::tryFrom((string) DB::table('organization_user')
->where('organization_id', $this->organization_id)
->where('user_id', $user->id)
->value('role'));
return $role?->defaultFolderRole();
}
/**
* Get the strongest role the user holds anywhere on this folder's
* ancestry: their own grant if the folder is theirs, explicit shares
* (which cascade through the whole subtree), and workspace-wide access
* which flows down through folders that are themselves shared with the
* workspace.
*
* Personal workspaces never share folders, and a private folder drops out
* of workspace-wide access above it. Returns null when the user has no
* access at all.
*/
public function effectiveRoleFor(User $user): ?FolderRole
{
if ($this->user_id === $user->id) {
return FolderRole::Admin;
}
$role = $this->sharedRoleFor($user);
// Workspace-wide access only reaches this folder and its descendants
// while every folder between the grant and this folder is shared with
// the workspace. A private folder therefore stops inherited workspace
// access, though explicit shares above it still cascade.
$inheritsWorkspace = $this->visibility === FolderVisibility::Workspace;
if ($inheritsWorkspace) {
$role = FolderRole::higherOf($role, $this->workspaceMembershipRoleFor($user));
}
$ancestor = $this->parent;
while ($ancestor !== null) {
$role = FolderRole::higherOf($role, $ancestor->sharedRoleFor($user));
if ($inheritsWorkspace && $ancestor->visibility === FolderVisibility::Workspace) {
$role = FolderRole::higherOf($role, $ancestor->workspaceMembershipRoleFor($user));
}
$ancestor = $ancestor->parent;
}
return $role;
}
/**
* Build a flattened, depth-aware tree of the user's folders
* ordered top-down, with the full path (e.g. "Work / Acme Corp").
@@ -89,12 +300,47 @@ class Folder extends Model
{
$folders = Folder::query()
->forUser($user)
->with('organization')
->orderBy('name')
->get()
->keyBy('id');
->get();
return static::flattenTree($folders);
}
/**
* Build the flattened tree of every folder the user can see in the given
* workspace: their own folders, folders shared with the workspace, and
* folders explicitly shared with them from any workspace.
*
* @return Collection<int, array{folder: Folder, depth: int, path: string}>
*/
public static function treeForVisibleTo(User|int $user, int $workspaceId): Collection
{
$folders = Folder::query()
->visibleTo($user, $workspaceId)
->with('organization')
->withCount('shares')
->orderBy('name')
->get();
return static::flattenTree($folders);
}
/**
* Flatten a flat collection of folders into a depth-aware tree. A folder
* whose parent is missing from the collection (for example a folder shared
* from outside the active workspace) is treated as a root so it is never
* dropped from the tree.
*
* @param Collection<int, Folder> $folders
* @return Collection<int, array{folder: Folder, depth: int, path: string}>
*/
private static function flattenTree(Collection $folders): Collection
{
$indexed = $folders->keyBy('id');
$tree = collect();
$visit = function (Folder $folder, int $depth, string $prefix) use (&$visit, &$tree, $folders): void {
$visit = function (Folder $folder, int $depth, string $prefix) use (&$visit, &$tree, $indexed): void {
$path = $prefix === '' ? $folder->name : $prefix.' / '.$folder->name;
$tree->push([
@@ -103,13 +349,17 @@ class Folder extends Model
'path' => $path,
]);
foreach ($folders->where('parent_id', $folder->id)->values() as $child) {
foreach ($indexed->where('parent_id', $folder->id)->values() as $child) {
$visit($child, $depth + 1, $path);
}
};
foreach ($folders->whereNull('parent_id')->values() as $topLevel) {
$visit($topLevel, 0, '');
$roots = $indexed->filter(
fn (Folder $folder): bool => $folder->parent_id === null || ! $indexed->has($folder->parent_id)
);
foreach ($roots->values() as $root) {
$visit($root, 0, '');
}
return $tree;
+242
View File
@@ -0,0 +1,242 @@
<?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();
}
}
+71 -5
View File
@@ -3,12 +3,15 @@
namespace App\Models;
use App\OrganizationRole;
use App\WorkspaceType;
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\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Number;
use Laravel\Cashier\Billable;
@@ -17,13 +20,14 @@ 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.
* 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.
*
* @property int $id
* @property string $name
* @property WorkspaceType $type
* @property bool $personal_workspace
* @property bool $lifetime_access
* @property string|null $stripe_id
@@ -33,7 +37,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'personal_workspace', 'lifetime_access'])]
#[Fillable(['name', 'type', 'personal_workspace', 'lifetime_access'])]
#[Hidden(['stripe_id'])]
class Organization extends Model
{
@@ -48,6 +52,7 @@ class Organization extends Model
protected function casts(): array
{
return [
'type' => WorkspaceType::class,
'personal_workspace' => 'boolean',
'lifetime_access' => 'boolean',
'trial_ends_at' => 'datetime',
@@ -64,6 +69,67 @@ class Organization extends Model
->withTimestamps();
}
/**
* @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;
}
/**
* Get the subscription type that Cashier stores this organization's
* subscriptions under.
+40 -4
View File
@@ -14,6 +14,7 @@ use Illuminate\Support\Carbon;
/**
* @property int $id
* @property int $user_id
* @property int|null $organization_id
* @property int $folder_id
* @property string $description
* @property string|null $notes
@@ -25,18 +26,38 @@ use Illuminate\Support\Carbon;
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['user_id', 'folder_id', 'description', 'notes', 'status', 'position', 'due_date', 'completed_at'])]
#[Fillable(['user_id', 'organization_id', 'folder_id', 'description', 'notes', 'status', 'position', 'due_date', 'completed_at'])]
class Todo extends Model
{
/** @use HasFactory<TodoFactory> */
use HasFactory;
/**
* Todos belong to a workspace through the folder they sit in. The
* organization id is filled in here for anything inserted outside
* Eloquent, which stores a column that is only nullable in the schema.
*/
protected static function booted(): void
{
static::creating(function (Todo $todo): void {
$todo->organization_id ??= Folder::query()
->whereKey($todo->folder_id)
->value('organization_id');
});
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/** @return BelongsTo<Organization, $this> */
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class);
}
/** @return BelongsTo<Folder, $this> */
public function folder(): BelongsTo
{
@@ -68,6 +89,19 @@ class Todo extends Model
return $query->where('user_id', $user instanceof User ? $user->id : $user);
}
/**
* Scope the query to todos the given user can access, which follows the
* folder the todo sits in. Pass a workspace id to narrow the query to the
* active workspace, matching {@see Folder::scopeVisibleTo()}.
*
* @param Builder<Todo> $query
* @return Builder<Todo>
*/
public function scopeVisibleTo(Builder $query, User|int $user, ?int $workspaceId = null): Builder
{
return $query->whereIn('folder_id', Folder::query()->visibleTo($user, $workspaceId)->select('folders.id'));
}
/**
* Scope the query to todos that have not been completed.
*
@@ -139,11 +173,13 @@ class Todo extends Model
/**
* Get the position to assign to a new todo so it appears at the top of the
* priority order for the given user.
* priority order for its folder. Ordering is shared by everyone with
* access to the folder, so the position is computed across all of the
* folder's todos regardless of who created them.
*/
public static function nextPositionFor(User|int $user): int
public static function nextPositionFor(Folder $folder): int
{
$min = static::query()->forUser($user)->min('position');
$min = static::query()->where('folder_id', $folder->id)->min('position');
return $min === null ? 1 : $min - 1;
}
+31 -2
View File
@@ -4,6 +4,7 @@ namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\OrganizationRole;
use App\WorkspaceType;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -71,6 +72,16 @@ class User extends Authenticatable implements PasskeyUser
->withTimestamps();
}
/**
* @return BelongsToMany<Folder, $this>
*/
public function sharedFolders(): BelongsToMany
{
return $this->belongsToMany(Folder::class)
->withPivot('role', 'invited_by')
->withTimestamps();
}
/**
* Create a personal organization owned by this user and make it current.
*/
@@ -78,6 +89,7 @@ class User extends Authenticatable implements PasskeyUser
{
$organization = Organization::create([
'name' => $this->name."'s Workspace",
'type' => WorkspaceType::Personal,
'personal_workspace' => true,
]);
@@ -122,13 +134,30 @@ class User extends Authenticatable implements PasskeyUser
}
/**
* Determine whether the user is an administrator.
* Determine whether the user is a site-wide administrator. This is
* unrelated to any workspace role: site admins may reach the admin area,
* whereas a workspace owner or admin may not.
*/
public function isAdmin(): bool
public function isSiteAdmin(): bool
{
return (bool) $this->is_admin;
}
/**
* Determine whether the user is an owner or admin of the given workspace.
* This grants rights inside that workspace only, never site-wide access.
*/
public function isOrganizationAdmin(Organization $organization): bool
{
return $organization->users()
->where('users.id', $this->id)
->wherePivotIn('role', [
OrganizationRole::Owner->value,
OrganizationRole::Admin->value,
])
->exists();
}
/**
* Get the maximum length allowed for todo notes.
*/