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
+510
View File
@@ -0,0 +1,510 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Cookie\CookieValuePrefix;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Seeds a dataset shaped like real usage, plus a manifest of ready-made
* authenticated sessions for the k6 load tests.
*
* The sessions are written through the framework's own session store rather
* than by posting to /login, because Fortify's login form runs bcrypt at
* BCRYPT_ROUNDS=12 and that would dominate the latency figures the tests are
* trying to measure.
*/
#[Signature(
signature: 'app:seed-load-test
{--users=1000 : Number of entitled users to create}
{--folders=50 : Folders per user, nested up to three levels deep}
{--todos=500 : Todos per user, spread across their folders}
{--admins=2 : Admin users to create}
{--chunk=50 : Users to create and populate per chunk}
{--sessions= : Where to write the k6 session manifest (defaults to load-tests/sessions.json)}
{--fresh : Delete previously seeded load-test users first}
{--force : Allow running when APP_ENV is production}',
)]
#[Description('Seed load-test users, folders, todos and authenticated sessions for k6')]
class SeedLoadTestData extends Command
{
/**
* Every seeded account uses this domain so --fresh can find them again
* without a database migration to track them.
*/
private const EMAIL_DOMAIN = 'loadtest.invalid';
/**
* How the todos of a user are distributed across the statuses the
* application branches on. The dashboard counts open, completed, overdue
* and due-today separately, so each of those buckets needs to be non-empty
* for the counts to mean anything.
*
* @var array<string, int>
*/
private const STATUS_MIX = [
'open' => 40,
'in-progress' => 15,
'on-hold' => 8,
'blocked' => 8,
'completed' => 20,
'cancelled' => 5,
'deferred' => 4,
];
/**
* Folder colours, matching the palette the folder UI offers.
*
* @var list<string>
*/
private const COLORS = ['red', 'orange', 'amber', 'green', 'emerald', 'blue', 'indigo', 'purple', 'pink'];
/**
* Execute the console command.
*/
public function handle(): int
{
if (app()->environment('production') && ! $this->option('force')) {
$this->error('Refusing to seed load-test data in production without --force.');
return self::FAILURE;
}
$users = (int) $this->option('users');
$admins = (int) $this->option('admins');
$folders = (int) $this->option('folders');
$todos = (int) $this->option('todos');
$chunk = max(1, (int) $this->option('chunk'));
if ($folders < 1) {
$this->error('--folders must be at least 1, because every todo belongs to a folder.');
return self::FAILURE;
}
if ($this->option('fresh')) {
$this->deleteSeededUsers();
}
$this->line(sprintf(
'Seeding %d user(s) and %d admin(s), %d folder(s) and %d todo(s) each...',
$users,
$admins,
$folders,
$todos,
));
$manifest = [];
$progress = $this->output->createProgressBar($users + $admins);
$progress->start();
for ($index = 0; $index < $users + $admins; $index += $chunk) {
$size = min($chunk, $users + $admins - $index);
foreach ($this->createChunk($index, $size, $folders, $todos) as $entry) {
$manifest[] = $entry;
}
$progress->advance($size);
}
$progress->finish();
$this->newLine(2);
$path = $this->writeManifest($manifest);
$this->line(sprintf('Wrote %d session(s) to %s', count($manifest), $path));
$this->newLine();
$this->line('Run the load tests against a served copy of this app with:');
$this->line(' k6 run load-tests/app.js');
return self::SUCCESS;
}
/**
* Create one batch of users and populate each with folders and todos.
*
* @return list<array{userId: int, email: string, isAdmin: bool, sessionId: string, cookie: string, todoIds: list<int>, folderIds: list<int>}>
*/
private function createChunk(int $offset, int $size, int $folders, int $todos): array
{
$entries = [];
$cookieName = (string) config('session.cookie');
for ($i = $offset; $i < $offset + $size; $i++) {
$isAdmin = $i >= (int) $this->option('users');
$user = $this->createUser($i, $isAdmin);
$organizationId = (int) $user->current_organization_id;
$folderIds = $this->seedFolders($user->id, $organizationId, $folders);
$this->seedTodos($user->id, $organizationId, $folderIds, $todos);
$sessionId = $this->createSession($user);
$entries[] = [
'userId' => $user->id,
'email' => $user->email,
'isAdmin' => $isAdmin,
'sessionId' => $sessionId,
'cookieName' => $cookieName,
'cookie' => $this->sessionCookie($sessionId),
'todoIds' => $this->sampleTodoIds($user->id, $folderIds),
'folderIds' => array_slice($folderIds, 0, 10),
];
}
return $entries;
}
/**
* Create one entitled user.
*
* UserFactory already attaches a personal organization and a local
* subscription row, which is all EnsureSubscribed reads, so no Stripe
* call is involved and none is possible.
*/
private function createUser(int $index, bool $isAdmin): User
{
$factory = User::factory();
if ($isAdmin) {
$factory = $factory->asAdmin();
}
return $factory->create([
'name' => $isAdmin ? 'Load Admin' : 'Load User '.$index,
'email' => sprintf('loadtest%05d@%s', $index, self::EMAIL_DOMAIN),
]);
}
/**
* Insert a folder tree for a user and return the ids of every folder.
*
* Parents are inserted in their own batch ahead of their children so the
* self-referencing foreign key is always satisfied by a row that already
* exists.
*
* @return list<int>
*/
private function seedFolders(int $userId, int $organizationId, int $count): array
{
$now = now();
$visibility = $this->visibilityFor($organizationId);
$insert = fn (string $name, ?int $parentId, int $position): array => [
'user_id' => $userId,
'organization_id' => $organizationId,
'name' => $name,
'visibility' => $visibility,
'parent_id' => $parentId,
'color' => self::COLORS[($position + $userId) % count(self::COLORS)],
'created_at' => $now,
'updated_at' => $now,
];
$rootCount = max(1, (int) round($count / 3));
$childCount = (int) round(($count - $rootCount) / 2);
$rows = [];
for ($i = 0; $i < $rootCount && $i < $count; $i++) {
$rows[] = $insert('Project '.($i + 1), null, $i);
}
DB::table('folders')->insert($rows);
$rootIds = $this->folderIds($userId);
$childIds = [];
if ($childCount > 0 && $rootIds !== []) {
$rows = [];
for ($i = 0; $i < $childCount; $i++) {
$rows[] = $insert('Milestone '.($i + 1), $rootIds[$i % count($rootIds)], $i);
}
DB::table('folders')->insert($rows);
$childIds = array_values(array_diff($this->folderIds($userId), $rootIds));
}
$remaining = $count - count($rootIds) - count($childIds);
if ($remaining > 0 && $childIds !== []) {
$rows = [];
for ($i = 0; $i < $remaining; $i++) {
$rows[] = $insert('Task '.($i + 1), $childIds[$i % count($childIds)], $i);
}
DB::table('folders')->insert($rows);
$childIds = array_values(array_diff($this->folderIds($userId), $rootIds));
}
return $childIds;
}
/**
* Read back a user's folder ids in insertion order.
*
* Ids are read rather than predicted because a cascade delete advances
* MySQL's auto-increment counter without lowering MAX(id), so the next
* insert is not guaranteed to continue from the current maximum.
*
* @return list<int>
*/
private function folderIds(int $userId): array
{
return DB::table('folders')
->where('user_id', $userId)
->orderBy('id')
->pluck('id')
->map(fn ($id): int => (int) $id)
->all();
}
/**
* Get the folder visibility a workspace defaults to, so bulk inserts match
* what the application would have written.
*/
private function visibilityFor(int $organizationId): string
{
$type = DB::table('organizations')->where('id', $organizationId)->value('type');
return strval($type) === 'personal' ? 'private' : 'workspace';
}
/**
* Insert a user's todos, spread across their folders.
*
* @param list<int> $folderIds
*/
private function seedTodos(int $userId, int $organizationId, array $folderIds, int $count): void
{
if ($folderIds === [] || $count < 1) {
return;
}
$statuses = $this->weightedStatuses();
$now = now();
$today = $now->copy()->startOfDay();
foreach (array_chunk(range(0, $count - 1), 500) as $batch) {
$rows = [];
$completedSeen = 0;
foreach ($batch as $index) {
$status = $statuses[$index % count($statuses)];
$isTerminal = $status === 'completed';
if ($isTerminal) {
$completedSeen++;
}
// Only active statuses can be overdue or due today, because
// both dashboard counts filter on active() as well.
$dueDate = $this->dueDateFor($status, $today, $index);
$rows[] = [
'user_id' => $userId,
'organization_id' => $organizationId,
'folder_id' => $folderIds[$index % count($folderIds)],
'description' => $this->descriptionFor($index),
'notes' => $index % 4 === 0 ? 'Context for item '.$index.'. '.str_repeat('Additional detail. ', 4) : null,
'status' => $status,
// Leaving roughly a third without a position exercises the
// "position IS NULL" branch of the priority sort.
'position' => $index % 3 === 0 ? $completedSeen + 1 : null,
'due_date' => $dueDate,
'completed_at' => $isTerminal ? $today->copy()->subDays($index % 30)->setTime(12, 0) : null,
'created_at' => $now->copy()->subDays($index % 60),
'updated_at' => $now,
];
}
DB::table('todos')->insert($rows);
}
}
/**
* Expand the status mix into one entry per todo.
*
* @return list<string>
*/
private function weightedStatuses(): array
{
$statuses = [];
foreach (self::STATUS_MIX as $status => $weight) {
for ($i = 0; $i < $weight; $i++) {
$statuses[] = $status;
}
}
return $statuses;
}
/**
* Choose a due date so the overdue, due-today and future buckets are all
* populated for the active statuses.
*/
private function dueDateFor(string $status, CarbonInterface $today, int $index): ?string
{
$active = ! in_array($status, ['completed', 'cancelled', 'deferred'], true);
if ($index % 5 === 0) {
return null;
}
if ($active && $index % 5 === 1) {
return $today->copy()->subDays(($index % 21) + 1)->toDateString();
}
if ($active && $index % 5 === 2) {
return $today->toDateString();
}
return $today->copy()->addDays(($index % 90) + 1)->toDateString();
}
/**
* Build a todo description, varying length so the search column holds a
* realistic mix rather than one uniform string.
*/
private function descriptionFor(int $index): string
{
$short = [
'Review pull request',
'Reply to inbox',
'Book dentist',
'Water the plants',
'Refill prescriptions',
'Pay the invoice',
'Update the changelog',
'Renew the domain',
];
$base = $short[$index % count($short)];
if ($index % 3 === 0) {
return $base.' #'.($index + 1);
}
if ($index % 3 === 1) {
return $base.' for the '.['launch', 'quarterly review', 'migration', 'handover'][$index % 4].' workstream';
}
return $base.' and confirm the follow-up items with the team before the '.['standup', 'review', 'retro'][$index % 3].' on Friday';
}
/**
* Pick todo ids for the write scenarios to act on.
*
* The load tests need real ids because the write calls go through
* findOrFail against the requesting user, so a fabricated id would measure
* a 404 instead of a write. Rotating over several ids keeps the write
* spread across rows the way real clicking does, rather than hammering
* one row that stays hot in the buffer pool.
*
* @param list<int> $folderIds
* @return list<int>
*/
private function sampleTodoIds(int $userId, array $folderIds): array
{
return DB::table('todos')
->where('user_id', $userId)
->whereIn('folder_id', $folderIds === [] ? [0] : $folderIds)
->whereNull('completed_at')
->orderBy('id')
->limit(5)
->pluck('id')
->map(fn ($id): int => (int) $id)
->all();
}
/**
* Create a logged-in session row for a user and return its id.
*
* Writing through the session store keeps the stored payload in exactly
* the shape the framework's own session handler reads back, which is what
* the load tests need in order to authenticate by cookie alone.
*
* The id is read back only after logging in, because SessionGuard::login()
* calls migrate() internally and replaces it with a fresh one.
*/
private function createSession(User $user): string
{
$store = app('session.store');
$store->setId(Str::random(40));
$store->start();
Auth::guard('web')->login($user);
$store->save();
return $store->getId();
}
/**
* Build the cookie header value a browser would present for a session.
*
* EncryptCookies wraps every cookie value in an HMAC prefix and then
* encrypts it, so a bare session id is not accepted on the wire. The
* seeder therefore has to produce the same envelope, using the same
* serializer flag the middleware reports for itself.
*/
private function sessionCookie(string $sessionId): string
{
$name = (string) config('session.cookie');
$prefix = CookieValuePrefix::create($name, app('encrypter')->getKey());
return app('encrypter')->encrypt(
$prefix.$sessionId,
EncryptCookies::serialized($name),
);
}
/**
* Remove previously seeded accounts, relying on cascades for their data.
*/
private function deleteSeededUsers(): void
{
$count = DB::table('users')->where('email', 'like', '%@'.self::EMAIL_DOMAIN)->count();
if ($count === 0) {
$this->line('No previously seeded load-test users to remove.');
return;
}
$userIds = DB::table('users')->where('email', 'like', '%@'.self::EMAIL_DOMAIN)->pluck('id');
DB::table('sessions')->whereIn('user_id', $userIds)->delete();
User::query()->whereIn('id', $userIds)->delete();
$this->line("Removed {$count} previously seeded load-test user(s).");
}
/**
* Write the session manifest that the k6 script reads at init time.
*
* @param list<array{userId: int, email: string, isAdmin: bool, sessionId: string, cookie: string}> $manifest
*/
private function writeManifest(array $manifest): string
{
$path = (string) ($this->option('sessions') ?: base_path('load-tests/sessions.json'));
$directory = dirname($path);
if (! is_dir($directory)) {
mkdir($directory, 0755, recursive: true);
}
file_put_contents($path, json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
return $path;
}
}
+75 -1
View File
@@ -78,6 +78,7 @@ class TransferSqliteData extends Command
$this->transferTable($table, $key);
}
$this->backfillWorkspaces();
$this->resetAutoIncrements();
} catch (Throwable $e) {
$this->error('Transfer failed: '.$e->getMessage());
@@ -117,12 +118,85 @@ class TransferSqliteData extends Command
->table($table)
->orderBy($key)
->chunk(500, function ($rows) use ($table): void {
DB::table($table)->insert($rows->map(fn ($row): array => (array) $row)->all());
DB::table($table)->insert($this->prepareRows($table, $rows));
});
$this->line(" transferred {$count} row(s) into {$table}.");
}
/**
* Folders and todos cannot be inserted without a workspace, but the source
* database predates workspaces. Folders inherit the current organization of
* their owner, and todos inherit the organization of their folder. Rows
* that already carry the value are left untouched.
*
* @param iterable<object> $rows
* @return list<array<string, mixed>>
*/
private function prepareRows(string $table, iterable $rows): array
{
$records = collect($rows)->map(fn ($row): array => (array) $row)->all();
if ($table === 'folders') {
$userIds = collect($records)->pluck('user_id')->all();
$organizationByUser = DB::table('users')
->whereIn('id', $userIds)
->pluck('current_organization_id', 'id')
->all();
foreach ($records as &$record) {
$record['organization_id'] ??= $organizationByUser[$record['user_id']] ?? null;
}
unset($record);
return $records;
}
if ($table === 'todos') {
$folderIds = collect($records)->pluck('folder_id')->all();
$organizationByFolder = DB::table('folders')
->whereIn('id', $folderIds)
->pluck('organization_id', 'id')
->all();
foreach ($records as &$record) {
$record['organization_id'] ??= $organizationByFolder[$record['folder_id']] ?? null;
}
unset($record);
return $records;
}
return $records;
}
/**
* The source database predates workspaces, so folders and todos arrive
* without an organization id and folders without a visibility. Fold them
* into the workspace their owner had active, exactly as the workspace
* migration does for existing rows.
*/
private function backfillWorkspaces(): void
{
DB::table('folders')
->join('users', 'users.id', '=', 'folders.user_id')
->whereNull('folders.organization_id')
->update(['folders.organization_id' => DB::raw('users.current_organization_id')]);
DB::table('todos')
->join('folders', 'folders.id', '=', 'todos.folder_id')
->whereNull('todos.organization_id')
->update(['todos.organization_id' => DB::raw('folders.organization_id')]);
DB::table('folders')
->join('organizations', 'organizations.id', '=', 'folders.organization_id')
->update([
'folders.visibility' => DB::raw(
"CASE WHEN organizations.personal_workspace = 1 THEN 'private' ELSE 'workspace' END"
),
]);
}
/**
* Bump each auto-increment counter past the highest transferred id so
* newly created records never collide with the preserved ids.
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App;
enum FolderRole: string
{
case Admin = 'admin';
case Editor = 'editor';
case Marker = 'marker';
case Viewer = 'viewer';
/**
* Get the human-friendly label for the role.
*/
public function label(): string
{
return match ($this) {
self::Admin => 'Admin',
self::Editor => 'Editor',
self::Marker => 'Marker',
self::Viewer => 'Viewer',
};
}
/**
* Determine whether the role may change a todo's completion state.
*/
public function canMarkComplete(): bool
{
return $this !== self::Viewer;
}
/**
* Determine whether the role may create, edit or delete todos. Editors
* manage todo content only; folder structure and collaborators are an
* admin concern.
*/
public function canEditTodos(): bool
{
return in_array($this, [self::Admin, self::Editor], true);
}
/**
* Determine whether the role may manage the folder itself: its structure,
* visibility and collaborators, and new folders beneath it.
*/
public function canManage(): bool
{
return $this === self::Admin;
}
/**
* Get the folder roles a collaborator may be assigned, most privileged
* first.
*
* @return list<self>
*/
public static function assignable(): array
{
return [self::Admin, self::Editor, self::Marker, self::Viewer];
}
/**
* Get this role's rank, so the strongest of two roles can be picked.
*/
public function rank(): int
{
return match ($this) {
self::Admin => 3,
self::Editor => 2,
self::Marker => 1,
self::Viewer => 0,
};
}
/**
* Get the strongest of the two roles, ignoring missing ones.
*/
public static function higherOf(?self $left, ?self $right): ?self
{
if ($left === null) {
return $right;
}
if ($right === null) {
return $left;
}
return $left->rank() >= $right->rank() ? $left : $right;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App;
enum FolderVisibility: string
{
case Private = 'private';
case Workspace = 'workspace';
/**
* Get the human-friendly label for the visibility.
*/
public function label(): string
{
return match ($this) {
self::Private => 'Private',
self::Workspace => 'Shared with workspace',
};
}
/**
* Determine whether a folder at this visibility is opened up to every
* member of its workspace.
*/
public function isSharedWithWorkspace(): bool
{
return $this === self::Workspace;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;
class EnsureAdmin
{
/**
* Restrict access to the site-wide administrator area. Organization
* owners/admins are not site administrators and are rejected here.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
Gate::authorize('accessAdmin');
return $next($request);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Mail;
use App\Models\Invitation;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class InvitationMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*/
public function __construct(public Invitation $invitation) {}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
$inviter = $this->invitation->inviterName();
$name = $this->invitation->inviteableName();
return new Envelope(
subject: $this->invitation->isForFolder()
? __(':inviter shared the folder ":name" with you', ['inviter' => $inviter, 'name' => $name])
: __(':inviter invited you to the ":name" workspace', ['inviter' => $inviter, 'name' => $name]),
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
markdown: 'mail.invitation',
with: [
'inviterName' => $this->invitation->inviterName(),
'inviteableName' => $this->invitation->inviteableName(),
'roleLabel' => $this->invitation->roleLabel(),
'isFolder' => $this->invitation->isForFolder(),
'url' => route('invitations.accept', $this->invitation->token),
],
);
}
/**
* Get the attachments for the message.
*
* @return array<int, Attachment>
*/
public function attachments(): array
{
return [];
}
}
+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.
*/
+24
View File
@@ -5,6 +5,7 @@ namespace App;
enum OrganizationRole: string
{
case Owner = 'owner';
case Admin = 'admin';
case Member = 'member';
/**
@@ -14,7 +15,30 @@ enum OrganizationRole: string
{
return match ($this) {
self::Owner => 'Owner',
self::Admin => 'Admin',
self::Member => 'Member',
};
}
/**
* Determine whether the role may manage the workspace: its members and its
* billing. Owners and admins may; members may not.
*/
public function canManageWorkspace(): bool
{
return in_array($this, [self::Owner, self::Admin], true);
}
/**
* Get the folder role a member of this workspace receives by default on a
* folder shared with the whole workspace. Admins and owners manage folders;
* plain members start as viewers until reassigned on a folder.
*/
public function defaultFolderRole(): FolderRole
{
return match ($this) {
self::Owner, self::Admin => FolderRole::Admin,
self::Member => FolderRole::Viewer,
};
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
class FolderPolicy
{
/**
* Anyone with a role anywhere on the folder's ancestry may see it.
*/
public function view(User $user, Folder $folder): bool
{
return $folder->effectiveRoleFor($user) !== null;
}
/**
* Only workspace admins create folders at the top of a workspace.
*/
public function create(User $user, Organization $organization): bool
{
$role = $this->organizationRoleFor($user, $organization);
return $role !== null && $role->canManageWorkspace();
}
/**
* Folder admins create folders beneath an existing folder.
*/
public function createChild(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
public function update(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
public function delete(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
/**
* Only folder admins invite collaborators and change visibility.
*/
public function manageShares(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
private function organizationRoleFor(User $user, Organization $organization): ?OrganizationRole
{
return OrganizationRole::tryFrom((string) $organization->users()
->where('users.id', $user->id)
->withPivot('role')
->first()?->pivot->role);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
class InvitationPolicy
{
/**
* Inviting people into a folder or workspace is gated by the inviteable's
* own policies.
*/
public function create(User $user, Organization|Folder $inviteable): bool
{
if ($inviteable instanceof Folder) {
return $user->can('manageShares', $inviteable);
}
return $user->can('manageMembers', $inviteable);
}
/**
* The invitation may be revoked by whoever sent it or by an admin of the
* thing it invites into.
*/
public function delete(User $user, Invitation $invitation): bool
{
return $user->id === $invitation->inviter_id
|| $user->can('delete', $invitation->inviteable);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Policies;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
class OrganizationPolicy
{
public function view(User $user, Organization $organization): bool
{
return $this->roleFor($user, $organization) !== null;
}
public function update(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
public function manageMembers(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
public function manageBilling(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
/**
* Only the owner may dissolve a workspace.
*/
public function delete(User $user, Organization $organization): bool
{
return $this->roleFor($user, $organization) === OrganizationRole::Owner;
}
private function roleFor(User $user, Organization $organization): ?OrganizationRole
{
return OrganizationRole::tryFrom((string) $organization->users()
->where('users.id', $user->id)
->withPivot('role')
->first()?->pivot->role);
}
private function canManage(User $user, Organization $organization): bool
{
return $user->isOrganizationAdmin($organization);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Todo;
use App\Models\User;
class TodoPolicy
{
public function view(User $user, Todo $todo): bool
{
return $todo->folder?->effectiveRoleFor($user) !== null;
}
/**
* Workspace folders are shared with editors so they can add todos to them.
*/
public function create(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canEditTodos();
}
public function update(User $user, Todo $todo): bool
{
return $this->canEdit($user, $todo);
}
public function delete(User $user, Todo $todo): bool
{
return $this->canEdit($user, $todo);
}
/**
* Markers and above may flip a todo's completion state.
*/
public function markComplete(User $user, Todo $todo): bool
{
$role = $todo->folder?->effectiveRoleFor($user);
return $role !== null && $role->canMarkComplete();
}
private function canEdit(User $user, Todo $todo): bool
{
$role = $todo->folder?->effectiveRoleFor($user);
return $role !== null && $role->canEditTodos();
}
}
+13
View File
@@ -4,9 +4,11 @@ namespace App\Providers;
use App\Http\Responses\RegisterResponse;
use App\Models\Organization;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier;
@@ -41,6 +43,17 @@ class AppServiceProvider extends ServiceProvider
{
$this->configureDefaults();
$this->configureCashier();
$this->defineGates();
}
/**
* Define the site-wide administrator ability. This is deliberately separate
* from an organization's Owner/Admin roles, which only ever grant rights
* inside a single workspace.
*/
protected function defineGates(): void
{
Gate::define('accessAdmin', fn (User $user): bool => $user->isSiteAdmin());
}
/**
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App;
enum WorkspaceType: string
{
case Personal = 'personal';
case Family = 'family';
case Organization = 'organization';
/**
* Get the human-friendly label for the workspace type.
*/
public function label(): string
{
return match ($this) {
self::Personal => 'Personal',
self::Family => 'Family',
self::Organization => 'Organization',
};
}
/**
* Get the visibility a new top-level folder receives by default in this
* kind of workspace. Personal workspaces are single-user, so their folders
* start private; family and organization folders are shared with every
* member until an admin narrows them.
*/
public function defaultFolderVisibility(): FolderVisibility
{
return match ($this) {
self::Personal => FolderVisibility::Private,
self::Family, self::Organization => FolderVisibility::Workspace,
};
}
/**
* Determine whether folders in this workspace are shared with members by
* default.
*/
public function sharesByDefault(): bool
{
return $this !== self::Personal;
}
}