$shares * @property Carbon|null $created_at * @property Carbon|null $updated_at */ #[Fillable(['user_id', 'organization_id', 'name', 'visibility', 'parent_id', 'color'])] class Folder extends Model { /** @use HasFactory */ use HasFactory; public const COLORS = [ 'zinc', 'red', 'orange', 'amber', 'green', 'emerald', '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 */ protected function casts(): array { return [ 'visibility' => FolderVisibility::class, ]; } /** @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class); } /** @return BelongsTo */ public function organization(): BelongsTo { return $this->belongsTo(Organization::class); } /** @return BelongsTo */ public function parent(): BelongsTo { return $this->belongsTo(Folder::class, 'parent_id'); } /** @return HasMany */ public function children(): HasMany { return $this->hasMany(Folder::class, 'parent_id'); } /** @return HasMany */ public function todos(): HasMany { return $this->hasMany(Todo::class); } /** @return BelongsToMany */ public function shares(): BelongsToMany { return $this->belongsToMany(User::class) ->withPivot('role', 'invited_by') ->withTimestamps(); } /** @return MorphMany */ public function invitations(): MorphMany { return $this->morphMany(Invitation::class, 'inviteable'); } /** * Scope the query to folders owned by the given user. * * @param Builder $query * @return Builder */ public function scopeForUser(Builder $query, User|int $user): Builder { return $query->where('user_id', $user instanceof User ? $user->id : $user); } /** * Scope the query to top-level folders (no parent). * * @param Builder $query * @return Builder */ public function scopeToplevel(Builder $query): Builder { 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 $query * @return Builder */ 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"). * * @return Collection */ public static function treeForUser(User|int $user): Collection { $folders = Folder::query() ->forUser($user) ->with('organization') ->orderBy('name') ->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 */ 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 $folders * @return Collection */ private static function flattenTree(Collection $folders): Collection { $indexed = $folders->keyBy('id'); $tree = collect(); $visit = function (Folder $folder, int $depth, string $prefix) use (&$visit, &$tree, $indexed): void { $path = $prefix === '' ? $folder->name : $prefix.' / '.$folder->name; $tree->push([ 'folder' => $folder, 'depth' => $depth, 'path' => $path, ]); foreach ($indexed->where('parent_id', $folder->id)->values() as $child) { $visit($child, $depth + 1, $path); } }; $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; } }