From 177f122c109775d5d132fb29dc81d83934007c76 Mon Sep 17 00:00:00 2001 From: Eric Downing Date: Thu, 15 Oct 2026 20:59:32 -0700 Subject: [PATCH] added roles and organizations --- app/Console/Commands/SeedLoadTestData.php | 510 ++++++++ app/Console/Commands/TransferSqliteData.php | 76 +- app/FolderRole.php | 91 ++ app/FolderVisibility.php | 29 + app/Http/Middleware/EnsureAdmin.php | 24 + app/Mail/InvitationMail.php | 63 + app/Models/Folder.php | 264 +++- app/Models/Invitation.php | 242 ++++ app/Models/Organization.php | 76 +- app/Models/Todo.php | 44 +- app/Models/User.php | 33 +- app/OrganizationRole.php | 24 + app/Policies/FolderPolicy.php | 71 + app/Policies/InvitationPolicy.php | 34 + app/Policies/OrganizationPolicy.php | 51 + app/Policies/TodoPolicy.php | 52 + app/Providers/AppServiceProvider.php | 13 + app/WorkspaceType.php | 45 + bootstrap/app.php | 2 + config/workspaces.php | 20 + database/factories/FolderFactory.php | 34 + database/factories/InvitationFactory.php | 84 ++ database/factories/OrganizationFactory.php | 14 + ...214840_add_type_to_organizations_table.php | 30 + ...add_workspace_columns_to_folders_table.php | 40 + ...842_add_organization_id_to_todos_table.php | 37 + ..._10_10_214843_create_folder_user_table.php | 33 + ..._10_10_214844_create_invitations_table.php | 40 + ...0_214846_backfill_workspace_membership.php | 53 + ...214847_make_workspace_columns_not_null.php | 39 + database/seeders/BaseDatabaseSeeder.php | 10 +- database/seeders/DatabaseSeeder.php | 21 +- load-tests/app.js | 528 ++++++++ load-tests/sessions.json | 1161 +++++++++++++++++ resources/views/components/app-logo.blade.php | 2 + resources/views/layouts/app/header.blade.php | 6 + resources/views/layouts/app/sidebar.blade.php | 7 +- resources/views/mail/invitation.blade.php | 16 + .../pages/admin/⚡notes-limits.blade.php | 85 +- .../pages/admin/⚡plan-pricing.blade.php | 7 +- .../pages/invitations/⚡accept.blade.php | 82 ++ .../views/pages/workspace/⚡members.blade.php | 334 +++++ resources/views/pages/⚡dashboard.blade.php | 145 +- resources/views/pages/⚡folders.blade.php | 578 ++++++-- resources/views/pages/⚡todos.blade.php | 139 +- routes/web.php | 14 +- tests/Feature/AdminNotesLimitsTest.php | 103 ++ tests/Feature/BaseDataSeederTest.php | 2 +- tests/Feature/Billing/PlanPricingTest.php | 33 + tests/Feature/FolderAccessTest.php | 276 ++++ tests/Feature/FolderSharingTest.php | 137 ++ tests/Feature/FoldersTest.php | 19 + tests/Feature/InvitationAcceptPageTest.php | 103 ++ tests/Feature/InvitationTest.php | 177 +++ tests/Feature/SharedAccessPagesTest.php | 180 +++ tests/Feature/WorkspaceMembersTest.php | 151 +++ tests/Feature/WorkspaceTest.php | 141 ++ 57 files changed, 6378 insertions(+), 247 deletions(-) create mode 100644 app/Console/Commands/SeedLoadTestData.php create mode 100644 app/FolderRole.php create mode 100644 app/FolderVisibility.php create mode 100644 app/Http/Middleware/EnsureAdmin.php create mode 100644 app/Mail/InvitationMail.php create mode 100644 app/Models/Invitation.php create mode 100644 app/Policies/FolderPolicy.php create mode 100644 app/Policies/InvitationPolicy.php create mode 100644 app/Policies/OrganizationPolicy.php create mode 100644 app/Policies/TodoPolicy.php create mode 100644 app/WorkspaceType.php create mode 100644 config/workspaces.php create mode 100644 database/factories/InvitationFactory.php create mode 100644 database/migrations/2026_10_10_214840_add_type_to_organizations_table.php create mode 100644 database/migrations/2026_10_10_214841_add_workspace_columns_to_folders_table.php create mode 100644 database/migrations/2026_10_10_214842_add_organization_id_to_todos_table.php create mode 100644 database/migrations/2026_10_10_214843_create_folder_user_table.php create mode 100644 database/migrations/2026_10_10_214844_create_invitations_table.php create mode 100644 database/migrations/2026_10_10_214846_backfill_workspace_membership.php create mode 100644 database/migrations/2026_10_10_214847_make_workspace_columns_not_null.php create mode 100644 load-tests/app.js create mode 100644 load-tests/sessions.json create mode 100644 resources/views/mail/invitation.blade.php create mode 100644 resources/views/pages/invitations/⚡accept.blade.php create mode 100644 resources/views/pages/workspace/⚡members.blade.php create mode 100644 tests/Feature/FolderAccessTest.php create mode 100644 tests/Feature/FolderSharingTest.php create mode 100644 tests/Feature/InvitationAcceptPageTest.php create mode 100644 tests/Feature/InvitationTest.php create mode 100644 tests/Feature/SharedAccessPagesTest.php create mode 100644 tests/Feature/WorkspaceMembersTest.php create mode 100644 tests/Feature/WorkspaceTest.php diff --git a/app/Console/Commands/SeedLoadTestData.php b/app/Console/Commands/SeedLoadTestData.php new file mode 100644 index 0000000..87381c4 --- /dev/null +++ b/app/Console/Commands/SeedLoadTestData.php @@ -0,0 +1,510 @@ + + */ + 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 + */ + 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, folderIds: list}> + */ + 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 + */ + 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 + */ + 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 $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 + */ + 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 $folderIds + * @return list + */ + 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 $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; + } +} diff --git a/app/Console/Commands/TransferSqliteData.php b/app/Console/Commands/TransferSqliteData.php index fbd7442..b8b4701 100644 --- a/app/Console/Commands/TransferSqliteData.php +++ b/app/Console/Commands/TransferSqliteData.php @@ -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 $rows + * @return list> + */ + 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. diff --git a/app/FolderRole.php b/app/FolderRole.php new file mode 100644 index 0000000..2de2dea --- /dev/null +++ b/app/FolderRole.php @@ -0,0 +1,91 @@ + '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 + */ + 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; + } +} diff --git a/app/FolderVisibility.php b/app/FolderVisibility.php new file mode 100644 index 0000000..af40652 --- /dev/null +++ b/app/FolderVisibility.php @@ -0,0 +1,29 @@ + '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; + } +} diff --git a/app/Http/Middleware/EnsureAdmin.php b/app/Http/Middleware/EnsureAdmin.php new file mode 100644 index 0000000..a79e455 --- /dev/null +++ b/app/Http/Middleware/EnsureAdmin.php @@ -0,0 +1,24 @@ +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 + */ + public function attachments(): array + { + return []; + } +} diff --git a/app/Models/Folder.php b/app/Models/Folder.php index b1737ef..36b0d07 100644 --- a/app/Models/Folder.php +++ b/app/Models/Folder.php @@ -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 $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 */ @@ -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 + */ + 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 { @@ -57,6 +116,20 @@ class Folder extends Model 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. * @@ -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 $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"). @@ -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 + */ + 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, $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; diff --git a/app/Models/Invitation.php b/app/Models/Invitation.php new file mode 100644 index 0000000..bf68d08 --- /dev/null +++ b/app/Models/Invitation.php @@ -0,0 +1,242 @@ + */ + 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 */ + public function inviteable(): MorphTo + { + return $this->morphTo(); + } + + /** @return BelongsTo */ + public function inviter(): BelongsTo + { + return $this->belongsTo(User::class, 'inviter_id'); + } + + /** @return BelongsTo */ + public function acceptedBy(): BelongsTo + { + return $this->belongsTo(User::class, 'accepted_by_id'); + } + + /** + * Get the attributes that should be cast. + * + * @return array + */ + 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 $query + * @return Builder + */ + 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(); + } +} diff --git a/app/Models/Organization.php b/app/Models/Organization.php index b23ff90..f14f050 100644 --- a/app/Models/Organization.php +++ b/app/Models/Organization.php @@ -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 + */ + public function folders(): HasMany + { + return $this->hasMany(Folder::class); + } + + /** + * @return MorphMany + */ + 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. diff --git a/app/Models/Todo.php b/app/Models/Todo.php index 47c6a23..ff3854d 100644 --- a/app/Models/Todo.php +++ b/app/Models/Todo.php @@ -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 */ 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 */ public function user(): BelongsTo { return $this->belongsTo(User::class); } + /** @return BelongsTo */ + public function organization(): BelongsTo + { + return $this->belongsTo(Organization::class); + } + /** @return BelongsTo */ 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 $query + * @return Builder + */ + 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; } diff --git a/app/Models/User.php b/app/Models/User.php index e18c1b6..106eb25 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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 + */ + 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. */ diff --git a/app/OrganizationRole.php b/app/OrganizationRole.php index 312d059..4a9b4c6 100644 --- a/app/OrganizationRole.php +++ b/app/OrganizationRole.php @@ -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, + }; + } } diff --git a/app/Policies/FolderPolicy.php b/app/Policies/FolderPolicy.php new file mode 100644 index 0000000..f590fe5 --- /dev/null +++ b/app/Policies/FolderPolicy.php @@ -0,0 +1,71 @@ +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); + } +} diff --git a/app/Policies/InvitationPolicy.php b/app/Policies/InvitationPolicy.php new file mode 100644 index 0000000..9168433 --- /dev/null +++ b/app/Policies/InvitationPolicy.php @@ -0,0 +1,34 @@ +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); + } +} diff --git a/app/Policies/OrganizationPolicy.php b/app/Policies/OrganizationPolicy.php new file mode 100644 index 0000000..a048bb3 --- /dev/null +++ b/app/Policies/OrganizationPolicy.php @@ -0,0 +1,51 @@ +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); + } +} diff --git a/app/Policies/TodoPolicy.php b/app/Policies/TodoPolicy.php new file mode 100644 index 0000000..4d0fcca --- /dev/null +++ b/app/Policies/TodoPolicy.php @@ -0,0 +1,52 @@ +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(); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 6476541..c6c5bf7 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -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()); } /** diff --git a/app/WorkspaceType.php b/app/WorkspaceType.php new file mode 100644 index 0000000..2039570 --- /dev/null +++ b/app/WorkspaceType.php @@ -0,0 +1,45 @@ + '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; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index fbac45e..0432340 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ withMiddleware(function (Middleware $middleware): void { $middleware->alias([ + 'admin' => EnsureAdmin::class, 'subscribed' => EnsureSubscribed::class, ]); diff --git a/config/workspaces.php b/config/workspaces.php new file mode 100644 index 0000000..129217e --- /dev/null +++ b/config/workspaces.php @@ -0,0 +1,20 @@ + [ + 'personal' => 1, + 'family' => 6, + 'organization' => null, + ], +]; diff --git a/database/factories/FolderFactory.php b/database/factories/FolderFactory.php index 9205704..6cbde3f 100644 --- a/database/factories/FolderFactory.php +++ b/database/factories/FolderFactory.php @@ -2,7 +2,9 @@ namespace Database\Factories; +use App\FolderVisibility; use App\Models\Folder; +use App\Models\Organization; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; @@ -36,4 +38,36 @@ class FolderFactory extends Factory 'user_id' => $folder->user_id, ]); } + + /** + * Indicate that the folder sits in the given organization, inheriting the + * visibility the workspace defaults to. + */ + public function inOrganization(Organization $organization): static + { + return $this->state(fn (array $attributes) => [ + 'organization_id' => $organization->id, + 'visibility' => Folder::defaultVisibilityFor($organization->id), + ]); + } + + /** + * Indicate that the folder is shared with everyone in its workspace. + */ + public function sharedWithWorkspace(): static + { + return $this->state(fn (array $attributes) => [ + 'visibility' => FolderVisibility::Workspace, + ]); + } + + /** + * Indicate that the folder is only visible to people it is shared with. + */ + public function private(): static + { + return $this->state(fn (array $attributes) => [ + 'visibility' => FolderVisibility::Private, + ]); + } } diff --git a/database/factories/InvitationFactory.php b/database/factories/InvitationFactory.php new file mode 100644 index 0000000..e2cefe7 --- /dev/null +++ b/database/factories/InvitationFactory.php @@ -0,0 +1,84 @@ + + */ +class InvitationFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'inviter_id' => User::factory(), + 'email' => fake()->unique()->safeEmail(), + 'role' => FolderRole::Viewer->value, + 'inviteable_type' => Folder::class, + 'inviteable_id' => Folder::factory(), + 'token' => Str::random(64), + 'expires_at' => now()->addDays(7), + 'accepted_at' => null, + 'accepted_by_id' => null, + ]; + } + + /** + * Indicate that the invitation invites someone into a folder. + */ + public function forFolder(Folder $folder, FolderRole $role = FolderRole::Viewer): static + { + return $this->state(fn (array $attributes) => [ + 'inviteable_type' => Folder::class, + 'inviteable_id' => $folder->id, + 'role' => $role->value, + ]); + } + + /** + * Indicate that the invitation invites someone into a workspace. + */ + public function forOrganization(Organization $organization, string $role = 'member'): static + { + return $this->state(fn (array $attributes) => [ + 'inviteable_type' => Organization::class, + 'inviteable_id' => $organization->id, + 'role' => $role, + ]); + } + + /** + * Indicate that the invitation has been redeemed. + */ + public function accepted(): static + { + return $this->afterCreating(function (Invitation $invitation): void { + $invitation->accepted_at = Carbon::now(); + $invitation->accepted_by_id = $invitation->accepted_by_id ?? $invitation->inviter_id; + $invitation->save(); + }); + } + + /** + * Indicate that the invitation has lapsed. + */ + public function expired(): static + { + return $this->state(fn (array $attributes) => [ + 'expires_at' => now()->subDay(), + ]); + } +} diff --git a/database/factories/OrganizationFactory.php b/database/factories/OrganizationFactory.php index 56f1b87..0b1a8c3 100644 --- a/database/factories/OrganizationFactory.php +++ b/database/factories/OrganizationFactory.php @@ -5,6 +5,7 @@ namespace Database\Factories; use App\Models\Organization; use App\Models\User; use App\OrganizationRole; +use App\WorkspaceType; use Illuminate\Database\Eloquent\Factories\Factory; /** @@ -21,6 +22,7 @@ class OrganizationFactory extends Factory { return [ 'name' => fake()->unique()->company(), + 'type' => WorkspaceType::Organization, 'personal_workspace' => false, 'lifetime_access' => false, ]; @@ -32,10 +34,22 @@ class OrganizationFactory extends Factory public function personal(): static { return $this->state(fn (array $attributes) => [ + 'type' => WorkspaceType::Personal, 'personal_workspace' => true, ]); } + /** + * Indicate that the organization is a shared family workspace. + */ + public function family(): static + { + return $this->state(fn (array $attributes) => [ + 'type' => WorkspaceType::Family, + 'personal_workspace' => false, + ]); + } + /** * Give the organization perpetual access, as granted to accounts that * predate subscriptions. diff --git a/database/migrations/2026_10_10_214840_add_type_to_organizations_table.php b/database/migrations/2026_10_10_214840_add_type_to_organizations_table.php new file mode 100644 index 0000000..3261cd0 --- /dev/null +++ b/database/migrations/2026_10_10_214840_add_type_to_organizations_table.php @@ -0,0 +1,30 @@ +string('type')->default('personal')->after('name'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('organizations', function (Blueprint $table) { + $table->dropColumn('type'); + }); + } +}; diff --git a/database/migrations/2026_10_10_214841_add_workspace_columns_to_folders_table.php b/database/migrations/2026_10_10_214841_add_workspace_columns_to_folders_table.php new file mode 100644 index 0000000..cc7c2c0 --- /dev/null +++ b/database/migrations/2026_10_10_214841_add_workspace_columns_to_folders_table.php @@ -0,0 +1,40 @@ +foreignId('organization_id') + ->nullable() + ->after('user_id') + ->constrained() + ->cascadeOnDelete(); + + $table->string('visibility')->default('private')->after('name'); + + $table->index(['organization_id', 'visibility']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('folders', function (Blueprint $table) { + $table->dropIndex(['organization_id', 'visibility']); + $table->dropConstrainedForeignId('organization_id'); + $table->dropColumn('visibility'); + }); + } +}; diff --git a/database/migrations/2026_10_10_214842_add_organization_id_to_todos_table.php b/database/migrations/2026_10_10_214842_add_organization_id_to_todos_table.php new file mode 100644 index 0000000..8d500af --- /dev/null +++ b/database/migrations/2026_10_10_214842_add_organization_id_to_todos_table.php @@ -0,0 +1,37 @@ +foreignId('organization_id') + ->nullable() + ->after('user_id') + ->constrained() + ->cascadeOnDelete(); + + $table->index(['organization_id', 'completed_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('todos', function (Blueprint $table) { + $table->dropIndex(['organization_id', 'completed_at']); + $table->dropConstrainedForeignId('organization_id'); + }); + } +}; diff --git a/database/migrations/2026_10_10_214843_create_folder_user_table.php b/database/migrations/2026_10_10_214843_create_folder_user_table.php new file mode 100644 index 0000000..5405ead --- /dev/null +++ b/database/migrations/2026_10_10_214843_create_folder_user_table.php @@ -0,0 +1,33 @@ +id(); + $table->foreignId('folder_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('role')->default('viewer'); + $table->foreignId('invited_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamps(); + + $table->unique(['folder_id', 'user_id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('folder_user'); + } +}; diff --git a/database/migrations/2026_10_10_214844_create_invitations_table.php b/database/migrations/2026_10_10_214844_create_invitations_table.php new file mode 100644 index 0000000..6afa2f1 --- /dev/null +++ b/database/migrations/2026_10_10_214844_create_invitations_table.php @@ -0,0 +1,40 @@ +id(); + $table->foreignId('inviter_id')->constrained('users')->cascadeOnDelete(); + $table->string('email'); + // Workspace invitations store an OrganizationRole; folder + // invitations store a FolderRole. The inviteable type selects + // which role vocabulary applies. + $table->string('role'); + $table->morphs('inviteable'); + $table->string('token', 64)->unique(); + $table->timestamp('expires_at')->nullable(); + $table->timestamp('accepted_at')->nullable(); + $table->foreignId('accepted_by_id')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamps(); + + $table->unique(['inviteable_type', 'inviteable_id', 'email']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('invitations'); + } +}; diff --git a/database/migrations/2026_10_10_214846_backfill_workspace_membership.php b/database/migrations/2026_10_10_214846_backfill_workspace_membership.php new file mode 100644 index 0000000..f53d1c7 --- /dev/null +++ b/database/migrations/2026_10_10_214846_backfill_workspace_membership.php @@ -0,0 +1,53 @@ +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" + ), + ]); + } + + /** + * Reverse the migrations. + * + * The organization id is derived from the folder's owner, so nulling it + * out restores the pre-migration state. Visibility is not reverted because + * reverting it would only be guesswork. + */ + public function down(): void + { + DB::table('todos')->update(['organization_id' => null]); + DB::table('folders')->update(['organization_id' => null]); + } +}; diff --git a/database/migrations/2026_10_10_214847_make_workspace_columns_not_null.php b/database/migrations/2026_10_10_214847_make_workspace_columns_not_null.php new file mode 100644 index 0000000..1919135 --- /dev/null +++ b/database/migrations/2026_10_10_214847_make_workspace_columns_not_null.php @@ -0,0 +1,39 @@ +foreignId('organization_id')->nullable(false)->change(); + }); + + Schema::table('todos', function (Blueprint $table) { + $table->foreignId('organization_id')->nullable(false)->change(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('folders', function (Blueprint $table) { + $table->foreignId('organization_id')->nullable()->change(); + }); + + Schema::table('todos', function (Blueprint $table) { + $table->foreignId('organization_id')->nullable()->change(); + }); + } +}; diff --git a/database/seeders/BaseDatabaseSeeder.php b/database/seeders/BaseDatabaseSeeder.php index ea4a100..ad6f257 100644 --- a/database/seeders/BaseDatabaseSeeder.php +++ b/database/seeders/BaseDatabaseSeeder.php @@ -21,9 +21,15 @@ class BaseDatabaseSeeder extends Seeder ], ); + // The organization is created by the model's created hook, which is + // silenced while run under a parent seeder using WithoutModelEvents, + // so create one here when needed. + if ($admin->currentOrganization()->first() === null) { + $admin->createPersonalOrganization(); + } + // Grandfather the admin so a fresh install is usable before any Stripe - // price is configured. The organization itself is created by the - // model's created hook. + // price is configured. $admin->currentOrganization()->first()?->forceFill([ 'lifetime_access' => true, ])->save(); diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 8dc388b..00cb624 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -29,6 +29,12 @@ class DatabaseSeeder extends Seeder ], ); + // Model events are disabled while seeding, so the created hook that + // normally hands every account its personal workspace does not run. + if ($user->current_organization_id === null) { + $user->createPersonalOrganization(); + } + $work = $this->createTopLevelFolder($user, 'Work'); $business = $this->createTopLevelFolder($user, 'Business'); $personal = $this->createTopLevelFolder($user, 'Personal'); @@ -69,7 +75,10 @@ class DatabaseSeeder extends Seeder foreach ($samples as [$description, $folderName, $daysFromToday, $status]) { $todo = Todo::firstOrCreate( ['user_id' => $user->id, 'folder_id' => $foldersByName[$folderName]->id, 'description' => $description], - ['status' => TodoStatus::Open], + [ + 'status' => TodoStatus::Open, + 'organization_id' => $foldersByName[$folderName]->organization_id, + ], ); if ($daysFromToday === null) { @@ -97,7 +106,10 @@ class DatabaseSeeder extends Seeder { return Folder::firstOrCreate( ['user_id' => $user->id, 'name' => $name, 'parent_id' => null], - ['color' => fake()->optional()->randomElement(Folder::COLORS)], + [ + 'organization_id' => $user->current_organization_id, + 'color' => fake()->optional()->randomElement(Folder::COLORS), + ], ); } @@ -105,7 +117,10 @@ class DatabaseSeeder extends Seeder { return Folder::firstOrCreate( ['user_id' => $parent->user_id, 'name' => $name, 'parent_id' => $parent->id], - ['color' => fake()->optional()->randomElement(Folder::COLORS)], + [ + 'organization_id' => $parent->organization_id, + 'color' => fake()->optional()->randomElement(Folder::COLORS), + ], ); } } diff --git a/load-tests/app.js b/load-tests/app.js new file mode 100644 index 0000000..be070f6 --- /dev/null +++ b/load-tests/app.js @@ -0,0 +1,528 @@ +/** + * Throughput and concurrency load tests for mytodos. + * + * The application is entirely Blade + Livewire with no API surface, so the + * dominant real-world cost is the POST to Livewire's update endpoint rather + * than the page GET that precedes it. Any test that only loads pages + * understates load by roughly an order of magnitude, because a single page view + * is normally followed by a burst of update round-trips: search is bound to a + * 300ms debounce, folders render on expand, and toggles each commit. + * + * Snapshots are captured from real pages and replayed. They cannot be + * synthesised, because Livewire signs every snapshot with + * hash_hmac('sha256', json_encode($snapshot), APP_KEY). A generator that + * invents snapshots is also self-defeating: the checksum guard locks out an IP + * after ten bad payloads in ten minutes, which would invalidate the whole run. + * + * Run one scenario at a time so the numbers stay attributable: + * + * SCENARIOS=page_load VUS=25 DURATION=2m k6 run load-tests/app.js + * + * Then step VUS upward until the p95 breaches the SLO. The driver script + * load-tests/ramp.sh does that sweep and collects the results. + */ + +import http from 'k6/http'; +import exec from 'k6/execution'; +import { check } from 'k6'; +import { Counter, Rate, Trend } from 'k6/metrics'; + +const BASE_URL = (__ENV.BASE_URL || 'http://mytodos.test').replace(/\/$/, ''); +const VUS = parseInt(__ENV.VUS || '25', 10); +const DURATION = __ENV.DURATION || '2m'; +const LABEL = __ENV.LABEL || `vus-${VUS}`; + +const ALL_SCENARIOS = [ + 'anon', + 'page_load', + 'livewire_read', + 'livewire_write', + 'folders_read', + 'folders_write', + 'admin', +]; + +const ENABLED = (__ENV.SCENARIOS || ALL_SCENARIOS.join(',')) + .split(',') + .map((name) => name.trim()) + .filter((name) => ALL_SCENARIOS.indexOf(name) !== -1); + +if (ENABLED.length === 0) { + throw new Error(`SCENARIOS must name at least one of: ${ALL_SCENARIOS.join(', ')}`); +} + +/** + * Read the session manifest written by `php artisan app:seed-load-test`. + * + * Each entry already carries the encrypted session cookie, because + * EncryptCookies wraps cookie values in an HMAC prefix and then encrypts them. + * A bare session id is rejected by the framework. + */ +const sessions = JSON.parse(open('./sessions.json')); +const userSessions = sessions.filter((s) => !s.isAdmin); +const adminSessions = sessions.filter((s) => s.isAdmin); + +/** + * Pair a latency trend with a request counter. + * + * A Trend's summary values carry percentiles but no sample count, and the count + * is what throughput is derived from, so each scenario needs both. + */ +function scenarioMetrics(name) { + return { + trend: new Trend(`${name}_latency`, true), + counter: new Counter(`${name}_requests`), + }; +} + +const METRICS = { + anon: scenarioMetrics('anon'), + page_load: scenarioMetrics('page_load'), + livewire_read: scenarioMetrics('livewire_read'), + livewire_write: scenarioMetrics('livewire_write'), + folders_read: scenarioMetrics('folders_read'), + folders_write: scenarioMetrics('folders_write'), + admin: scenarioMetrics('admin'), +}; + +const failures = new Rate('functional_failures'); +const serverErrors = new Counter('server_errors'); +const checksumRejects = new Counter('checksum_rejects'); + +/** + * Record one successful request against a scenario's metrics. + */ +function record(name, durationMs) { + METRICS[name].trend.add(durationMs); + METRICS[name].counter.add(1); + failures.add(false); +} + +// Service level objectives the ramp is looking for a breach of. +const SLO_P95_MS = parseInt(__ENV.SLO_P95_MS || '1000', 10); +const SLO_ERROR_RATE = parseFloat(__ENV.SLO_ERROR_RATE || '0.01'); + +export const options = { + discardResponseBodies: false, + // p99 is not in k6's default summary set, and it is the number that exposes + // a tail growing long before the mean moves. + summaryTrendStats: ['avg', 'min', 'med', 'max', 'p(50)', 'p(90)', 'p(95)', 'p(99)'], + scenarios: ENABLED.reduce((acc, name) => { + acc[name] = { + executor: 'constant-vus', + vus: VUS, + duration: DURATION, + exec: name, + tags: { scenario: name }, + }; + return acc; + }, {}), + thresholds: { + functional_failures: [`rate<${SLO_ERROR_RATE}`], + }, +}; + +/** + * Choose the session a VU always authenticates as. + * + * Pinning each VU to one account keeps a single session cookie hot for the + * whole run and spreads load across accounts, which is closer to real use than + * re-authenticating on every iteration. + */ +function sessionFor(pool, vuId) { + if (pool.length === 0) { + throw new Error('The session manifest has no usable sessions. Run php artisan app:seed-load-test first.'); + } + return pool[(vuId - 1) % pool.length]; +} + +function authHeaders(session) { + return { + Cookie: `${session.cookieName}=${session.cookie}`, + Accept: 'text/html,application/xhtml+xml', + }; +} + +function livewireHeaders(session, page) { + return { + Cookie: `${session.cookieName}=${session.cookie}`, + 'Content-Type': 'application/json', + 'X-Livewire': '1', + 'X-CSRF-TOKEN': page.csrf, + Accept: 'application/json', + }; +} + +/** + * Pull the three values a Livewire round-trip needs out of a rendered page: + * the signed snapshot, the CSRF token and the update endpoint URL. + */ +function parsePage(body) { + const snapshot = /wire:snapshot="([^"]*)"/.exec(body); + const csrf = /data-csrf="([^"]*)"/.exec(body); + const uri = /data-update-uri="([^"]*)"/.exec(body); + + if (!snapshot || !csrf || !uri) { + throw new Error('Could not find the Livewire snapshot, CSRF token or update URI in the response.'); + } + + return { + snapshot: htmlDecode(snapshot[1]), + csrf: csrf[1], + uri: uri[1], + }; +} + +/** + * Blade escapes attribute values, so the snapshot arrives HTML-escaped inside + * the wire:snapshot attribute. + */ +function htmlDecode(value) { + return value + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/&/g, '&'); +} + +/** + * Load a page and remember the session context for later update calls. + * + * Cached per VU because the update scenarios chain snapshots: each response + * carries the next valid snapshot, so refetching every iteration would measure + * page loads rather than the update path. + */ +function loadPage(pool, path) { + const session = sessionFor(pool, exec.vu.idInTest); + + const response = http.get(BASE_URL + path, { + headers: authHeaders(session), + tags: { name: path, step: 'page' }, + }); + + const ok = check(response, { + 'page returned 200': (r) => r.status === 200, + 'page is not the paywall redirect': (r) => r.status !== 302, + }); + + if (!ok) { + failures.add(true); + serverErrors.add(1); + throw new Error(`${path} returned ${response.status}`); + } + + const page = parsePage(response.body); + page.timing = response.timings.duration; + + return { session, path, ...page }; +} + +/** + * Post one Livewire update, chaining the returned snapshot for the next call. + */ +function sendUpdate(page, scenario, updates, calls) { + const payload = JSON.stringify({ + components: [ + { + snapshot: page.snapshot, + updates: updates || {}, + // Livewire 4 validates that every call carries a method string and a + // params array, and rejects the whole payload with a 500 otherwise. + calls: (calls || []).map((call) => ({ + path: '', + method: call.method, + params: call.params || [], + })), + }, + ], + }); + + const response = http.post(page.uri, payload, { + headers: livewireHeaders(page.session, page), + tags: { name: page.path, step: 'update' }, + }); + + if (response.status !== 200) { + failures.add(true); + serverErrors.add(1); + + if (response.status === 429) { + checksumRejects.add(1); + } + + throw new Error(`Livewire update to ${page.path} returned ${response.status}`); + } + + let body; + + try { + body = JSON.parse(response.body); + } catch (e) { + failures.add(true); + throw new Error(`Livewire update to ${page.path} did not return JSON`); + } + + const component = body.components && body.components[0]; + + if (!component || !component.snapshot) { + failures.add(true); + throw new Error(`Livewire update to ${page.path} returned no snapshot`); + } + + // The response snapshot is the only one valid for the next request. + page.snapshot = component.snapshot; + + record(scenario, response.timings.duration); + + return response; +} + +export function anon() { + for (const path of ['/', '/pricing']) { + const response = http.get(BASE_URL + path, { tags: { name: path } }); + const ok = check(response, { 'anonymous page returned 200': (r) => r.status === 200 }); + + if (!ok) { + failures.add(true); + serverErrors.add(1); + } else { + record('anon', response.timings.duration); + } + } +} + +export function page_load() { + // Rotate through the three authenticated pages a user actually navigates + // between, so the reported number is not the mean of one page's cost. + const page = loadPage(userSessions, PAGE_LOAD_PATHS[exec.scenario.iterationInTest % PAGE_LOAD_PATHS.length]); + record('page_load', page.timing); +} + +export function livewire_read() { + const page = getTodosContext(); + const step = exec.scenario.iterationInTest % 4; + + if (step === 0) { + // The search box is bound to a 300ms debounce, so every few keystrokes of + // a real search session produce one of these. It is also the only query in + // the app whose predicate cannot use an index. + const term = SEARCH_TERMS[exec.scenario.iterationInTest % SEARCH_TERMS.length]; + sendUpdate(page, 'livewire_read', { search: term }, []); + } else if (step === 1) { + sendUpdate(page, 'livewire_read', {}, [{ method: 'resetFilters' }]); + } else if (step === 2) { + const status = STATUS_FILTERS[exec.scenario.iterationInTest % STATUS_FILTERS.length]; + sendUpdate(page, 'livewire_read', { status }, []); + } else { + // Paginates one more page, which re-runs the filtered COUNT(*). + sendUpdate(page, 'livewire_read', {}, [{ method: 'loadMore' }]); + } +} + +export function livewire_write() { + const page = getTodosContext(); + const session = page.session; + const todoId = session.todoIds[exec.scenario.iterationInTest % session.todoIds.length]; + + sendUpdate(page, 'livewire_write', {}, [{ method: 'toggleComplete', params: [todoId] }]); +} + +export function folders_read() { + const page = getFoldersContext(); + const folderIds = page.session.folderIds; + + // A fresh id every time means the component always expands rather than + // toggling shut, so every iteration pays the per-folder todo query. + const folderId = folderIds[exec.scenario.iterationInTest % folderIds.length]; + + sendUpdate(page, 'folders_read', {}, [{ method: 'toggleExpandFolder', params: [folderId] }]); +} + +export function folders_write() { + const page = getFoldersContext(); + const session = page.session; + const todoId = session.todoIds[exec.scenario.iterationInTest % session.todoIds.length]; + const folderId = session.folderIds[exec.scenario.iterationInTest % session.folderIds.length]; + + sendUpdate(page, 'folders_write', {}, [ + { method: 'moveTodoToFolder', params: [todoId, folderId] }, + ]); +} + +export function admin() { + const pool = adminSessions.length > 0 ? adminSessions : userSessions; + const response = http.get(BASE_URL + '/admin/notes-limits', { + headers: authHeaders(sessionFor(pool, exec.vu.idInTest)), + tags: { name: '/admin/notes-limits' }, + }); + + const ok = check(response, { 'admin page returned 200': (r) => r.status === 200 }); + + if (!ok) { + failures.add(true); + serverErrors.add(1); + } else { + record('admin', response.timings.duration); + } +} + +/** + * Search terms, including one that matches nothing, so the LIKE predicate is + * exercised against both a matching and a full-scan outcome. + */ +const SEARCH_TERMS = ['invoice', 'review', 'the', 'a', 'zzznomatch', 'team', 'update', '']; +const STATUS_FILTERS = ['open', 'completed', 'overdue', 'all']; +const PAGE_LOAD_PATHS = ['/dashboard', '/todos', '/folders']; + +/** + * Per-VU snapshot chains. Each VU gets its own module instance, so these are + * private to that VU and survive across its iterations. + */ +let todosContext = null; +let foldersContext = null; + +function getTodosContext() { + if (todosContext === null) { + todosContext = loadPage(userSessions, '/todos'); + } + return todosContext; +} + +function getFoldersContext() { + if (foldersContext === null) { + foldersContext = loadPage(userSessions, '/folders'); + } + return foldersContext; +} + +/** + * Turn the run into the number the question actually asks for: how many + * concurrent users this workload supports. + * + * Little's Law gives that directly. With a stable arrival rate, the mean number + * of requests resident in the system equals the arrival rate times the mean + * time each spends there, so: + * + * concurrent users = throughput (req/s) x mean response time (s) + * + * Note this is a floor derived from the offered load. Once the server is + * saturated, response time grows in step with offered concurrency, so the + * product stops growing too. That is why the SLO breach, not the product, is + * the signal to stop ramping. + */ +function capacityFor(metrics, scenario, durationSeconds) { + const trend = metrics[METRICS[scenario].trend.name]; + const counter = metrics[METRICS[scenario].counter.name]; + + if (!trend || !counter || !durationSeconds) { + return null; + } + + const count = counter.values.count; + const values = trend.values; + + if (!count) { + return null; + } + + const rps = count / durationSeconds; + const meanSeconds = values.avg / 1000; + + return { + requests: count, + rps: round(rps, 2), + meanMs: round(values.avg, 1), + p50Ms: round(values.med, 1), + p95Ms: round(values['p(95)'], 1), + p99Ms: round(values['p(99)'], 1), + maxMs: round(values.max, 1), + concurrentUsers: round(rps * meanSeconds, 1), + breachesP95: values['p(95)'] > SLO_P95_MS, + }; +} + +function round(value, places) { + const factor = Math.pow(10, places); + return Math.round(value * factor) / factor; +} + +export function handleSummary(data) { + const durationSeconds = (data.state.testRunDurationMs || 0) / 1000; + const rows = []; + + for (const name of ENABLED) { + rows.push({ scenario: name, ...(capacityFor(data.metrics, name, durationSeconds) || { error: 'no samples' }) }); + } + + const errorRate = data.metrics.functional_failures + ? data.metrics.functional_failures.values.rate + : 0; + + const missing = rows.filter((row) => row.error); + const breached = rows.filter((row) => row.breachesP95); + const saturated = errorRate >= SLO_ERROR_RATE; + + const lines = []; + lines.push(''); + lines.push(`label ${LABEL}`); + lines.push(`base url ${BASE_URL}`); + lines.push(`vus/scenario ${VUS}`); + lines.push(`duration ${DURATION} (measured ${round(durationSeconds, 1)}s)`); + lines.push(`error rate ${round(errorRate * 100, 2)}% (SLO < ${SLO_ERROR_RATE * 100}%)`); + lines.push(''); + lines.push('scenario rps mean p50 p95 p99 max users p95-ok'); + lines.push('----------------- ------ ------ ----- ----- ----- ----- ------ ------'); + + for (const row of rows) { + if (row.error) { + lines.push(`${row.scenario.padEnd(17)} ${row.error}`); + continue; + } + + lines.push( + [ + row.scenario.padEnd(17), + String(row.rps).padStart(6), + String(row.meanMs).padStart(6), + String(row.p50Ms).padStart(5), + String(row.p95Ms).padStart(5), + String(row.p99Ms).padStart(5), + String(row.maxMs).padStart(5), + String(row.concurrentUsers).padStart(6), + (row.breachesP95 ? 'NO' : 'yes').padStart(6), + ].join(' '), + ); + } + + lines.push(''); + lines.push(`p95 SLO: ${SLO_P95_MS}ms`); + + if (missing.length > 0) { + lines.push(`VERDICT: ${missing.map((r) => r.scenario).join(', ')} produced no samples. Fix the scenario before reading any capacity number from this run.`); + } else if (saturated) { + lines.push(`VERDICT: saturated at ${VUS} VU(s). Throughput is capped by the server, not by the workload.`); + } else if (breached.length > 0) { + lines.push(`VERDICT: ${breached.map((r) => r.scenario).join(', ')} breached the p95 SLO at ${VUS} VU(s). This is the knee.`); + } else { + lines.push(`VERDICT: still within SLO at ${VUS} VU(s). Raise VUS and measure again.`); + } + + const summary = { + label: LABEL, + baseUrl: BASE_URL, + vus: VUS, + durationSeconds: round(durationSeconds, 2), + errorRate: errorRate, + sloP95Ms: SLO_P95_MS, + rows, + }; + + const output = { stdout: lines.join('\n') + '\n' }; + + if (__ENV.RESULTS) { + output[__ENV.RESULTS] = JSON.stringify(summary, null, 2); + } + + return output; +} \ No newline at end of file diff --git a/load-tests/sessions.json b/load-tests/sessions.json new file mode 100644 index 0000000..6deaf32 --- /dev/null +++ b/load-tests/sessions.json @@ -0,0 +1,1161 @@ +[ + { + "userId": 85, + "email": "loadtest00000@loadtest.invalid", + "isAdmin": false, + "sessionId": "5hbBmCGr91lqBYFaS14k3oXhMLIFxAN0qfTbbwI0", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InNieG5NMHNnSnhEbGthbmMxUytCeHc9PSIsInZhbHVlIjoiWjd5RlJmMWVnVGc2RXgvYy9lcjJtTzR0aUlPYmV3UkdGakNtaGhkdnA1YVlzMEFZa01RQm5GUm9MazhmREx2YVJianVGVTd3SURhdVpSd0U3aWpSR1BwdC9ia29tVUQzYnU1dW1KVkNHMGtmNnY4c0w0UkhPNi9NM0NpY3p5TkEiLCJtYWMiOiJiZTY2MGU0ZmY5ZGUxOGZmZWE2ZTdmMzEzZTcxYzZhNWI4MGNlYjhiMzliMWU3ZmQ4Y2NhZTJhNTM1MDY0ZjljIiwidGFnIjoiIn0=", + "todoIds": [ + 717, + 718, + 719, + 720, + 721 + ], + "folderIds": [ + 322, + 323 + ] + }, + { + "userId": 86, + "email": "loadtest00001@loadtest.invalid", + "isAdmin": false, + "sessionId": "3W2hO5sjuXqgLTwwqDR3fC1FTEIo2YUUv7XVyteU", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlFDQkpJZmFwZFRCaVFBYzVQWklDSHc9PSIsInZhbHVlIjoibTlOZ0VLbmVod2QwNSsrK3pDUzlMYmFUNTlyZjZiQ2JheDdhcjA5RFk2MWN3aTkxWFBha1BXNDQyUTdKL1FDREdVYTRQU1FhMG1heDZWQmhqNUwxTlZHUk83dVdNamJFdllyaTVMUThTQlFLTXZMSnhBejhZL1ZzN0liOE02cWoiLCJtYWMiOiI0MmE1MzEwZDY1ZjY5YmZhMjY2Y2ExZjdjN2U4MTdlMDk0YjcxZGJjNjBkOWRlZDQxMjhkNWNmYjgxOWJhMWQ1IiwidGFnIjoiIn0=", + "todoIds": [ + 723, + 724, + 725, + 726, + 727 + ], + "folderIds": [ + 325, + 326 + ] + }, + { + "userId": 87, + "email": "loadtest00002@loadtest.invalid", + "isAdmin": false, + "sessionId": "hK7mxT2Ij3Zuo3mHH128BFdW1TSfs4AgkQAVnxup", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ilp0S2o4cWsvdDVHOC80czRwejIzRnc9PSIsInZhbHVlIjoiVG5qeTJ6TGhxVkMvcXBwOW5JeDdHc1hjY2xJOWpuSTZGTEZiZGUycUtlaDRGdS9vYnJaUkpDZ3E4dVZVWFBOOXFYcXI1cGIyWURsaUlkZ3FRcFFkU2tFYmNYWWNURlY4STNJejhFSWZUTnFnQ1kwUksvT3pmVDI0RHYxSFNFdWkiLCJtYWMiOiIzNzg1ZmEwMWQ2ZDlkNmZmMWU0YjVhMzVkZDE3ZjcwMjMxMjhmZjc5ODBhNGUzZjUzYmM2MzQyZmEzNTgyZmUyIiwidGFnIjoiIn0=", + "todoIds": [ + 729, + 730, + 731, + 732, + 733 + ], + "folderIds": [ + 328, + 329 + ] + }, + { + "userId": 88, + "email": "loadtest00003@loadtest.invalid", + "isAdmin": false, + "sessionId": "URMSGLSePuq7c5fdg17bSmMREGWr7OBCBzYGKZ7T", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlZyREhjSzlLQ3AzZTIwOTdpQ3N2L2c9PSIsInZhbHVlIjoiZVBYMjdkaGZ4UHBUOWF5WEVjeXI0S2tMYnhJRzdtczZsM3Y1Y29CM3NNay93TkNQSnZNcDEwYkZlVGNBeFhySnRYa2RBTUZna1ZpeWJlQUR5UG5iM3Fzd2JzVWRpcmVyRUEva3BoWHJTQzg1N1dvMkp2SVp2eFJiTytycXRHLy8iLCJtYWMiOiJmNTcxNzkzZjc2MjAzOTZkYTRiOTM4ZjBjY2VhM2M0NWNhMjc4YzJhYzFjMzhhMWExNmYyNWQ3MGJiNTU1MmQ0IiwidGFnIjoiIn0=", + "todoIds": [ + 735, + 736, + 737, + 738, + 739 + ], + "folderIds": [ + 331, + 332 + ] + }, + { + "userId": 89, + "email": "loadtest00004@loadtest.invalid", + "isAdmin": false, + "sessionId": "nIExJL2xximz6s8fTyqyCCC7jQcdyWxZ2x5ozUDK", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjdqSjIxQVBoMHJJQVlhenNsNFBjaUE9PSIsInZhbHVlIjoiZTg0TnVMVVZRdkRhWUxKcFFpeGhhaTZwRWJFWE40aFdIMlB4WVM3cnl0OVNVcTNEU0kxV0xEK2ZzWWI0UVBmNHRWZUNnOWx0dk1UNTE1TEJOb1g1ZzR2VnQ3cDRGczJ2QUNHUExOK01URzlBUjJYOHgwMGNhYWpkcDlQeWJBcDAiLCJtYWMiOiIzZWI0NTU5NDc1ZmQ4ZGY2Njg0ZWVkZTdmZWZhMGU0ZmE5ZGZmNjQ0ODE2MWE0Yzk4MWIxMGQ1MmI5MGM1ZWMyIiwidGFnIjoiIn0=", + "todoIds": [ + 741, + 742, + 743, + 744, + 745 + ], + "folderIds": [ + 334, + 335 + ] + }, + { + "userId": 90, + "email": "loadtest00005@loadtest.invalid", + "isAdmin": false, + "sessionId": "qnTsKmTQEksSoGCXEc7fDRk0gevp2HulAHkpRT7V", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImRmRnhoMEVaT3U4cS9XRUJOaEhTQVE9PSIsInZhbHVlIjoiQTVZMjlLbTBLTm9BWUREK0NDcjBNdTc0MEliQXpMZjVKZWUyc1hHTWNQNng3ZzBPUFpwSWdqNXVRL1ZrZFpoQmwzVzc3ZnJ3MWc4TmVubzkvVVlpT0tJc2NRY3FuUmNnNHR3bWVob0s2VTVKcFRsR3hPaXJyM1d2a1FudG9ISloiLCJtYWMiOiI2MmM3NzFkNTBjMmM4OWVkOGFiNWQ2YmMyM2U2MjA0YWMyYTlkOWU4OTQ5MzJhNzlhYzVhMTcxMDQ4NTA5M2U3IiwidGFnIjoiIn0=", + "todoIds": [ + 747, + 748, + 749, + 750, + 751 + ], + "folderIds": [ + 337, + 338 + ] + }, + { + "userId": 91, + "email": "loadtest00006@loadtest.invalid", + "isAdmin": false, + "sessionId": "hdjySh9l1m4IGifoxy6XT9G0K7hM2SAdLIOT6nSD", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImEwa3UrYzh5dlVyaDU5ZURzSFZOTmc9PSIsInZhbHVlIjoiUHF2YjE0TDJUd3QrQXdTVUQ4U0dtZENSYmlJbWh4MzJqZExlRmdlNkVGSU5qR3p1N0FmWE00dVdzdUhVZDQ2Y2pCcTBCMnlGSEErUTE0WmgvTmJ6RjIrVHEzTmJWTzR5MUx6L2FhUnJWOER5SlZza081RTByS1JocW85UjBBWHgiLCJtYWMiOiIwMjI2NGJhZGI5MTQ2NTg4ZTJmODMxOTExNmNiYWM4MzNmZmVlY2U4MDljNjM2NmU5NjgwODk3ZjMxNjA0ZDJmIiwidGFnIjoiIn0=", + "todoIds": [ + 753, + 754, + 755, + 756, + 757 + ], + "folderIds": [ + 340, + 341 + ] + }, + { + "userId": 92, + "email": "loadtest00007@loadtest.invalid", + "isAdmin": false, + "sessionId": "uddQpF4lSFievxBYUpe6mTKdllpnCsON0rflC8jU", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlFpVWdiSXF2eXh3T3IvN0RlUlJDN0E9PSIsInZhbHVlIjoiMDlvNU9USjUrZW9xSzNJSmJnQm5Ta3luWHBrS3RCUVRCcEcrLzgyYmJrSkhZOGdDajhucjBTSFlOL3pPLzRoZ3Z4VVQyYzAzem54VVRSYUViTi9XZnYyajdFcHMwMnVYaUZkOXFiYnBRQTFHa25ybGM0RUlyQVZObGRIOGVMODkiLCJtYWMiOiI1ZGYzMmQ2Y2UyYmM5Y2E3MjllMDU3YzIwZWQxOTgxZjQ1OWQ5NGZlMWYxODg2NGQ5M2UwODlhOGE3NDFmMjkwIiwidGFnIjoiIn0=", + "todoIds": [ + 759, + 760, + 761, + 762, + 763 + ], + "folderIds": [ + 343, + 344 + ] + }, + { + "userId": 93, + "email": "loadtest00008@loadtest.invalid", + "isAdmin": false, + "sessionId": "TLjjJuGKp64UaPOA0uKhVk6oWkiXyEVuLqKLPEgm", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IldEclZsdElFSnA0RlZ5bENuOFFQcEE9PSIsInZhbHVlIjoiVnF0dk0rUTk2d1I1TDNRU21zb2hkTVhJRnBnYjRKVTlPZERUd1NMUW00VGJacXhGZ05DK3lLYmVJeCtPL3cyZkhPZFpaZWQ0WlNvM21vMUhFMG1vbm9CaVVZMzBQQ0E1QzVJbFRDdS9lSWJwM05xbDJCSWhGWDlhZ1lWMmRpaEYiLCJtYWMiOiJhOTNlZjIyNWFiZGVjN2UwZDIxZmRhZWU5YmNkNmE5NDlkNzFlYWNiOTU2NGZlZDcxNjhmZmM0N2EzYzVmOTc3IiwidGFnIjoiIn0=", + "todoIds": [ + 765, + 766, + 767, + 768, + 769 + ], + "folderIds": [ + 346, + 347 + ] + }, + { + "userId": 94, + "email": "loadtest00009@loadtest.invalid", + "isAdmin": false, + "sessionId": "C1XtBXea717JFXArkHXWrqfCrVIeJIA6jpraUzyO", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjZhd3A4bmRxaWFpOTdURXlHOHp1WlE9PSIsInZhbHVlIjoiK3F6bEdVcEtFQVFobVpiRWFhYlA0T29UQUw2WXBGc013L0RpZXVIWmw0ZzVuQWlpVlR6bHhWU0lhYm1kS2lSYnFsVkFKQnFMNDBWNkdGQTRLbkRDRHZ6SGFkWWpxTzZLWDdNZVY0UGhxY1N3aXJTcDM1bVhrNTNBU2xOd1VOT24iLCJtYWMiOiJhZDg5ZmY2M2Y3MzZlN2M2YTdmOGRmN2NhY2IzYWFlODU5MDk4ODk4YWNmNDVjMjRkYzc1YmRmNTVjNWEwZTk3IiwidGFnIjoiIn0=", + "todoIds": [ + 771, + 772, + 773, + 774, + 775 + ], + "folderIds": [ + 349, + 350 + ] + }, + { + "userId": 95, + "email": "loadtest00010@loadtest.invalid", + "isAdmin": false, + "sessionId": "4qsZkRRec9y6XsHuoy2ahZ2qSULXoiwIgQBlDMo1", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImludlJ0aWsxNDlkVkdvY1FDYzFkaGc9PSIsInZhbHVlIjoiOHJTOW1iN04rblZlb1VBQVoxajNWc1BqNVVpZ2M2bGxSekV1VWRTOUxBd2lLNVRFMlA3NGh1ank1N0pwVGNHMEpNdTFETnpDM09jSkRjcU9oT0pNVkIxakw0bXVzZnBhc0JIckJoZUFnYkcrYUJnVUdCTXBmL1B3QVdvNXZyaHQiLCJtYWMiOiJjMDM2ZGVmMjhiYzM5ODM2MzM2YTBiYzc4NzU3NjIzNmU4ZjlkY2YzMWY2YTNhNGViNGQ0MWNkYWRlODMzYTk1IiwidGFnIjoiIn0=", + "todoIds": [ + 777, + 778, + 779, + 780, + 781 + ], + "folderIds": [ + 352, + 353 + ] + }, + { + "userId": 96, + "email": "loadtest00011@loadtest.invalid", + "isAdmin": false, + "sessionId": "XAS7Oirm4eKIoa8nCvqVIP5TlnvDz2V0q8G9zmI1", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ing5VW9FNEgzR2ozTi92TWNxQzJoU3c9PSIsInZhbHVlIjoiaHlPWGpwem5yTXZxNytMa1hsaExGWE9FbFlUWmkxdUp3YjRxUFZqV3BkSVV3eVR5VWxzd0NBYytheHVSNmEwZllob2ZpdlgybnoyYm1ybVFTVTRHaTNhRTNzWE1nY3dMQ0lVbGtzNEsvY01TaTZmMjZMQjBDc0g4RTRwUzJOQngiLCJtYWMiOiI3ZTI1OWZhN2E4OTU2ZDc2MDc2NmNiYzg0ODNmNmJkMzlhMWI5ODI5ZWEzNjc1ZWEzZDUxZDVlNzJmNGVmYjQxIiwidGFnIjoiIn0=", + "todoIds": [ + 783, + 784, + 785, + 786, + 787 + ], + "folderIds": [ + 355, + 356 + ] + }, + { + "userId": 97, + "email": "loadtest00012@loadtest.invalid", + "isAdmin": false, + "sessionId": "Z1I5Rww0dM0Yk6FnD0nPpQOUZfwQr9JYkFpCeHBw", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlBaRTB6ZWpDRDN3bXE1NFhZMEpNRXc9PSIsInZhbHVlIjoiL29Ub0xSc2pCTHNSMTFJMzJuSTU5SlRVVXVPMi85Umg5YWRNS3g1c3ZkNHp1MllrS2kxSzFrbjdVWHFqV093TG9LcmZhS0x5YjZkSEpwRWtoRzBoNmRCZFE3QWtmc0RBSVVnRGl6YzVLaS9kN0s3am1XQmVFRUxYaitIM000L0wiLCJtYWMiOiIwOTAxYjZhMWMxOGRkZTUyMDM5Yjk3YjllMmVkZGE1OTI2ZWM2YTA5MGYxNGM5Yjg2M2UwNjE5YWZiYWJmY2FjIiwidGFnIjoiIn0=", + "todoIds": [ + 789, + 790, + 791, + 792, + 793 + ], + "folderIds": [ + 358, + 359 + ] + }, + { + "userId": 98, + "email": "loadtest00013@loadtest.invalid", + "isAdmin": false, + "sessionId": "aUJlPJeDd4lLiXfKhVMQkQLH3agoXIUqSJDy889J", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ikk4aWs2RFBLTFAwbVRkaFhESHBlQVE9PSIsInZhbHVlIjoiVG5Cek9XL3Qzc252Y0ZNK2FLS0c2U3NKeis1SnBGVDFJYzNSS1ViWE9QcUF3eDMweEVBL0V4MHJWTlRZYUtnRHFOWHAweFBHWWg3RnNubFZ0OW1ha211aW9yeVlVNmV3T1BYa1RES3VVdDYzRU5TdzlJb1FpNkJqWXdxQi9GRW0iLCJtYWMiOiI4ZmE3NGM0MDYwMDZiOGQ3YmQyMGVhZGQ5MjcxZDQ0ODE5MTIzZTEyMDY1YWFiYjlhYWI4ZjIzOTY5YzQzYzI1IiwidGFnIjoiIn0=", + "todoIds": [ + 795, + 796, + 797, + 798, + 799 + ], + "folderIds": [ + 361, + 362 + ] + }, + { + "userId": 99, + "email": "loadtest00014@loadtest.invalid", + "isAdmin": false, + "sessionId": "blWSo2rrgCP4UkxkrFRP8wDrgsIxkXwfpGd5cmUM", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Imh3TUJBNlFrQUVJNHBZbDd5cXA0Snc9PSIsInZhbHVlIjoiTmtEVmtpUG1DNlNUQWw2OVpWYnBndmV2ckZVM0xITWhjbnJ1MlNEQXJvSTB3R1lUUmEydGpneVVIZUpxTmdWMkhWNWY4aVBYR29mdW92YUxvYUFUQ1FseUFGRDRVRW5qSHZheE5veHJEa3hNakFUbThjVUk2TDFIaU1jcWRWNTkiLCJtYWMiOiJiZDNlYjI4ODc0Y2RhNzZmNTA5ZTUwMzZmZWRkZjliMGM4NmNhZWE1ZmVhYmMxMWUwNjU4YmRlNGRkYTc4ZmY1IiwidGFnIjoiIn0=", + "todoIds": [ + 801, + 802, + 803, + 804, + 805 + ], + "folderIds": [ + 364, + 365 + ] + }, + { + "userId": 100, + "email": "loadtest00015@loadtest.invalid", + "isAdmin": false, + "sessionId": "qydNFUXhhHrJOWLOprwOhphr4v95Sc9tbn6SGK89", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjdoeTAvbS9MeFk3OWZBZ25qR1dwMGc9PSIsInZhbHVlIjoiaTRWaG1BNklURG9tcytPWHVMdXZ3UW9KTU16UFJBS1YwTndQWDNRdHBTZ3BsRnN2TGV6K3RQQklFZW8xMEk5U1JIS3cwWnZtWFZld1FEYkdDTExEU2hYM3RnR0NIcHpCcFBlZHJGcGY4YmVzdnVRdjNMaXJITjFqUjJ4VVRHODIiLCJtYWMiOiJkMmI5MjFmNWUwZWEyZDIxYzU4YjU3Mzg5YTk2MWE4YzQzMTM0YTVkZDczNjExY2E0NmNkNzhhNzkwYTM0MmZjIiwidGFnIjoiIn0=", + "todoIds": [ + 807, + 808, + 809, + 810, + 811 + ], + "folderIds": [ + 367, + 368 + ] + }, + { + "userId": 101, + "email": "loadtest00016@loadtest.invalid", + "isAdmin": false, + "sessionId": "X2d2LaJ0wjalLO0009dfMcT4ftJFRWuMEliC5rxB", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImgrZjRrQ1VIRG0ySGJqU3BMS0hZRWc9PSIsInZhbHVlIjoidGhIQVVHbHBoNVh5K0hhV1UwejU0WkZSOC9GUnJLejJ5bGY0amNXdXdkSytnbjluZ2Nkb1ZBWlZLL0hyc29QK3F0WUN4dDkrbktvZDdNQ3NjZ3d3ZjVlbUt5VUV6TmFKMk9pd21IK1VsVGZUQ3Rsc21RU1I1V280RTN5WDkrQmIiLCJtYWMiOiJhOGU3ODQ5YzgzNTliYTJhMGEzYTEwNDJjYzA0ZmJhZmRjN2YxMjk2YmRkMDM4NGY4Mjk1NWNjZmM4NTNlZTIzIiwidGFnIjoiIn0=", + "todoIds": [ + 813, + 814, + 815, + 816, + 817 + ], + "folderIds": [ + 370, + 371 + ] + }, + { + "userId": 102, + "email": "loadtest00017@loadtest.invalid", + "isAdmin": false, + "sessionId": "GUC2CVKgY6HvsVNvrKXnyyn6zG6gxw1lDBbhszo4", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ik1maHlFNzRsdzhaNmZzRmFxNFRIUmc9PSIsInZhbHVlIjoiTVJHUHNONm9QWXAySmtDeS9FMDV3ZTRCMjBnWnJEOEJUaGs0SVdqZnRlTnpoVTcrUEg5aXZZU2RaN3dTTnExcjY0ZWE2WjlBKzZyMzh6RnYwcGlFMVU1THNNQWhsSEFwZit6QVdzbzR5MVNKS3FQT0lSWEpUa3AzZGdGWnNtb3UiLCJtYWMiOiI4Yjc4MDQ4OGY2MDAzYTIzMjI3YzgzYjU4NDU5YjAzNzUyMDliMmRhZWY3NWQyOTJiYWQ3NDg2ZWRhMjU5MTJiIiwidGFnIjoiIn0=", + "todoIds": [ + 819, + 820, + 821, + 822, + 823 + ], + "folderIds": [ + 373, + 374 + ] + }, + { + "userId": 103, + "email": "loadtest00018@loadtest.invalid", + "isAdmin": false, + "sessionId": "noukGk3o1aTCuRUKbsqrYUxqeYD5VtLJROKPbiVE", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlJmTFlUTVRaaTNCcGttU3N0cE1MTHc9PSIsInZhbHVlIjoiWGRPbnY2bHloWW5xRDNnZmdJQyt3cER6REVSd05qS0ZHQXdhaVRzRVIzV3FlWWpWQ1FncXh4SW16NFJodXI5OG5Ua2pvOFRDVXhVTE5aMldqa3k2OHRBNFRMaTVqSVZ3b0U0ZnpqREhPNmZiTG9rd29hd3pMRVV3Y095RktnZDEiLCJtYWMiOiJmNzhjNWI4YjAwOGQzNjY2NzNmMzczZTliMTVjZDZmODMwNDU5ZDE3ZjlmMDkxNDYyZjMzYmMxMDZkYjVjOTA3IiwidGFnIjoiIn0=", + "todoIds": [ + 825, + 826, + 827, + 828, + 829 + ], + "folderIds": [ + 376, + 377 + ] + }, + { + "userId": 104, + "email": "loadtest00019@loadtest.invalid", + "isAdmin": false, + "sessionId": "kIHtfKKT6fQpuwU1hNo6Zeg4RZKhjkFrf44yJNaf", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImFLVnAvSEJqRzVXNStoNTBVTk5MT3c9PSIsInZhbHVlIjoiUDc4eFlrdTRGRVFZcmpwL1cyVFE5aTdPQWxCQ09GeVd0V0ptcERHZ0MzckptUXBSN2IyVVBzOXp6RVdiR0lrd2l2dzBvSW91MjFreFBndEFEYmpydnAvcFVwYTdxeDVjVHY2MjRFY0lRczZVMmk3YUFER1JhNkNnckdEN1RhL0wiLCJtYWMiOiIwMWIzOTBjMjJhYTQyMWU4YTkzNjhkZmZkM2IyMjVmOGJlNjZmMmFlOTI5MGVkN2Q4N2U4OWI0ZDc4MzY4NmMwIiwidGFnIjoiIn0=", + "todoIds": [ + 831, + 832, + 833, + 834, + 835 + ], + "folderIds": [ + 379, + 380 + ] + }, + { + "userId": 105, + "email": "loadtest00020@loadtest.invalid", + "isAdmin": false, + "sessionId": "l4vuOehiqKI1dvMbDQmvFKaRxsd14yHB8fDOQXJq", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IkFsT08zb3NRRGtuZ0dyTjFJbFNCYkE9PSIsInZhbHVlIjoiTjJvT0ZKVmlQcHBZMytMWWg4YkZtZU10R1hEV2ZhS1pMVjdGSytrWU13NUkxSEVGYWE2UC90YWJ6TlppV29uMFkwa2ZFb2lYYXh3ZUhCU09nOUJwUGEwUE5vQW5Vck1mNTZzb1JvNWlHaGVGY1ZPNHVnR0FGRmtQaS9ub1lqTVMiLCJtYWMiOiI5MjlhZDU2MjEzNTMyZDBlNDgzOWE5YjgyOTc4YTE5ZDZhODY4NjAyYjY2NjQ5NDg4ZmY0MGVmYTljYmI1MTA1IiwidGFnIjoiIn0=", + "todoIds": [ + 837, + 838, + 839, + 840, + 841 + ], + "folderIds": [ + 382, + 383 + ] + }, + { + "userId": 106, + "email": "loadtest00021@loadtest.invalid", + "isAdmin": false, + "sessionId": "O2JVLEXcj6iLKA1nydNSdqd2PZdIofYPi9jjkeyI", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ii83c1R1SW5LYUZPR2lKR3J3UUdHckE9PSIsInZhbHVlIjoiTVExWWI1NDgwN1lZYnJ4aTk2QTYvRU85cjI3ZUJWV051S3FDWG1ORGlEdGVtbnlhQVpjMi9UU25UZkFJSWl0V2lWdDNEeUdzd0IyZDlwSDRQRHZzcjdLOTBZNzRjU2NvWWRsM0E5OThlRXlqaTN2aE9sckN3MkcvVHlWa3lDTTciLCJtYWMiOiIxM2NlMWZiM2VlZDdmYmUwM2E3NDIyZmIyNzk4MTM4ZTZlNGI1ZWUxYTRiMWUzOWUzZGRiOTVhOGViNDJlNGI3IiwidGFnIjoiIn0=", + "todoIds": [ + 843, + 844, + 845, + 846, + 847 + ], + "folderIds": [ + 385, + 386 + ] + }, + { + "userId": 107, + "email": "loadtest00022@loadtest.invalid", + "isAdmin": false, + "sessionId": "braBRY2tasB6FrAdd7NMV0abeDXT4QfrQ5dejuoB", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjJGSVFCaHZyZ3pSSlJvdGJrZm9WU0E9PSIsInZhbHVlIjoiQ0ZPRzU3KzVWWmh6UUQ3VTdYSHVZMml0OUFZQWFhYXhIbVF3ZWFoTWNQSUk4U1JoZDMwV25Pb21rTlRuaDR1WHgvbUF0bVFmMUwvY3dQQ0dmNzZGcjkzbS9pRE5BNFpSL0dwNHpjTGRmSUFxbG1jYkJlLzdpM2I1UjlXWXNzanoiLCJtYWMiOiJmMmYxOTViNDZjZjkzZTc5ZDk1NmE3OWU4ODg4ZDBhNDRhNGRkYTM2M2YzNTU3ODFkNzdmYTk5YmI5MmRmNDUzIiwidGFnIjoiIn0=", + "todoIds": [ + 849, + 850, + 851, + 852, + 853 + ], + "folderIds": [ + 388, + 389 + ] + }, + { + "userId": 108, + "email": "loadtest00023@loadtest.invalid", + "isAdmin": false, + "sessionId": "ZH6rBbq9xYnpnzcIgwwKMvwDDFnt1wkm9R0Nx2HI", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlNOV28rb2FURkxocFJ1WVVhNEJSWEE9PSIsInZhbHVlIjoiY3JhNmdOZWNndVZGUlpEQ2svNWJLMkRJZGhMQjJSaWNMOFZVeEtsNUxxLzFRc2JxV214NUNndG5qaE5qRXVEUHlDZkwzTjJBUVZUVzdUeHRxdHpjeDYzV0pHM0dBMmhPbmdHMFZFWDVnNlE1RzVQYjVyUitPL1pobEhrTmFWQW0iLCJtYWMiOiI1ZmVkNzZkMjMzZDIxM2YzOGExODFlNTM3MTJlOTU3NTRmOGJiZGJhMjI2OWM0N2Q3MDc1NDRjNDIwNWQ4YmE4IiwidGFnIjoiIn0=", + "todoIds": [ + 855, + 856, + 857, + 858, + 859 + ], + "folderIds": [ + 391, + 392 + ] + }, + { + "userId": 109, + "email": "loadtest00024@loadtest.invalid", + "isAdmin": false, + "sessionId": "iLccuQXkm2ZucwroOttxoWnzxJhRLnq9Xuk9fgGX", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IkVqNjdWVTVDLzkvVVo5RnlSTk1EK2c9PSIsInZhbHVlIjoiZmp0OUw4OStmUUdVUWlVU0RvdkxieENGM2lWT1NtT2RQUUF3OWdnbUZrR1lQbmg4Ym4xOUtlMFVBdmhlWVprWmFjbzlGRnRESUV0dTR5bGxNeVFkTW8xVGZITnorVVVXYUl4TzI2ZFVRck5PZkpEZlJwM09BeUFsdTBKbEJkUDkiLCJtYWMiOiJjZTVlNzNiYjEzMmVhYmM1ZDJjYTMxM2E3M2U4OGMwYjk0N2VjMWI1ZDAwYTA3ZDU0MzFlMjliZDI3YjQyYjM2IiwidGFnIjoiIn0=", + "todoIds": [ + 861, + 862, + 863, + 864, + 865 + ], + "folderIds": [ + 394, + 395 + ] + }, + { + "userId": 110, + "email": "loadtest00025@loadtest.invalid", + "isAdmin": false, + "sessionId": "A4PjhsEnUb2B8QWo9BfSXecKEKfHmDTJjuY0Hek7", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlRaQkU3eFI1QkpuUDlVakNKKzRrNVE9PSIsInZhbHVlIjoiZDFya0MyTUtrdWw3N3pFeHczemlEMFJKQ3d5N3hzZmNkUDZmR3RGUUR0cHM3RHJtZVR4aHBsWWZlN1BFTCtVakhVM2tpcmpZR3g4cndJZzhvbGh1VURDeXI0cFo4UDNVeVJEdndzY1U1Wkg4Wm5JYlpENlVxa2QvaHdTbTN2L0giLCJtYWMiOiJiYjZlNjRlNGRjMzVjY2ZjZGUxMWNmYTEyZmFkM2ZkYzZmMDBjOWZmNjI0M2VmMWEyNzU2NjkwMzYxNWI2ZThhIiwidGFnIjoiIn0=", + "todoIds": [ + 867, + 868, + 869, + 870, + 871 + ], + "folderIds": [ + 397, + 398 + ] + }, + { + "userId": 111, + "email": "loadtest00026@loadtest.invalid", + "isAdmin": false, + "sessionId": "l9Qcggyo6svalMAtbJML9ikJohiE1LXfEd5p2fTT", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InNrSEhNeUZZNTYrbEc0WW5CQTNKV2c9PSIsInZhbHVlIjoidjdLNHJCVjFxamh2Ti90L3B4VVFOdXZKeGVjNGwwNnBrMXR6QkpyenZ5bkZxeGdRMEYyRDZhU3ZmeCtyOXh2Q3AxYnZ6UTRxSWlnVmxhV0sxYjMvcTlHMXJRVDl4Q3R2a1U5MnMyckFXU0szVnVDSFoyY0psSDJpS2NSUWh3VXUiLCJtYWMiOiIzMmQ5NzVkOTg4NmRlNmVmOWJjMTcwMjQzMmVmZGE1YmY3OTBmYThmZmZhYmQ5NjMwZGY3NWI0NjVlNDE2Y2IxIiwidGFnIjoiIn0=", + "todoIds": [ + 873, + 874, + 875, + 876, + 877 + ], + "folderIds": [ + 400, + 401 + ] + }, + { + "userId": 112, + "email": "loadtest00027@loadtest.invalid", + "isAdmin": false, + "sessionId": "ZCCInfUeqiw7A9TO8N2te211gqJ9A6urOUILRplV", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ilh2ZEhzVVFvV3J0aURJdVd2TXpORGc9PSIsInZhbHVlIjoiY0x5ZTRyK1AyWVQ5aWNQdUxLVG03bkJCZEdhcUxGNUdBTWZuN2xVMG5uUEpUNUpMOVhyQnFJSnFCN0Z4Z05ZWlNQZnlIa01xZm1BTXBLSjNvem9JSm9pRFh3dVMwNzJ2L1E5Mzh3QjFFTWI3MjRjMEdmZVBldlQrVUpjbDE0RU8iLCJtYWMiOiI5OWYwZjRlZDczYmVkZTQwZTVlYTgyMmY5MmY5YjVlNjRmZTczZTM1NDc0MDliNjFlMGEwMDY0OGQ2NGVlNDE5IiwidGFnIjoiIn0=", + "todoIds": [ + 879, + 880, + 881, + 882, + 883 + ], + "folderIds": [ + 403, + 404 + ] + }, + { + "userId": 113, + "email": "loadtest00028@loadtest.invalid", + "isAdmin": false, + "sessionId": "tb3oWafzPMN9Q8lihpbLq1RoiuyOhABnUSbeoEZY", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InFnZUk4RDJEaDc0L2JTZldtWGhINmc9PSIsInZhbHVlIjoiNkIrL3BteG1semFiSndSSnBEdVFFenN1aTVWRUMzYUZSQm00SUdobWpnb0NDeXFyZHd0bVJwYzJLY0JSN042bUdaekZKVTUyYmRTcTFONXdyQ1dLdFdMV21nUnRyRmNnbjMrTHE4WW95OEN0aU9WcmYxRWVVdkRyZFVLdmEwYkMiLCJtYWMiOiI3OTI4MzFlZTMzY2VlZGU1NDQ5ODA1YjFjMzYzZjRhZDk4NmU4NzQxMDg2YjZhMmU1YmM3N2JkNTYyYTM0ZTc1IiwidGFnIjoiIn0=", + "todoIds": [ + 885, + 886, + 887, + 888, + 889 + ], + "folderIds": [ + 406, + 407 + ] + }, + { + "userId": 114, + "email": "loadtest00029@loadtest.invalid", + "isAdmin": false, + "sessionId": "R6tupN5C317UDNFrKMVh9DYXeGrV81DKrUBvTAH9", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InAzbm8reFVPbXE0RFRCRGR5dU5XQkE9PSIsInZhbHVlIjoialc1T0o2alpXUjFONGxTWXd1azNjT3dTTElQaERLVUphNWhNUCttTkFYT1ZVcVh3NUVSL0JNbEM4dEdadUxKNitDVTNUcnRWMTc3bnIvNXMrOXZYa2xmTU1meklKaVdFT0tkbjRjOG5QU1ZTRGliOTRaWTM0L1NwK05aQi9QRXEiLCJtYWMiOiI4NGY4ZmI3ZWFlMjViZDVkZWEyNWNhYjJlNGJiZjM1OWMyNmQ1ZmRmMzNkOTQ2ZmY1NTc0MWExYzNlYjY5OGI1IiwidGFnIjoiIn0=", + "todoIds": [ + 891, + 892, + 893, + 894, + 895 + ], + "folderIds": [ + 409, + 410 + ] + }, + { + "userId": 115, + "email": "loadtest00030@loadtest.invalid", + "isAdmin": false, + "sessionId": "v70N3NYnwSxQNEBFmDXgQ17Vl19I7To5OUr6laZ9", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IkN0bWg3amViVnZvdVpDV0lIK3lkT3c9PSIsInZhbHVlIjoiU0kvMmtJSGJPU1ZjRFZSeDZtc2tSZUFNenZDWXFFNStXeS9uUzBJdTFzeEZNYnNVVU5jdUFGYm9NWHM4Z3B2b3laM3JOL2xUWExjc0dkekIyRWhabDlVMjZEeDA4Q3NKek5FbktlNHF1ci81MWlPVGs2elNvUW5qSmg2K0pOeUMiLCJtYWMiOiI2ZGFkYjUwMDA1MjI3NTE2N2UxOTdlNzAzODlmMmIwODg5ZDc3N2RmNWNlNGNmOWViODhmODkxNDllY2YxYTkzIiwidGFnIjoiIn0=", + "todoIds": [ + 897, + 898, + 899, + 900, + 901 + ], + "folderIds": [ + 412, + 413 + ] + }, + { + "userId": 116, + "email": "loadtest00031@loadtest.invalid", + "isAdmin": false, + "sessionId": "cU4RM3UaKKmZB7LiesdqQwqXaVZDe2vhjzL7XOLg", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ii9ldUQ3NGFNOFlNZW1JNlVsc3ByeWc9PSIsInZhbHVlIjoieGo0cjR3MW1YakZ5YjYrb0JkeXJmbVlLSW50NzBmdWFlanRTRitvaHlQaWxlVHV6WU9QaE9HaUVUZjFsNDU0WTZFYlRLYjEzUzJjUG9rVExSbnJrM25qRXJ0ZURlamZZZVJ2NmZhM29RRm1SZm5zaXRyREdjNGx6ZXlJTW9wQ0UiLCJtYWMiOiI1YTVhNjdkZjc2NDM3ZmNhYzRkYjVjZjZhOTA3ZWRmMmRhNmUwODhiOGFkMjI0ODM1NmFhZDM1ZDIzMTg1MWQxIiwidGFnIjoiIn0=", + "todoIds": [ + 903, + 904, + 905, + 906, + 907 + ], + "folderIds": [ + 415, + 416 + ] + }, + { + "userId": 117, + "email": "loadtest00032@loadtest.invalid", + "isAdmin": false, + "sessionId": "60pukuMFid3V3ey9lQWGTxQ5yUoVFZzD5PsXKKZJ", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IkEyZEV0VXBjZjNWcWwwdmlGL3pta0E9PSIsInZhbHVlIjoidEF3MnFsOXZtRi9xaGJKRDRPeGd3dktrMG1xMmdwenBzYkNvN3BUZ0plcmdkYi9WZDhwZHhMY1ptUHBYM2g3VFMzRHU5OTdmU2dRMFQ5T1lTSUdzRmx5cXBoV09SeUlERGZ1NnhrNmtYMDRaU0gyNkhpS1hhdmdYcVR3ZnZBWkciLCJtYWMiOiJmNzY5NzExYzRiNzBkNWQ4NmY2ZTE3NGNjYTM0ODdlMzRmNjNhZTBhYTc2Nzc4OTE1ZTEwNDBiZDA4MDNlYWYwIiwidGFnIjoiIn0=", + "todoIds": [ + 909, + 910, + 911, + 912, + 913 + ], + "folderIds": [ + 418, + 419 + ] + }, + { + "userId": 118, + "email": "loadtest00033@loadtest.invalid", + "isAdmin": false, + "sessionId": "XBt5MW4PH6KQR2EceHj5fhHWQNaQaOq1BJr2aGAI", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImhnRmQ4Zi95S1V5eitBaVlVY3NrMUE9PSIsInZhbHVlIjoiNDFDZzhpV2tyaHI4RUxqMENTNXRjRXN4U0R2YlB0KzlBR3ZSUVZKNDRuazBlYmJ4cFZqUDd5ZGdWdVZiMCt2WmhTVTk1RytZQ2JLbEkxeUxibzFudGlLLzRpQ3RmRmszVGVpcU96cCt0ZVJMazhiOUlnczlsL0JpSURmVXh3MHUiLCJtYWMiOiI5N2Q3MzU1MzRkZTk4ZmJmNTljMTM0ZmMxZTk3NzNiZjdkYTEyYTU5MGZiMmNmZDU3ODhiYjZiNjRlZWQyMGZjIiwidGFnIjoiIn0=", + "todoIds": [ + 915, + 916, + 917, + 918, + 919 + ], + "folderIds": [ + 421, + 422 + ] + }, + { + "userId": 119, + "email": "loadtest00034@loadtest.invalid", + "isAdmin": false, + "sessionId": "ncBCcmbLyjyu10SZ077qeVYd9GyHbMZPbm8aVOBD", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Inovblh6bVIrVzhCUDRYampTSlZpU1E9PSIsInZhbHVlIjoiZGRDdFpaSVdUZWZDWDNPTGJhMmVrSUtUNVVId3dFb0JQeXlsb3VGZXJrcTh4ZzMyWGJneTJ1SUlnVmFVN3ZmazczOGFsajBPOFU1ZWtFb2k5ZHVzcVdlZGVLdVlscldUc0dMR2xBeExLSWpwczZnMGFnU3pQZVJXS2N5YWQ3V1ciLCJtYWMiOiJiYjdjYjc0MzIyNzlmY2Y2NTY3MTU4OTE1NWExZDAzMzFjZGViMTczMjY1YTY1YzQyODY2YzhkZTAyOWE5NGZjIiwidGFnIjoiIn0=", + "todoIds": [ + 921, + 922, + 923, + 924, + 925 + ], + "folderIds": [ + 424, + 425 + ] + }, + { + "userId": 120, + "email": "loadtest00035@loadtest.invalid", + "isAdmin": false, + "sessionId": "svayYHlIeBAgndBxQGGBv1yZdWvk3wBbPholXlqT", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjJqYkthU09JQVpXMGxYSlhxZ0c3OFE9PSIsInZhbHVlIjoiS09TY1NITU9vM0Y5bFk1cVRWZ2VyYndrekJHb056MWNnMmFLaWhkZHJtdFV0cE5oU05NUy81Q2QvRnZFeksvcEJ1RXY3VW42MWpyRjc2ZTdMOGxuUXducjR3Yk5QRy85ZlpsT0d1c0JtT04rSEZ5Q29ySlE3bmhzUkxWeDc4akoiLCJtYWMiOiI5ZTNlNDhkN2MxNGE4OWE0MzllYjRhNGU5YWVmMTQxNTY5Zjk1ZThjZDVkYjczMDc2YTljMDEyZDJkZWM4ZDM2IiwidGFnIjoiIn0=", + "todoIds": [ + 927, + 928, + 929, + 930, + 931 + ], + "folderIds": [ + 427, + 428 + ] + }, + { + "userId": 121, + "email": "loadtest00036@loadtest.invalid", + "isAdmin": false, + "sessionId": "V4EaUFB6zlmjwtr54hH3fGSHIJyB3RmcTvEF5Dz0", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IisvS3pqVEFaTGxKb2o1ZjFHREpUbEE9PSIsInZhbHVlIjoiVldELzdTdE5BTGRtS3pyOGhsM3A5cnZub0NKQlZmQVpHWERIOWtTc1dOQnhnY2NHeTBBWmFORFdHTDdhcG81a1dROTZoaTROMzg2TGt0bnZjYktNSWlSNGVnQmpWdG04NzN2OTFRZE9SS3F6M1JRYnkvWlEyMUY0VEl5V1F5VHIiLCJtYWMiOiI2NGNjNjc5NWM4YzVlY2E0OTdiZGMwNjYwZTlmYzBmN2FlZTA4MDVmOWEwYjI0MWFkMDA1ZTUyZTUxMWUwM2Q5IiwidGFnIjoiIn0=", + "todoIds": [ + 933, + 934, + 935, + 936, + 937 + ], + "folderIds": [ + 430, + 431 + ] + }, + { + "userId": 122, + "email": "loadtest00037@loadtest.invalid", + "isAdmin": false, + "sessionId": "XSbSQSR9a7gMfnneeNcmGczszRXoz0BWurW2QxuG", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImU4WHMrODY3b0xDeTVZUFZXWXd2N1E9PSIsInZhbHVlIjoiUDhvT0tSKzhNdkhQb0lhT3pIdVA3UUxJb0kwWGlwdlRyaVN0MjN0Zm10aEFZZ2lhanJwSWJza09VaktZdHJYZnNvSTN1aGJnQnEwdXlWZkswTHI1amcvcnI1MnF2aU9GU212TXppZnpSTGtyc1Bva0FtbFF0VEdQVXZWZ3R0d08iLCJtYWMiOiI5NTJmYzM4ODIwMDE4YzdiOWM5YjdmMGVhMzQ3YzQ1MDFhYjg4Y2QzMDI2ODMyOTI3YmExNDYwOGEyYTMwNjg2IiwidGFnIjoiIn0=", + "todoIds": [ + 939, + 940, + 941, + 942, + 943 + ], + "folderIds": [ + 433, + 434 + ] + }, + { + "userId": 123, + "email": "loadtest00038@loadtest.invalid", + "isAdmin": false, + "sessionId": "xGEMXdAH5SAfJeeXsMELbar54ps1GCGuC52p9EUT", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImJ3eW1vZG9CN0QxVWZiZWdJQ2RKTlE9PSIsInZhbHVlIjoicVR0SXZ2ejMrK1NkQWxuTWFZYitwOExkL3lwamxaeW9BZXQvQVlyV1lsOXhtSGM1MFIvWlpGVzFvZjFoaEI1VUc3NUdEeHAyMmRtTFcyREFJcXEwVWl4MHM5d2laWisxUitmTlhwQS9jK1RNV1ZPTEZNTGFETWVhN3RzaVNBd2MiLCJtYWMiOiIwYmFjZjYxMjIzNmUzOGZiZDliNzQ4ZjM2NWYyMWMwNDRmNjcyZWNhZTIyNDk0ZmIxNDRlNmJlOWQ1Yzk0ODI4IiwidGFnIjoiIn0=", + "todoIds": [ + 945, + 946, + 947, + 948, + 949 + ], + "folderIds": [ + 436, + 437 + ] + }, + { + "userId": 124, + "email": "loadtest00039@loadtest.invalid", + "isAdmin": false, + "sessionId": "R0GAmqqjTGPCkzhaPL6dk6r1gGvobKg3NHxa6abt", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImN6MFpnVFhJSVJkRzVOdDB0bU13MkE9PSIsInZhbHVlIjoiVXFpRUpnaFhMbEdVeUxrU0ZBU3g4d1hwd2p3U25jZWVIMHJrR00yK05Ua3VDaHpNaDdvcDRQOCs2ZXR4NVM2VUJ1Q2txM3dtRDRRc2ltaDU0RHJXZDA2ZTFjTHZYNDY1NjJmMnNBVVNUMzZtRDdOL0NwZHYxRjJYT2JKVE5WQVAiLCJtYWMiOiIwN2ZmY2E3MWE1ODM3MzQzMzQ2ODA0Njg4MjY2NGE2YzAyNjY1NDJkZDM3NTI2NzRhNzBlZDFmYmZkZGExODc5IiwidGFnIjoiIn0=", + "todoIds": [ + 951, + 952, + 953, + 954, + 955 + ], + "folderIds": [ + 439, + 440 + ] + }, + { + "userId": 125, + "email": "loadtest00040@loadtest.invalid", + "isAdmin": false, + "sessionId": "ZfB0wSqiNCKMaq7zcB3AXOc282j1cqyffvyxoMcs", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlVQc0dZRW9EOHJSd0dNdzB3Zytaanc9PSIsInZhbHVlIjoiK09hbHU3OVhXT1l1aUFFVW9LUENrMUtuYUdwS3VaTzc5V01idWI2TkkwSGsxT2hTN2pWaHIwazd3NTBzakJ4cWt2V0tiaGNDWms5OTU2ZjZDcCtlemtPS1lIUjFZOWVmdEx3aE16bGlhNUtGQ3dHM0d5SXF4WEp4aUtNRGVQZHQiLCJtYWMiOiIwMWRmNWJiYjUyY2VmZDVkNGY0MzFhMTA2OWFiYTM2ZDgxYzViOTRjZTgyNzI4YjkwYjQyOGYyMjE2NGI2NmY3IiwidGFnIjoiIn0=", + "todoIds": [ + 957, + 958, + 959, + 960, + 961 + ], + "folderIds": [ + 442, + 443 + ] + }, + { + "userId": 126, + "email": "loadtest00041@loadtest.invalid", + "isAdmin": false, + "sessionId": "CPJKncuWCbewpdGJuiMf4H14nEGB3OIGAUwsNHRE", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Iko4MXo2dkNGYWdIM2VZbzN1NDkrdmc9PSIsInZhbHVlIjoiZzJxWEhadHdPdGdBNGE3TGpENE1VZnNKVVdUV3FJbUxYQUZVckNuZ09FTWtpS09DR2RkS1lVYUYyUm42bTFtNzNGMEJkeXI5c3VDdUVORjltekxLZENOc2xZZ2hCTmtQVC9LTWlUOUtDM0UzTytVUGZ4ZUJzdHZsQXEzandnVEEiLCJtYWMiOiJmNjA0ZmNkMDU1OTk0YjMxZjBkZGYxZWIzM2U3OWFhMmU1ZWU2Y2M0ZmU1Y2EwM2U1YmY2YmJmOGE5ZjM0YmI0IiwidGFnIjoiIn0=", + "todoIds": [ + 963, + 964, + 965, + 966, + 967 + ], + "folderIds": [ + 445, + 446 + ] + }, + { + "userId": 127, + "email": "loadtest00042@loadtest.invalid", + "isAdmin": false, + "sessionId": "5w6tScuQ7WXMSseTs3kP1v4H4gDKz5G2CO5gauWj", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Iml4MUh6cWlGdTJXdWlUcGdUY1pvU3c9PSIsInZhbHVlIjoibUw5cDZMQnkzNTQ3QVRmUVIwOFd5Z2JMUWxORGs2eGpKamdnek9RR0g2eTU2bEYwQ1B3Y0syd2hQRHlGQ0NkZWVvOUZVd0p6eVFjcWQ3eHhmT0V4amJ2ckI5UHpMZ003dk0vdUU1Z01HWmxLNTlmVEhOOU5xV3JQQ2RkR3o5dnkiLCJtYWMiOiJhZTE0MGRmZDZkMDhkNjQ5Yjc0NjcxY2YyY2Y0ODVkODgwYWE1YmNiMDkxYzk0OGYzN2JmOWNmYWJlOGI5Y2Q4IiwidGFnIjoiIn0=", + "todoIds": [ + 969, + 970, + 971, + 972, + 973 + ], + "folderIds": [ + 448, + 449 + ] + }, + { + "userId": 128, + "email": "loadtest00043@loadtest.invalid", + "isAdmin": false, + "sessionId": "tdqrPluFTjoza7DsnIHKxLFLGLDLqCxAetjUs733", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InIvWWtCc0l3ZnN0R0ZWOTRYWnE3Q1E9PSIsInZhbHVlIjoiSDRSZVlqVld5bEZrb3NJalAxNmR4bGFXTG5RaWI3SG9CQlVpOFF4RVZxMWhBNjlaRzEzTmNPRFZoUFlndnREWTQ1VDErOTRBdWttaFp6MWo1TlVZdjdnbzNhdElrNkdTdTJzaWNnYzRuYS90VWxkdTBPZDI2WTc1WDdseGpuZFciLCJtYWMiOiIwY2MyYzUxNGU4ZTU0ZTQyN2I1NGY0NDdiZDc1ZjFmNDFlMmE3ZGRiMWViNDA0MDQ2ZjhkZTA2MzExYjUzNTdkIiwidGFnIjoiIn0=", + "todoIds": [ + 975, + 976, + 977, + 978, + 979 + ], + "folderIds": [ + 451, + 452 + ] + }, + { + "userId": 129, + "email": "loadtest00044@loadtest.invalid", + "isAdmin": false, + "sessionId": "Nl6DFcFdLSiZN9UxKI3sUKjrdBwNq2CWIyGlnqqs", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6ImZEVXlqT3BieGJFbFdYaHBVckxoSUE9PSIsInZhbHVlIjoielgyb2FRM0xHWmpKTVB1RWRzSnc2N1lCQzljcjc1Y0ZKUWczTUpHVWNrMHVWVy8vcHBoWXRzbWU2Wm5YNldkYkswOVJzZ0RKdGUvbVI0cnVEN2Qvc0JFVU8xSWkwdWtCOXg4bDcyRjEyOEF5K3k4TXE0bzhnbGJISnQ0VmhPQnoiLCJtYWMiOiIxNTQzMzAyOTM3MWQxNjUxZmRhODlkMTM4NGU2YzJlNzcwYjAwYzU5ZGY2YjFkNzRhMWE0MWRkZDYxMDdhYzY4IiwidGFnIjoiIn0=", + "todoIds": [ + 981, + 982, + 983, + 984, + 985 + ], + "folderIds": [ + 454, + 455 + ] + }, + { + "userId": 130, + "email": "loadtest00045@loadtest.invalid", + "isAdmin": false, + "sessionId": "tM8ubLwA99UE14bWANHxrzuUNovWygEQNXbOLiLi", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ijd2S0JJVXJjVGFIOVNvakJCN2RRQ1E9PSIsInZhbHVlIjoiN2ZRQThqRklCR0E1d2VvY1dnZmtmc3lidHpPTW4xZytyT3hUZTYvR2YzNjM5ZW01U0Z1MzhCUDJHOWtBSktjYlNCWFU1TzdaWkNJSlJQbmx0REQzNm40VDUvZ1hzQWxKUlVZZ0MvQzNFZ2NDWjNicVE3RjhqSURQT1VSejY5bEYiLCJtYWMiOiI4OWFmMTA3MmIwMDgzOGQzYzZhNjgyZDhlMWI4M2IwZjc5ZWRjMzA4ZDc1NmRhODUxYWYyODJhZjQ2MDg0ZTU0IiwidGFnIjoiIn0=", + "todoIds": [ + 987, + 988, + 989, + 990, + 991 + ], + "folderIds": [ + 457, + 458 + ] + }, + { + "userId": 131, + "email": "loadtest00046@loadtest.invalid", + "isAdmin": false, + "sessionId": "8D5F28K7PzLb6xNZsxw13zxEJrfuJDe1CqAJ1bLC", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IklKNHRPamcrVjdOZVhKNmVEMG5hY1E9PSIsInZhbHVlIjoic2FsWmFTbytmQlNaa1lGdDEyNUt5ZHd4bFczQmJGYnBacG5TYVhWTjhpV0dNS0pGZU1ubEpoREFhUTUvNnZIRndQZ0plUUd4d0FQQ3VzYmM3RmRzbU1hMndvZ0U3Qm1GS3hJWUhDaHRFL1Y4cE1yMTdjeUhkN2prTUlIRmlEeEciLCJtYWMiOiIyY2MwNzJhM2Y2MTdjYWE2NDlmNmNhNGIzZTE5MDAzY2JmMjdkNWMyMDYxZTQ3NTI2ODE0MjgwNGQ3NzRkYmZiIiwidGFnIjoiIn0=", + "todoIds": [ + 993, + 994, + 995, + 996, + 997 + ], + "folderIds": [ + 460, + 461 + ] + }, + { + "userId": 132, + "email": "loadtest00047@loadtest.invalid", + "isAdmin": false, + "sessionId": "f0tpN59Aq5lr1V6LZt4aGq2vTGwBwm8aGccmhvYk", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InBTcEZGR0JQVU4zRmVvckMzNGtvWEE9PSIsInZhbHVlIjoiT1V6emorZ3VzZG80ek90aE8xM00vMG1iZmlPcjhzdmJ2WkRoVlhYWjNMcnAvMzNndG9MK3hMTXUrSWlMWFgxNDA0LzdGenNLTVpHUUpMcE9LcEpnZldqSEtoL3pPcUJTWDNSeTB4cCswNHRHZjlHZCtUTWRsRkg5bVpJZGx5VFMiLCJtYWMiOiIwNzhhZmUyNDM2NDkwYjI3ZjFmODIxOWRlYjMxYThiYzg1ZjI3YjJkNGM1YTg5YjYzZTg0MjNmOTgwYjFiZDc3IiwidGFnIjoiIn0=", + "todoIds": [ + 999, + 1000, + 1001, + 1002, + 1003 + ], + "folderIds": [ + 463, + 464 + ] + }, + { + "userId": 133, + "email": "loadtest00048@loadtest.invalid", + "isAdmin": false, + "sessionId": "g4JbvR8Dt2GJsy5g8E2cZeJzwisfipfnxVrpbsT6", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IjBjNUhlMTJBYU1UQmI1WllSWGQ2Rmc9PSIsInZhbHVlIjoiNlh0cWxDb0I1YTVjOE5tS3pua2wweWw5UEJaSnc3dVhEWmR2eGs2SndGbEJlL2dTQ0hscDNWNWlLb0I4QTdzQlp4Uzd0MXY3ajVIM0lIVXozTlZLSnc4OHppS2dsaHBIRThocnpSKzdRTkhGSkF4OHNvWVVNZDlUdUxtTjJzM2EiLCJtYWMiOiIxODE0MDYwZmNhMTUyNGIzNDFhNGIzMDg2NjI4MWY3MTBhYjgwYzQ2OTU2ZDg3ZTkxNzRjYmY5ZDEzNjJlYjdiIiwidGFnIjoiIn0=", + "todoIds": [ + 1005, + 1006, + 1007, + 1008, + 1009 + ], + "folderIds": [ + 466, + 467 + ] + }, + { + "userId": 134, + "email": "loadtest00049@loadtest.invalid", + "isAdmin": false, + "sessionId": "wdyhwP12WjUJbsRdCWqv9j9rfqwNocnpCOJRfoLS", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InhYMERXRXBhbzl2T29FZEJIdTc5Z2c9PSIsInZhbHVlIjoiY3lNTklOZmtROXdidHFEckxkbjhGUjRleGhpcVc4Z003UjJVRGVjTjdRMVpib2cwRyswZXJrNTNZR1pzSWoyY0IvcEpwMUtza0svMFR2V3pSWDE5bVpWb0xGbklkclczcGtBcEJ5VkpReGtBTFFFanFSajU0cjlheTViNTZxUlUiLCJtYWMiOiI0ODRmMTUyNjk1OTI5OTcxNGM5OWYxOGU2NmYzMGM4YTQ2YjA4MDEzMGI1ZDJiMDIxYWY0NTA2NGQ5YTBkZTc2IiwidGFnIjoiIn0=", + "todoIds": [ + 1011, + 1012, + 1013, + 1014, + 1015 + ], + "folderIds": [ + 469, + 470 + ] + }, + { + "userId": 135, + "email": "loadtest00050@loadtest.invalid", + "isAdmin": false, + "sessionId": "pMALgaixCc8bUxuqRXzVXA77A1G33IYlcGyOB12e", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ik13T00wQVhjWXIwZExKbTN2UDJxbXc9PSIsInZhbHVlIjoiTEhCWnQxRUVMR3ozenhrbGkrdHcyVEtqOXZVYndodjhJaUpUSnlkNVUzbDd6SlhEWEhiZndVQnJnM1FDYkljSEQxT3AyeUhORGNUV3FlOXNsOHpab2ZicnBEUHQ5RU1kd252S2RvTHVMRWFXNEY0N0VmVDZhR2dmYWg2Y1FTVUgiLCJtYWMiOiJiZGUxMWY0MzdjMzczM2JjYTgyOGU2ZTgwMjI1NDM1ZGJkYTA2YTFhZDFhM2IwMzNkNTQ4ZDZmYTZkM2Y0Mjk5IiwidGFnIjoiIn0=", + "todoIds": [ + 1017, + 1018, + 1019, + 1020, + 1021 + ], + "folderIds": [ + 472, + 473 + ] + }, + { + "userId": 136, + "email": "loadtest00051@loadtest.invalid", + "isAdmin": false, + "sessionId": "6sNJ1l0mSNq8OrqlB1bsmqGFHcm5rGQqIbmKN26x", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlMvaWljV3JWeDkzOURUQ3VabTlJV3c9PSIsInZhbHVlIjoiYkxyRkRhTmlnWlUvS3Mvb3l1ZTJzMi9yaDVMeEcvMG1IL0xGbEltY0dBU3RkMzRBVmF5L2lZakYya3k2cFR1OFQ0S0tIUVlVNkozZXNSR3hXZnhkRjJvMWhRK01RNVBFcVkyM1BXbEV5eFNtT3BJN05tTUpWNkhFa2ZINXk0SDkiLCJtYWMiOiJhMzNjMTk4ZmY3NDEyMTdhMTM4NDIwZmMxZGZjMjY1M2I2YWM1MTY1OGRkNzNkYjkwOTU4NzVhY2VkMWJkYTFiIiwidGFnIjoiIn0=", + "todoIds": [ + 1023, + 1024, + 1025, + 1026, + 1027 + ], + "folderIds": [ + 475, + 476 + ] + }, + { + "userId": 137, + "email": "loadtest00052@loadtest.invalid", + "isAdmin": false, + "sessionId": "deQcnsYePU80G2DsEiP22n5t5idOsEXfaDbe46Ci", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InB4eU9rcWdWdE4vWThvdFF1TTREaHc9PSIsInZhbHVlIjoicFBaUnV2S0oxNm5CLythMERidHBZMjFMNlFoWFQya0ZVNkFvL2NSNHVzYnRhdlZhQXJEL2NMR1ZsR2ZNL3pNSzQ0NER6RGxJSnFIWTNoYy9aY012UzdqbGM1eGpZNHdzRlBTWFZqNzFybzNRWjQ0R1d2cXN6UUNseGVzZUFTUUQiLCJtYWMiOiI0ZWUxNDgyYTFmYmI4ZmQ1OGNkNDMwMmJlNzcwYTM3YTg3NTE3YjQ2MTIyMDM2MjU0M2I2YzJhMDg3ZThlMzI4IiwidGFnIjoiIn0=", + "todoIds": [ + 1029, + 1030, + 1031, + 1032, + 1033 + ], + "folderIds": [ + 478, + 479 + ] + }, + { + "userId": 138, + "email": "loadtest00053@loadtest.invalid", + "isAdmin": false, + "sessionId": "bRlYaJNKQzh7hV3pIes8DN0S7lr4Nst2mpEVyOFr", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlYvK0hiQmhnN05pSERWUmtjMGdhYUE9PSIsInZhbHVlIjoiM21jTmNKeVp2TmdXNHlvTVVGUXFxcXdNdkovdUUzbWtGL1JRK3U2a2pkQittKzVmQ3BlRllrSHlnWEFlVjBoWkQrUUpoLzFNWFkyZnVIdFdUb1J4ZEdSR0cwRi8wdjhtU0JoNXRrUVZqSFA2WjBib0EvclBmM0JsWWRhVHgxUkwiLCJtYWMiOiI2MmZhZTAyZjRkZWEzZDJmYmU5ZWI3N2U4YjY1NGMxYzBlZWJlMmJhZjZjYjNiZDA3Y2FjNTY2YmUyOWFlYjYyIiwidGFnIjoiIn0=", + "todoIds": [ + 1035, + 1036, + 1037, + 1038, + 1039 + ], + "folderIds": [ + 481, + 482 + ] + }, + { + "userId": 139, + "email": "loadtest00054@loadtest.invalid", + "isAdmin": false, + "sessionId": "ltaFOB5gzliWEqQax49mAeMcRJRheM2g2t9r3DY8", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6InlURzJmTnlPN0ZKQ0pvdkRsTFhsN1E9PSIsInZhbHVlIjoiTTBOdFpzeVk1dGRHcXErRmROVjFsODRQYkVPek5ZUmZoUE04T0NJcVU1eTgrMlI0Z21TR0lPdHRGMWNGbnhKVzV6U3g0alpyOU1oeTF4Q1hQK2VDZ0hGcUFJRU5ZNFBXN0Q4ZTRQK3gzUnN5Q3JkeFZxL1RaTWd1anhRdnZGMG4iLCJtYWMiOiI0ZmZiNGE0ZDY4YzZlMGQ4MmFkYzVjY2VjZDY2Njc0ZmY2NTFjYWU1MjM2NTEyOGRlODU2ZDJlYmJhZjY5NTNhIiwidGFnIjoiIn0=", + "todoIds": [ + 1041, + 1042, + 1043, + 1044, + 1045 + ], + "folderIds": [ + 484, + 485 + ] + }, + { + "userId": 140, + "email": "loadtest00055@loadtest.invalid", + "isAdmin": false, + "sessionId": "ArpjKZluRKpUSwOPS5irlPei1bmMTywiGqbl01wZ", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlQrL3J2eTBGelNFM1lmejd4QWsxRUE9PSIsInZhbHVlIjoiK3VBMGNnZ3JSOFRmdGM3RHEvQmE4eGFDcXR0ajNYeDc1QmtCRWZrdWpERmRLdXRmRDAvVkcxUGR6ZXRpMUJGcDU4Y1laNEgvZzM3Q1gxU0J3bHowTG9mYVBya0NRVnhSWXRhUWI4T0hsUUdaUmVZdGY5VzJoRWNoOTBPeitJRUYiLCJtYWMiOiI0NWM0YjZlMTc2YTE4NzU0MThjMDc1ZDIzNDFhMjkyOWJiMzVjYWNmYWFjZDE2NDVhMGMxNTkyYTBiNDU4ZjhkIiwidGFnIjoiIn0=", + "todoIds": [ + 1047, + 1048, + 1049, + 1050, + 1051 + ], + "folderIds": [ + 487, + 488 + ] + }, + { + "userId": 141, + "email": "loadtest00056@loadtest.invalid", + "isAdmin": false, + "sessionId": "uJ92PXwixcKHYOIVKrdLwt3sCwmkQ6R6MRwbzzCt", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Imh6N0hGTFlMVU9QdHh3a0lYMlp4S1E9PSIsInZhbHVlIjoidjVRV3FhSVM2Zm4yeDhLWHI1bytxMUY5Ykx5UXlkWDZSVnZlajAvYzFsZ3lyM3pvSVVwa0FiRDZYbmFwbFhoZE96cmM5cHJNZVE3VUJRKzNaL3gxUlJEWHdYV3ducEF2dll2RGVZQmttNTh2ZVpsY2tyeWZRLzVPSjhOeTE0M2EiLCJtYWMiOiIyZWQzZmI0MTQxYWQ5ZThjMTFiMTAxNTY3NTkwYjU0MjI3MWYyMjdhMDE3ZWEwNzc0MDYwODdiN2I1MjI1YjcxIiwidGFnIjoiIn0=", + "todoIds": [ + 1053, + 1054, + 1055, + 1056, + 1057 + ], + "folderIds": [ + 490, + 491 + ] + }, + { + "userId": 142, + "email": "loadtest00057@loadtest.invalid", + "isAdmin": false, + "sessionId": "NJJDN1QJWIF86BWlUVc07H4gT8CA9HvQDf6lIDsm", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6IlByWHE1VmVVeVRwSE5lK0Rxb3RMUXc9PSIsInZhbHVlIjoiREVKdzVndkpjN0t5NkhHNmI4QnBGTlpnRmpXWVZ5NHpHK3BZWis1dUo3UWdBRVZLOHd2UDh0b0dLSWFyb3JKV0xCV2d6N2d2eFlZQnI5Q3d6NHYzblg4THNyUlI4T2s2cVNOVnk2K0xBS1RQeWFjcE5UNGo1ZHdPdHdGQ0pNbDkiLCJtYWMiOiI4NjQ3YzFhMmU5MjQxNjBhMjNmNzk5NTBkMjNjOWJkMzhlZjY0Y2I0MjE0ZTAwYWFmMTIwY2ViY2I4MDQyNmY2IiwidGFnIjoiIn0=", + "todoIds": [ + 1059, + 1060, + 1061, + 1062, + 1063 + ], + "folderIds": [ + 493, + 494 + ] + }, + { + "userId": 143, + "email": "loadtest00058@loadtest.invalid", + "isAdmin": false, + "sessionId": "2cJBsfxArOOQgrR5717C7ekKmxJlfzzcr00uJ0pu", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Iktic2dlaHN5NHg1SjBpMldYdWswQ1E9PSIsInZhbHVlIjoiUWhpYnNkYi9NekFRNWNlaURvTW40dXR6WSt3aEJDVklQdWViODRiS0ExUVBNVXpHam1hQ2Vnanl4ZUw1aWkyVk5oTENNZ1Z2QnVVSHlWT3E2ckdncFhHTHJvODFXZEhIL1FkNmtxOENLc1pBZzdDbTlyYnZBYXhrNkZaZFMrN1AiLCJtYWMiOiI0YzQzMzk3ODZiYzhkYzhkMmMwYTVhMjg5YzNiYzRmMmY4NjViYTg2NDUwOTVhOWJmM2RmMmQ1YWQyNDM0NjIxIiwidGFnIjoiIn0=", + "todoIds": [ + 1065, + 1066, + 1067, + 1068, + 1069 + ], + "folderIds": [ + 496, + 497 + ] + }, + { + "userId": 144, + "email": "loadtest00059@loadtest.invalid", + "isAdmin": false, + "sessionId": "YlENcuLJcXhPZdV6Iv42Hp6k9EFSP1XkullV3gkW", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Ii8rUzFwUjdvMnBpWC9CNzBJay8ySmc9PSIsInZhbHVlIjoiSDNERFNXbUFUZ1AxSk1WYUtSUEoyTU5Ra09XVjB0SmZ2cy9tZyt0eVZxMlQxcU92anVrcWJIanN3QkNXRXlIR2x1UzhBZWtlV3U5V3FkVE5ZRm05RUxieXlnNXhXY0xlYnZhSkdzUWxWVmdCUUxuclVwcStydFBZQjlZdU9vZ1YiLCJtYWMiOiI5MmI1MjkyMDQwNWQ4YzM0NjkzNzg2YzZiNDZmNTRmNzUyMzVjYWMzMjJiNjE4MTViZWM1MDQ3MmRiMGE4MTIyIiwidGFnIjoiIn0=", + "todoIds": [ + 1071, + 1072, + 1073, + 1074, + 1075 + ], + "folderIds": [ + 499, + 500 + ] + }, + { + "userId": 145, + "email": "loadtest00060@loadtest.invalid", + "isAdmin": true, + "sessionId": "mKPfhbUY9U7H65foswyL4aSKlnK7Rh5fSEPt2ilp", + "cookieName": "my-todos-session", + "cookie": "eyJpdiI6Impaek4yZHpVSjZwWG5hVHVTV09DV1E9PSIsInZhbHVlIjoiMmR6VHovaXBXNXQrcTRwUlY5Rk00ZzFPOFJMc0dpMlgwdkJqeEppdjBOWTlsS0NiSDJpR0tGRmpzQng4bkVJOXZ3SVdxR3haZlg1YkRrKy9EQk5hQkFSTEVabWJVS3RqdVlKMktKK3lBV002YnQ5dWc3Q3Q5M21wb1pmRHhCY3UiLCJtYWMiOiJkMjI1NzUxMjk2YzU4Yjc1ODJjNWQ1OGY3ODllMjE0ZDdiYTllNjVmMGZiNGUzOThkZjM1NzQyNjE1YzFmODRiIiwidGFnIjoiIn0=", + "todoIds": [ + 1077, + 1078, + 1079, + 1080, + 1081 + ], + "folderIds": [ + 502, + 503 + ] + } +] diff --git a/resources/views/components/app-logo.blade.php b/resources/views/components/app-logo.blade.php index 31c2688..2b09628 100644 --- a/resources/views/components/app-logo.blade.php +++ b/resources/views/components/app-logo.blade.php @@ -6,6 +6,8 @@ + + {{ config('app.name', 'Laravel') }} @else diff --git a/resources/views/layouts/app/header.blade.php b/resources/views/layouts/app/header.blade.php index c36bd0b..5720060 100644 --- a/resources/views/layouts/app/header.blade.php +++ b/resources/views/layouts/app/header.blade.php @@ -19,6 +19,9 @@ {{ __('Folders') }} + + {{ __('Members') }} + @@ -68,6 +71,9 @@ {{ __('Folders') }} + + {{ __('Members') }} + diff --git a/resources/views/layouts/app/sidebar.blade.php b/resources/views/layouts/app/sidebar.blade.php index 9f46877..56c4e3e 100644 --- a/resources/views/layouts/app/sidebar.blade.php +++ b/resources/views/layouts/app/sidebar.blade.php @@ -21,10 +21,13 @@ {{ __('Folders') }} + + {{ __('Members') }} + - @if (auth()->user()->isAdmin()) - + @if (auth()->user()->isSiteAdmin()) + {{ __('Notes limits') }} diff --git a/resources/views/mail/invitation.blade.php b/resources/views/mail/invitation.blade.php new file mode 100644 index 0000000..74bd879 --- /dev/null +++ b/resources/views/mail/invitation.blade.php @@ -0,0 +1,16 @@ + +# {{ $isFolder ? __('You have been invited to a folder') : __('You have been invited to a workspace') }} + +{{ $inviterName }} has invited you to {{ $isFolder ? 'the folder' : 'the workspace' }} **{{ $inviteableName }}** as **{{ $roleLabel }}**. + + +{{ __('Accept invitation') }} + + +This invitation link can only be used once and will expire in {{ \App\Models\Invitation::EXPIRY_DAYS }} days. + +If you did not expect this invitation, you can safely ignore this email. + +Thanks,
+{{ config('app.name') }} +
diff --git a/resources/views/pages/admin/⚡notes-limits.blade.php b/resources/views/pages/admin/⚡notes-limits.blade.php index d629ae4..95db9c6 100644 --- a/resources/views/pages/admin/⚡notes-limits.blade.php +++ b/resources/views/pages/admin/⚡notes-limits.blade.php @@ -2,19 +2,24 @@ use App\Models\User; use Flux\Flux; -use Illuminate\Support\Collection; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Support\Facades\Gate; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Attributes\Title; use Livewire\Component; +use Livewire\WithPagination; new #[Title('Notes limits')] class extends Component { + use WithPagination; + + private const PER_PAGE = 10; + public function mount(): void { - if (! auth()->user()->isAdmin()) { - abort(403); - } + Gate::authorize('accessAdmin'); } #[Locked] @@ -24,12 +29,33 @@ new #[Title('Notes limits')] class extends Component public string $notesLimitInput = ''; + public string $search = ''; + + public function updatedSearch(): void + { + $this->resetPage(); + } + #[Computed] - public function users(): Collection + public function users(): LengthAwarePaginator + { + return $this->filteredUserQuery() + ->orderBy('name') + ->paginate(self::PER_PAGE); + } + + /** + * @return Builder + */ + private function filteredUserQuery(): Builder { return User::query() - ->orderBy('name') - ->get(); + ->when( + $this->search !== '', + fn (Builder $query) => $query->where(fn (Builder $query) => $query + ->where('name', 'like', '%'.$this->search.'%') + ->orWhere('email', 'like', '%'.$this->search.'%')) + ); } public function startEditLimit(int $userId): void @@ -44,6 +70,8 @@ new #[Title('Notes limits')] class extends Component public function saveNotesLimit(): void { + Gate::authorize('accessAdmin'); + $user = $this->userById($this->editingUserId); $validated = $this->validate([ @@ -69,24 +97,49 @@ new #[Title('Notes limits')] class extends Component {{ __('Set how many characters each user may write in todo notes.') }} +
+ + + @if ($search !== '') + + {{ __('Clear') }} + + @endif +
+ - + {{ __('Name') }} {{ __('Email') }} - {{ __('Role') }} + {{ __('Site role') }} {{ __('Notes limit') }} {{ __('Actions') }} - @foreach ($this->users as $user) + @forelse ($this->users as $user) {{ $user->name }} {{ $user->email }} - @if ($user->isAdmin()) - {{ __('Admin') }} + @if ($user->isSiteAdmin()) + {{ __('Site admin') }} @else {{ __('Member') }} @endif @@ -107,7 +160,13 @@ new #[Title('Notes limits')] class extends Component - @endforeach + @empty + + + {{ __('No users match your search.') }} + + + @endforelse diff --git a/resources/views/pages/admin/⚡plan-pricing.blade.php b/resources/views/pages/admin/⚡plan-pricing.blade.php index 320f000..b4a3557 100644 --- a/resources/views/pages/admin/⚡plan-pricing.blade.php +++ b/resources/views/pages/admin/⚡plan-pricing.blade.php @@ -4,6 +4,7 @@ use App\Models\Organization; use App\Models\Setting; use Flux\Flux; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Gate; use Livewire\Attributes\Computed; use Livewire\Attributes\Title; use Livewire\Component; @@ -12,9 +13,7 @@ new #[Title('Plan pricing')] class extends Component { public function mount(): void { - if (! auth()->user()->isAdmin()) { - abort(403); - } + Gate::authorize('accessAdmin'); $this->amounts = $this->plans() ->mapWithKeys(fn (array $plan): array => [ @@ -61,6 +60,8 @@ new #[Title('Plan pricing')] class extends Component public function saveAmounts(): void { + Gate::authorize('accessAdmin'); + $validated = $this->validate([ 'amounts' => ['required', 'array'], 'amounts.*' => ['required', 'numeric', 'min:0', 'decimal:0,2'], diff --git a/resources/views/pages/invitations/⚡accept.blade.php b/resources/views/pages/invitations/⚡accept.blade.php new file mode 100644 index 0000000..e7ec312 --- /dev/null +++ b/resources/views/pages/invitations/⚡accept.blade.php @@ -0,0 +1,82 @@ +invitation = $invitation; + } + + /** + * Redeem the invitation for the signed-in user, then send them into the + * app. Workspace invitations are refused once the workspace is full. + */ + public function accept(): void + { + if (! $this->invitation->isValid()) { + return; + } + + $organization = $this->invitation->inviteable; + + if ($organization instanceof Organization && ! $organization->canAddMember()) { + $this->addError('invitation', __('This workspace is full, so this invitation can no longer be accepted.')); + + return; + } + + $this->invitation->accept(auth()->user()); + + $this->redirect(route('dashboard'), navigate: true); + } +}; ?> + +
+ {{ __('Invitation') }} + + @if ($invitation->isAccepted()) + + {{ __('This invitation has already been accepted.') }} + + @elseif ($invitation->isExpired()) + + {{ __('This invitation has expired. Ask the sender to invite you again.') }} + + @else + + @if ($invitation->isForFolder()) + {{ __(':inviter invited you to collaborate on the folder ":name" as :role.', [ + 'inviter' => $invitation->inviter?->name ?? __('Someone'), + 'name' => $invitation->inviteable?->name ?? __('a folder'), + 'role' => $invitation->roleLabel(), + ]) }} + @else + {{ __(':inviter invited you to join the ":name" workspace as :role.', [ + 'inviter' => $invitation->inviter?->name ?? __('Someone'), + 'name' => $invitation->inviteable?->name ?? __('a workspace'), + 'role' => $invitation->roleLabel(), + ]) }} + @endif + + + @error('invitation') + {{ $message }} + @enderror + +
+ + {{ __('Not now') }} + + + {{ __('Accept invitation') }} + +
+ @endif +
diff --git a/resources/views/pages/workspace/⚡members.blade.php b/resources/views/pages/workspace/⚡members.blade.php new file mode 100644 index 0000000..3d3c58c --- /dev/null +++ b/resources/views/pages/workspace/⚡members.blade.php @@ -0,0 +1,334 @@ + */ + public array $memberRoles = []; + + public function mount(): void + { + $this->seedMemberRoles(); + } + + #[Computed] + public function organization(): Organization + { + return auth()->user()->currentOrganization()->firstOrFail(); + } + + #[Computed] + public function canManage(): bool + { + return auth()->user()->can('manageMembers', $this->organization); + } + + /** + * @return Collection + */ + #[Computed] + public function members(): Collection + { + return $this->organization->users()->orderBy('name')->get(); + } + + /** + * @return Collection + */ + #[Computed] + public function invitations(): Collection + { + return $this->organization->invitations()->pending()->orderBy('email')->get(); + } + + /** + * Invite someone to the active workspace by email. The seat limit is a + * hard cap, so no invitation is sent once every seat is taken. + */ + public function inviteMember(): void + { + abort_unless($this->canManage, 403); + + $organization = $this->organization; + + $validated = $this->validate([ + 'inviteEmail' => ['required', 'string', 'email', 'max:255'], + 'inviteRole' => ['required', Rule::in([OrganizationRole::Admin->value, OrganizationRole::Member->value])], + ]); + + $email = Str::lower($validated['inviteEmail']); + + if ($organization->users()->where('users.email', $email)->exists()) { + $this->addError('inviteEmail', __('That person is already a member of this workspace.')); + + return; + } + + if (! $organization->canAddMember()) { + $this->addError('inviteEmail', __('This workspace is full, so no more invitations can be sent.')); + + return; + } + + $invitation = Invitation::updateOrCreate( + [ + 'inviteable_type' => Organization::class, + 'inviteable_id' => $organization->id, + 'email' => $email, + ], + [ + 'inviter_id' => auth()->id(), + 'role' => $validated['inviteRole'], + 'token' => Str::random(64), + 'expires_at' => now()->addDays(Invitation::EXPIRY_DAYS), + 'accepted_at' => null, + 'accepted_by_id' => null, + ], + ); + + Mail::to($email)->send(new InvitationMail($invitation)); + + $this->reset('inviteEmail', 'inviteRole'); + unset($this->invitations); + + Flux::toast(variant: 'success', text: __('Invitation sent to :email.', ['email' => $email])); + } + + public function updateMemberRole(int $userId, string $role): void + { + abort_unless($this->canManage, 403); + + $organization = $this->organization; + + if ($this->memberRole($organization, $userId) === OrganizationRole::Owner) { + return; + } + + $validated = validator( + ['role' => $role], + ['role' => ['required', Rule::in([OrganizationRole::Admin->value, OrganizationRole::Member->value])]], + )->validate(); + + $organization->users()->updateExistingPivot($userId, ['role' => $validated['role']]); + + unset($this->members); + + Flux::toast(variant: 'success', text: __('Member role updated.')); + } + + public function updatedMemberRoles(string $value, string $key): void + { + $this->updateMemberRole((int) $key, $value); + } + + public function removeMember(int $userId): void + { + abort_unless($this->canManage, 403); + + if ($userId === auth()->id()) { + Flux::toast(variant: 'danger', text: __('You cannot remove yourself from the workspace.')); + + return; + } + + $organization = $this->organization; + + if ($this->memberRole($organization, $userId) === OrganizationRole::Owner) { + return; + } + + $organization->users()->detach($userId); + + // Move the removed member back to their personal workspace if they + // were currently working in this one. + $user = User::find($userId); + + if ($user !== null && (int) $user->current_organization_id === $organization->id) { + $fallback = $user->organizations() + ->where('type', WorkspaceType::Personal->value) + ->first() ?? $user->organizations()->first(); + + if ($fallback !== null) { + $user->forceFill(['current_organization_id' => $fallback->id])->save(); + } + } + + unset($this->members); + + $this->seedMemberRoles(); + + Flux::toast(variant: 'success', text: __('Member removed.')); + } + + public function revokeInvitation(int $invitationId): void + { + abort_unless($this->canManage, 403); + + $invitation = $this->organization->invitations()->whereKey($invitationId)->firstOrFail(); + + abort_unless(auth()->user()->can('delete', $invitation), 403); + + $invitation->delete(); + + unset($this->invitations); + + Flux::toast(variant: 'success', text: __('Invitation revoked.')); + } + + private function memberRole(Organization $organization, int $userId): ?OrganizationRole + { + return OrganizationRole::tryFrom((string) $organization->users() + ->where('users.id', $userId) + ->withPivot('role') + ->first()?->pivot->role); + } + + private function seedMemberRoles(): void + { + $this->memberRoles = $this->members + ->mapWithKeys(fn (User $member): array => [$member->id => (string) $member->pivot->role]) + ->all(); + } +}; ?> + +
+
+ {{ __('Members') }} + + {{ __('People with access to the ":name" workspace.', ['name' => $this->organization->name]) }} + +
+ + @php($limit = $this->organization->seatLimit()) + + @if ($limit === null) + {{ __(':count members', ['count' => $this->organization->memberCount()]) }} + @else + {{ __(':count of :limit seats used', ['count' => $this->organization->memberCount(), 'limit' => $limit]) }} + @endif + + + +
+ {{ __('Current members') }} + + @foreach ($this->members as $member) + @php($role = OrganizationRole::tryFrom((string) $member->pivot->role)) +
+
+ {{ $member->name }} + {{ $member->email }} +
+ +
+ @if ($role === OrganizationRole::Owner || ! $this->canManage || $member->id === auth()->id()) + + {{ $role?->label() ?? $member->pivot->role }} + + @else + + @foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option) + {{ $option->label() }} + @endforeach + + @if ($role !== OrganizationRole::Owner) + + @endif + @endif +
+
+ @endforeach +
+
+ + @if ($this->canManage) + @if ($this->organization->canAddMember()) + +
+ {{ __('Invite a member') }} + +
+
+ + +
+
+ + @foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option) + {{ $option->label() }} + @endforeach + + +
+ + {{ __('Send invite') }} + +
+
+
+ @else + + {{ __('Every seat in this workspace is taken, so no more members can be invited.') }} + + @endif + + @if ($this->invitations->isNotEmpty()) + +
+ {{ __('Pending invitations') }} + + @foreach ($this->invitations as $invitation) +
+
+ {{ $invitation->email }} + {{ $invitation->roleLabel() }} +
+ + {{ __('Revoke') }} + +
+ @endforeach +
+
+ @endif + @endif +
diff --git a/resources/views/pages/⚡dashboard.blade.php b/resources/views/pages/⚡dashboard.blade.php index bd317e3..583235a 100644 --- a/resources/views/pages/⚡dashboard.blade.php +++ b/resources/views/pages/⚡dashboard.blade.php @@ -55,7 +55,7 @@ new #[Title('Dashboard')] class extends Component $folderId = (int) $folderId; - if (Folder::query()->forUser(auth()->id())->whereKey($folderId)->exists()) { + if (Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($folderId)->exists()) { $this->folderId = $folderId; } } @@ -93,7 +93,7 @@ new #[Title('Dashboard')] class extends Component public function openEditForm(int $todoId): void { - $todo = $this->todoForUser($todoId); + $todo = $this->todoForAction($todoId, 'update'); $this->editingTodoId = $todo->id; $this->description = $todo->description; @@ -113,11 +113,20 @@ new #[Title('Dashboard')] class extends Component 'todoStatus' => ['required', Rule::enum(TodoStatus::class)], 'dueDate' => ['nullable', 'date'], 'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()], - 'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->where('user_id', auth()->id())], + 'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->whereIn( + 'id', + Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->select('folders.id') + )], ]); + $folder = Folder::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->findOrFail($validated['formFolderId']); + + abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403); + $data = [ - 'folder_id' => $validated['formFolderId'], + 'folder_id' => $folder->id, 'description' => $validated['description'], 'status' => TodoStatus::from($validated['todoStatus']), 'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null, @@ -125,11 +134,11 @@ new #[Title('Dashboard')] class extends Component ]; if ($this->editingTodoId !== null) { - $this->todoForUser($this->editingTodoId)->update($data); + $this->todoForAction($this->editingTodoId, 'update')->update($data); } else { Todo::create($data + [ 'user_id' => auth()->id(), - 'position' => Todo::nextPositionFor(auth()->user()), + 'position' => Todo::nextPositionFor($folder), ]); } @@ -138,7 +147,7 @@ new #[Title('Dashboard')] class extends Component public function toggleComplete(int $todoId): void { - $todo = $this->todoForUser($todoId); + $todo = $this->todoForAction($todoId, 'markComplete'); $data = ['completed_at' => $todo->completed_at === null ? now() : null]; @@ -153,7 +162,7 @@ new #[Title('Dashboard')] class extends Component public function confirmTodoDelete(int $todoId): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'delete'); $this->confirmingTodoDelete = $todoId; $this->modal('confirm-todo-delete')->show(); @@ -161,7 +170,7 @@ new #[Title('Dashboard')] class extends Component public function deleteTodo(): void { - $this->todoForUser($this->confirmingTodoDelete)->delete(); + $this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete(); $this->confirmingTodoDelete = null; $this->modal('confirm-todo-delete')->close(); @@ -176,7 +185,7 @@ new #[Title('Dashboard')] class extends Component #[Computed] public function todoCounts(): array { - $query = Todo::query()->forUser(auth()->id()); + $query = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId()); return [ 'open' => (clone $query)->active()->count(), @@ -189,7 +198,7 @@ new #[Title('Dashboard')] class extends Component #[Computed] public function folderTree(): Collection { - return Folder::treeForUser(auth()->id()); + return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId()); } #[Computed] @@ -208,12 +217,12 @@ new #[Title('Dashboard')] class extends Component $tree = $this->folderTree; $openByFolder = Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->active() ->pluck('folder_id') ->countBy(); $overdueByFolder = Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->overdue() ->pluck('folder_id') ->countBy(); @@ -264,7 +273,7 @@ new #[Title('Dashboard')] class extends Component public function moveTodo(int $todoId, string $direction): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'update'); $ids = $this->orderedTodoIds; $currentIndex = array_search($todoId, $ids, true); @@ -284,7 +293,7 @@ new #[Title('Dashboard')] class extends Component public function handleSort(int $todoId, int $position): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'update'); $offset = ($this->todos->currentPage() - 1) * self::PER_PAGE; @@ -317,7 +326,7 @@ new #[Title('Dashboard')] class extends Component unset($visibleOrder[$currentIndex]); array_splice($visibleOrder, $newIndex, 0, $todoId); - $ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all(); + $ids = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->priority()->pluck('id')->all(); $slots = array_keys(array_intersect($ids, $visibleIds)); @@ -326,7 +335,7 @@ new #[Title('Dashboard')] class extends Component } foreach ($ids as $position => $id) { - Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); + Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($id)->update(['position' => $position]); } unset($this->todos, $this->orderedTodoIds); @@ -338,7 +347,7 @@ new #[Title('Dashboard')] class extends Component private function filteredTodoQuery(): Builder { return Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->when( $this->search !== '', fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%') @@ -369,9 +378,21 @@ new #[Title('Dashboard')] class extends Component return $ids; } - private function todoForUser(int $todoId): Todo + private function todoForAction(int $todoId, string $ability): Todo { - return Todo::query()->forUser(auth()->id())->findOrFail($todoId); + $todo = Todo::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->with('folder') + ->findOrFail($todoId); + + abort_unless(auth()->user()->can($ability, $todo), 403); + + return $todo; + } + + private function activeWorkspaceId(): int + { + return (int) auth()->user()->current_organization_id; } }; ?> @@ -510,18 +531,22 @@ new #[Title('Dashboard')] class extends Component @forelse ($this->todos as $todo) -
- -
+ @can('update', $todo) +
+ +
+ @endcan
- + @can('markComplete', $todo) + + @endcan @@ -581,44 +606,46 @@ new #[Title('Dashboard')] class extends Component
- @if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) + @can('update', $todo) + @if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) + + @endif + + @if ($todo->id !== ($this->orderedTodoIds[array_key_last($this->orderedTodoIds)] ?? null)) + + @endif + - @endif - - @if ($todo->id !== ($this->orderedTodoIds[array_key_last($this->orderedTodoIds)] ?? null)) - @endif - - - + @endcan
diff --git a/resources/views/pages/⚡folders.blade.php b/resources/views/pages/⚡folders.blade.php index 54e2954..327ad9d 100644 --- a/resources/views/pages/⚡folders.blade.php +++ b/resources/views/pages/⚡folders.blade.php @@ -1,10 +1,19 @@ */ + public array $collaboratorRoles = []; + public bool $showTodoForm = false; #[Locked] @@ -55,8 +76,15 @@ new #[Title('Folders')] class extends Component public function createTopLevelFolder(): void { + $organization = auth()->user()->currentOrganization()->first(); + + abort_unless( + $organization !== null && auth()->user()->can('create', [Folder::class, $organization]), + 403 + ); + $validated = $this->validate([ - 'newFolderName' => $this->folderNameRules(parentId: null), + 'newFolderName' => $this->folderNameRules($organization->id, parentId: null), 'newFolderColor' => $this->folderColorRules(), ]); @@ -72,7 +100,7 @@ new #[Title('Folders')] class extends Component public function startChildCreate(int $folderId): void { - $this->folderForUser($folderId); + $this->folderForAction($folderId, 'createChild'); $this->creatingChildOf = $folderId; $this->reset('newChildName', 'newChildColor'); @@ -86,18 +114,19 @@ new #[Title('Folders')] class extends Component public function createChildFolder(): void { - $this->folderForUser($this->creatingChildOf); + $parent = $this->folderForAction($this->creatingChildOf ?? 0, 'createChild'); $validated = $this->validate([ - 'newChildName' => $this->folderNameRules(parentId: $this->creatingChildOf), + 'newChildName' => $this->folderNameRules($parent->organization_id, parentId: $parent->id), 'newChildColor' => $this->folderColorRules(), ]); Folder::create([ 'user_id' => auth()->id(), + 'organization_id' => $parent->organization_id, 'name' => $validated['newChildName'], 'color' => filled($validated['newChildColor']) ? $validated['newChildColor'] : null, - 'parent_id' => $this->creatingChildOf, + 'parent_id' => $parent->id, ]); $this->reset('creatingChildOf', 'newChildName', 'newChildColor'); @@ -105,7 +134,7 @@ new #[Title('Folders')] class extends Component public function startRename(int $folderId): void { - $folder = $this->folderForUser($folderId); + $folder = $this->folderForAction($folderId, 'update'); $this->renamingFolderId = $folder->id; $this->renameName = $folder->name; @@ -119,10 +148,10 @@ new #[Title('Folders')] class extends Component public function saveRename(): void { - $folder = $this->folderForUser($this->renamingFolderId); + $folder = $this->folderForAction($this->renamingFolderId ?? 0, 'update'); $validated = $this->validate([ - 'renameName' => $this->folderNameRules(parentId: $folder->parent_id, ignoreId: $folder->id), + 'renameName' => $this->folderNameRules($folder->organization_id, parentId: $folder->parent_id, ignoreId: $folder->id), ]); $folder->update(['name' => $validated['renameName']]); @@ -132,7 +161,7 @@ new #[Title('Folders')] class extends Component public function confirmFolderDelete(int $folderId): void { - $this->folderForUser($folderId); + $this->folderForAction($folderId, 'delete'); $this->confirmingFolderDelete = $folderId; $this->modal('confirm-folder-delete')->show(); @@ -140,7 +169,7 @@ new #[Title('Folders')] class extends Component public function deleteFolder(): void { - $folder = $this->folderForUser($this->confirmingFolderDelete); + $folder = $this->folderForAction($this->confirmingFolderDelete ?? 0, 'delete'); if ($this->expandedFolderId === $folder->id) { $this->expandedFolderId = null; @@ -154,14 +183,14 @@ new #[Title('Folders')] class extends Component public function toggleExpandFolder(int $folderId): void { - $this->folderForUser($folderId); + $this->visibleFolder($folderId); $this->expandedFolderId = $this->expandedFolderId === $folderId ? null : $folderId; } public function startColorEdit(int $folderId): void { - $folder = $this->folderForUser($folderId); + $folder = $this->folderForAction($folderId, 'update'); $this->colorEditingFolderId = $folder->id; $this->colorDraft = $folder->color ?? ''; @@ -171,7 +200,7 @@ new #[Title('Folders')] class extends Component public function saveFolderColor(): void { - $folder = $this->folderForUser($this->colorEditingFolderId ?? 0); + $folder = $this->folderForAction($this->colorEditingFolderId ?? 0, 'update'); $validated = $this->validate([ 'colorDraft' => $this->folderColorRules(), @@ -185,21 +214,179 @@ new #[Title('Folders')] class extends Component $this->modal('folder-color')->close(); } + public function startShare(int $folderId): void + { + $folder = $this->folderForAction($folderId, 'manageShares'); + + $this->sharingFolderId = $folder->id; + $this->shareVisibility = $folder->visibility->value; + $this->collaboratorRoles = $folder->shares() + ->get() + ->mapWithKeys(fn (User $user): array => [$user->id => (string) $user->pivot->role]) + ->all(); + $this->reset('inviteEmail', 'inviteRole'); + $this->resetErrorBag('inviteEmail', 'inviteRole'); + $this->modal('folder-share')->show(); + } + + public function closeShare(): void + { + $this->reset('sharingFolderId', 'inviteEmail', 'inviteRole', 'collaboratorRoles'); + $this->modal('folder-share')->close(); + } + + public function updatedCollaboratorRoles(string $value, string $key): void + { + $this->updateCollaboratorRole((int) $key, $value); + } + + public function updatedShareVisibility(string $value): void + { + $this->updateVisibility($value); + } + + public function updateVisibility(string $visibility): void + { + $folder = $this->folderForAction($this->sharingFolderId ?? 0, 'manageShares'); + + $validated = validator( + ['shareVisibility' => $visibility], + ['shareVisibility' => ['required', Rule::enum(FolderVisibility::class)]], + )->validate(); + + // Personal workspaces hold a single member, so there is nothing to + // share a folder with. Only ever move such a folder back to private. + if ($validated['shareVisibility'] === FolderVisibility::Workspace->value + && $folder->organization?->isPersonal()) { + return; + } + + $folder->update(['visibility' => $validated['shareVisibility']]); + + unset($this->sharingFolder); + + Flux::toast(variant: 'success', text: __('Folder sharing updated.')); + } + + public function inviteCollaborator(): void + { + $folder = $this->folderForAction($this->sharingFolderId ?? 0, 'manageShares'); + + $validated = $this->validate([ + 'inviteEmail' => ['required', 'string', 'email', 'max:255'], + 'inviteRole' => ['required', Rule::enum(FolderRole::class)], + ]); + + $email = Str::lower($validated['inviteEmail']); + + if ($folder->shares()->where('users.email', $email)->exists()) { + $this->addError('inviteEmail', __('That person already has access to this folder.')); + + return; + } + + if (Str::lower((string) $folder->user?->email) === $email) { + $this->addError('inviteEmail', __('That person already owns this folder.')); + + return; + } + + $invitation = Invitation::updateOrCreate( + [ + 'inviteable_type' => Folder::class, + 'inviteable_id' => $folder->id, + 'email' => $email, + ], + [ + 'inviter_id' => auth()->id(), + 'role' => $validated['inviteRole'], + 'token' => Str::random(64), + 'expires_at' => now()->addDays(Invitation::EXPIRY_DAYS), + 'accepted_at' => null, + 'accepted_by_id' => null, + ], + ); + + Mail::to($email)->send(new InvitationMail($invitation)); + + $this->reset('inviteEmail', 'inviteRole'); + unset($this->sharingInvitations); + + Flux::toast(variant: 'success', text: __('Invitation sent to :email.', ['email' => $email])); + } + + public function updateCollaboratorRole(int $userId, string $role): void + { + $folder = $this->folderForAction($this->sharingFolderId ?? 0, 'manageShares'); + + if ($userId === $folder->user_id) { + return; + } + + $validated = validator( + ['role' => $role], + ['role' => ['required', Rule::enum(FolderRole::class)]], + )->validate(); + + $folder->shares()->updateExistingPivot($userId, ['role' => $validated['role']]); + + unset($this->sharingCollaborators); + + Flux::toast(variant: 'success', text: __('Collaborator role updated.')); + } + + public function removeCollaborator(int $userId): void + { + $folder = $this->folderForAction($this->sharingFolderId ?? 0, 'manageShares'); + + if ($userId === $folder->user_id) { + return; + } + + $folder->shares()->detach($userId); + + unset($this->sharingCollaborators); + + Flux::toast(variant: 'success', text: __('Collaborator removed.')); + } + + public function revokeFolderInvitation(int $invitationId): void + { + $folder = $this->folderForAction($this->sharingFolderId ?? 0, 'manageShares'); + + $invitation = $folder->invitations()->whereKey($invitationId)->firstOrFail(); + + abort_unless(auth()->user()->can('delete', $invitation), 403); + + $invitation->delete(); + + unset($this->sharingInvitations); + + Flux::toast(variant: 'success', text: __('Invitation revoked.')); + } + public function moveTodoToFolder(int $todoId, int $folderId): void { - $todo = Todo::query()->forUser(auth()->id())->findOrFail($todoId); + $todo = Todo::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->with('folder') + ->findOrFail($todoId); - $folder = Folder::query()->forUser(auth()->id())->findOrFail($folderId); + abort_unless(auth()->user()->can('update', $todo), 403); + + $folder = $this->visibleFolder($folderId); + + abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403); $todo->update(['folder_id' => $folder->id]); } public function moveFolderToTopLevel(int $folderId): void { - $folder = $this->folderForUser($folderId); + $folder = $this->folderForAction($folderId, 'update'); $hasSiblingConflict = Folder::query() - ->forUser(auth()->id()) + ->where('organization_id', $folder->organization_id) ->whereNull('parent_id') ->whereKeyNot($folder->id) ->where('name', $folder->name) @@ -214,8 +401,8 @@ new #[Title('Folders')] class extends Component public function moveFolderToFolder(int $folderId, int $targetFolderId): void { - $folder = $this->folderForUser($folderId); - $target = $this->folderForUser($targetFolderId); + $folder = $this->folderForAction($folderId, 'update'); + $target = $this->folderForAction($targetFolderId, 'createChild'); if ($folder->id === $target->id || $this->isDescendantOf($target, $folder)) { return; @@ -251,7 +438,7 @@ new #[Title('Folders')] class extends Component public function todosForFolder(int $folderId): Collection { return Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->where('folder_id', $folderId) ->active() ->priority() @@ -260,7 +447,7 @@ new #[Title('Folders')] class extends Component public function startTodoCreate(int $folderId): void { - $this->folderForUser($folderId); + $this->folderForTodoCreate($folderId); $this->todoFolderId = $folderId; $this->reset('todoDescription', 'todoStatus', 'todoDueDate', 'todoNotes'); @@ -270,7 +457,7 @@ new #[Title('Folders')] class extends Component public function saveFolderTodo(): void { - $folder = $this->folderForUser($this->todoFolderId ?? 0); + $folder = $this->folderForTodoCreate($this->todoFolderId ?? 0); $validated = $this->validate([ 'todoDescription' => ['required', 'string', 'max:255'], @@ -286,7 +473,7 @@ new #[Title('Folders')] class extends Component 'status' => TodoStatus::from($validated['todoStatus']), 'due_date' => filled($validated['todoDueDate']) ? Carbon::parse($validated['todoDueDate']) : null, 'notes' => filled($validated['todoNotes']) ? $validated['todoNotes'] : null, - 'position' => Todo::nextPositionFor(auth()->user()), + 'position' => Todo::nextPositionFor($folder), ]); $this->reset('showTodoForm', 'todoFolderId', 'todoDescription', 'todoStatus', 'todoDueDate', 'todoNotes'); @@ -295,7 +482,7 @@ new #[Title('Folders')] class extends Component #[Computed] public function folderTree(): Collection { - return Folder::treeForUser(auth()->id()); + return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId()); } #[Computed] @@ -305,7 +492,10 @@ new #[Title('Folders')] class extends Component return null; } - return Folder::query()->with('parent')->forUser(auth()->id())->find($this->todoFolderId); + return Folder::query() + ->with('parent') + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->find($this->todoFolderId); } #[Computed] @@ -324,12 +514,43 @@ new #[Title('Folders')] class extends Component public function openCounts(): Collection { return Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->active() ->pluck('folder_id') ->countBy(); } + #[Computed] + public function sharingFolder(): ?Folder + { + if ($this->sharingFolderId === null) { + return null; + } + + return Folder::query() + ->with('organization') + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->find($this->sharingFolderId); + } + + /** + * @return Collection + */ + #[Computed] + public function sharingCollaborators(): Collection + { + return $this->sharingFolder?->shares()->orderBy('name')->get() ?? collect(); + } + + /** + * @return Collection + */ + #[Computed] + public function sharingInvitations(): Collection + { + return $this->sharingFolder?->invitations()->pending()->orderBy('email')->get() ?? collect(); + } + /** * @return array */ @@ -341,7 +562,7 @@ new #[Title('Folders')] class extends Component /** * @return array */ - private function folderNameRules(?int $parentId = null, ?int $ignoreId = null): array + private function folderNameRules(int $organizationId, ?int $parentId = null, ?int $ignoreId = null): array { return [ 'required', @@ -350,14 +571,39 @@ new #[Title('Folders')] class extends Component Rule::unique('folders', 'name') ->ignore($ignoreId) ->where(fn ($query) => $query - ->where('user_id', auth()->id()) + ->where('organization_id', $organizationId) ->where('parent_id', $parentId)), ]; } - private function folderForUser(int $folderId): Folder + private function activeWorkspaceId(): int { - return Folder::query()->forUser(auth()->id())->findOrFail($folderId); + return (int) auth()->user()->current_organization_id; + } + + private function visibleFolder(int $folderId): Folder + { + return Folder::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->findOrFail($folderId); + } + + private function folderForAction(int $folderId, string $ability): Folder + { + $folder = $this->visibleFolder($folderId); + + abort_unless(auth()->user()->can($ability, $folder), 403); + + return $folder; + } + + private function folderForTodoCreate(int $folderId): Folder + { + $folder = $this->visibleFolder($folderId); + + abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403); + + return $folder; } }; ?> @@ -465,22 +711,36 @@ new #[Title('Folders')] class extends Component @else
-
- -
+ @can('update', $node['folder']) +
+ +
+ @endcan {{ $node['folder']->name }} + + {{ $node['folder']->organization?->name }} + + @if ($node['folder']->visibility === \App\FolderVisibility::Workspace || $node['folder']->shares_count > 0) + + {{ __('Shared') }} + + @endif
- - - + @can('manageShares', $node['folder']) + + + + @endcan + @can('update', $node['folder']) + + + + @endcan - - - - - - - - - - - - + @can('create', [App\Models\Todo::class, $node['folder']]) + + + + @endcan + @can('createChild', $node['folder']) + + + + @endcan + @can('update', $node['folder']) + + + + + + + @endcan
@endif @@ -739,4 +1018,129 @@ new #[Title('Folders')] class extends Component + + + @if ($this->sharingFolder !== null) +
+
+ {{ __('Share folder') }} + + {{ __('Manage who can access ":name" and what they can do.', ['name' => $this->sharingFolder->name]) }} + +
+ + @if ($this->sharingFolder->organization !== null && ! $this->sharingFolder->organization->isPersonal()) + + {{ __('Visibility') }} + + @foreach (FolderVisibility::cases() as $visibility) + {{ $visibility->label() }} + @endforeach + + + + {{ __('Workspace folders are visible to every member of :name.', ['name' => $this->sharingFolder->organization->name]) }} + + + @else + + {{ __('This folder is only visible to you. Personal workspaces cannot hold other members.') }} + + @endif + +
+ {{ __('Collaborators') }} + +
+ {{ $this->sharingFolder->user?->name }} + {{ __('Owner') }} +
+ + @forelse ($this->sharingCollaborators as $collaborator) +
+
+ {{ $collaborator->name }} + {{ $collaborator->email }} +
+
+ + @foreach (FolderRole::assignable() as $role) + {{ $role->label() }} + @endforeach + + +
+
+ @empty + {{ __('No one else has access yet.') }} + @endforelse +
+ +
+ {{ __('Invite by email') }} +
+
+ + +
+
+ + @foreach (FolderRole::assignable() as $role) + {{ $role->label() }} + @endforeach + + +
+ + {{ __('Send invite') }} + +
+
+ + @if ($this->sharingInvitations->isNotEmpty()) +
+ {{ __('Pending invitations') }} + @foreach ($this->sharingInvitations as $invitation) +
+
+ {{ $invitation->email }} + {{ $invitation->roleLabel() }} +
+ + {{ __('Revoke') }} + +
+ @endforeach +
+ @endif + +
+ + {{ __('Done') }} + +
+
+ @endif +
\ No newline at end of file diff --git a/resources/views/pages/⚡todos.blade.php b/resources/views/pages/⚡todos.blade.php index 2134d9f..ce690b0 100644 --- a/resources/views/pages/⚡todos.blade.php +++ b/resources/views/pages/⚡todos.blade.php @@ -52,7 +52,7 @@ new #[Title('Todos')] class extends Component $folderId = (int) $folderId; - if (Folder::query()->forUser(auth()->id())->whereKey($folderId)->exists()) { + if (Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($folderId)->exists()) { $this->folderId = $folderId; } } @@ -90,7 +90,7 @@ new #[Title('Todos')] class extends Component public function openEditForm(int $todoId): void { - $todo = $this->todoForUser($todoId); + $todo = $this->todoForAction($todoId, 'update'); $this->editingTodoId = $todo->id; $this->description = $todo->description; @@ -110,11 +110,20 @@ new #[Title('Todos')] class extends Component 'todoStatus' => ['required', Rule::enum(TodoStatus::class)], 'dueDate' => ['nullable', 'date'], 'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()], - 'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->where('user_id', auth()->id())], + 'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->whereIn( + 'id', + Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->select('folders.id') + )], ]); + $folder = Folder::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->findOrFail($validated['formFolderId']); + + abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403); + $data = [ - 'folder_id' => $validated['formFolderId'], + 'folder_id' => $folder->id, 'description' => $validated['description'], 'status' => TodoStatus::from($validated['todoStatus']), 'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null, @@ -122,11 +131,11 @@ new #[Title('Todos')] class extends Component ]; if ($this->editingTodoId !== null) { - $this->todoForUser($this->editingTodoId)->update($data); + $this->todoForAction($this->editingTodoId, 'update')->update($data); } else { Todo::create($data + [ 'user_id' => auth()->id(), - 'position' => Todo::nextPositionFor(auth()->user()), + 'position' => Todo::nextPositionFor($folder), ]); } @@ -135,7 +144,7 @@ new #[Title('Todos')] class extends Component public function toggleComplete(int $todoId): void { - $todo = $this->todoForUser($todoId); + $todo = $this->todoForAction($todoId, 'markComplete'); $data = ['completed_at' => $todo->completed_at === null ? now() : null]; @@ -150,7 +159,7 @@ new #[Title('Todos')] class extends Component public function confirmTodoDelete(int $todoId): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'delete'); $this->confirmingTodoDelete = $todoId; $this->modal('confirm-todo-delete')->show(); @@ -158,7 +167,7 @@ new #[Title('Todos')] class extends Component public function deleteTodo(): void { - $this->todoForUser($this->confirmingTodoDelete)->delete(); + $this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete(); $this->confirmingTodoDelete = null; $this->modal('confirm-todo-delete')->close(); @@ -181,7 +190,7 @@ new #[Title('Todos')] class extends Component #[Computed] public function folderTree(): Collection { - return Folder::treeForUser(auth()->id()); + return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId()); } #[Computed] @@ -243,7 +252,7 @@ new #[Title('Todos')] class extends Component public function moveTodo(int $todoId, string $direction): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'update'); $ids = $this->orderedTodoIds; $currentIndex = array_search($todoId, $ids, true); @@ -263,7 +272,7 @@ new #[Title('Todos')] class extends Component public function handleSort(int $todoId, int $position): void { - $this->todoForUser($todoId); + $this->todoForAction($todoId, 'update'); $this->reorderTodo($todoId, $position); } @@ -294,7 +303,7 @@ new #[Title('Todos')] class extends Component unset($visibleOrder[$currentIndex]); array_splice($visibleOrder, $newIndex, 0, $todoId); - $ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all(); + $ids = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->priority()->pluck('id')->all(); $slots = array_keys(array_intersect($ids, $visibleIds)); @@ -303,7 +312,7 @@ new #[Title('Todos')] class extends Component } foreach ($ids as $position => $id) { - Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); + Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($id)->update(['position' => $position]); } unset($this->todos, $this->orderedTodoIds); @@ -315,7 +324,7 @@ new #[Title('Todos')] class extends Component private function filteredTodoQuery(): Builder { return Todo::query() - ->forUser(auth()->id()) + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) ->when( $this->search !== '', fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%') @@ -346,9 +355,21 @@ new #[Title('Todos')] class extends Component return $ids; } - private function todoForUser(int $todoId): Todo + private function todoForAction(int $todoId, string $ability): Todo { - return Todo::query()->forUser(auth()->id())->findOrFail($todoId); + $todo = Todo::query() + ->visibleTo(auth()->id(), $this->activeWorkspaceId()) + ->with('folder') + ->findOrFail($todoId); + + abort_unless(auth()->user()->can($ability, $todo), 403); + + return $todo; + } + + private function activeWorkspaceId(): int + { + return (int) auth()->user()->current_organization_id; } }; ?> @@ -424,18 +445,22 @@ new #[Title('Todos')] class extends Component @forelse ($this->todos as $todo) -
- -
+ @can('update', $todo) +
+ +
+ @endcan
- + @can('markComplete', $todo) + + @endcan @@ -491,44 +516,46 @@ new #[Title('Todos')] class extends Component
- @if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) + @can('update', $todo) + @if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) + + @endif + + @if ($todo->id !== ($this->orderedTodoIds[array_key_last($this->orderedTodoIds)] ?? null)) + + @endif + - @endif - - @if ($todo->id !== ($this->orderedTodoIds[array_key_last($this->orderedTodoIds)] ?? null)) - @endif - - - + @endcan
diff --git a/routes/web.php b/routes/web.php index 2f55078..7f9cdcc 100644 --- a/routes/web.php +++ b/routes/web.php @@ -10,14 +10,24 @@ Route::livewire('pricing', 'pages::pricing')->name('pricing'); Route::middleware(['auth'])->group(function () { Route::livewire('subscription/confirmed', 'pages::subscription-confirmed')->name('subscription.confirmed'); + + // Reachable without an active subscription so a newly invited user can + // redeem their invitation; the app itself still requires one. + Route::livewire('invitations/{invitation:token}', 'pages::invitations.accept')->name('invitations.accept'); }); Route::middleware(['auth', 'verified', 'subscribed'])->group(function () { Route::livewire('dashboard', 'pages::dashboard')->name('dashboard'); Route::livewire('todos', 'pages::todos')->name('todos'); Route::livewire('folders', 'pages::folders')->name('folders'); - Route::livewire('admin/notes-limits', 'pages::admin.notes-limits')->name('admin.notes-limits'); - Route::livewire('admin/plan-pricing', 'pages::admin.plan-pricing')->name('admin.plan-pricing'); + Route::livewire('members', 'pages::workspace.members')->name('members'); + + // Site-wide administration, open only to users flagged as site admins. + // Organization owners/admins are not site admins and cannot reach these. + Route::middleware('admin')->group(function () { + Route::livewire('admin/notes-limits', 'pages::admin.notes-limits')->name('admin.notes-limits'); + Route::livewire('admin/plan-pricing', 'pages::admin.plan-pricing')->name('admin.plan-pricing'); + }); }); require __DIR__.'/settings.php'; diff --git a/tests/Feature/AdminNotesLimitsTest.php b/tests/Feature/AdminNotesLimitsTest.php index 7e5bf87..d56b6d9 100644 --- a/tests/Feature/AdminNotesLimitsTest.php +++ b/tests/Feature/AdminNotesLimitsTest.php @@ -1,6 +1,8 @@ get(route('admin.notes-limits'))->assertForbidden(); }); +test('workspace admins are not site admins and cannot access the notes limits page', function () { + $workspaceAdmin = User::factory()->create(); + $organization = Organization::factory()->family() + ->withMember($workspaceAdmin, OrganizationRole::Admin) + ->create(); + + $this->actingAs($workspaceAdmin); + + expect($organization->userHasRole($workspaceAdmin, OrganizationRole::Admin))->toBeTrue(); + + $this->get(route('admin.notes-limits'))->assertForbidden(); +}); + +test('a non-admin cannot save a notes limit through a direct action call', function () { + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + $member = User::factory()->create(); + + $component = Livewire::test('pages::admin.notes-limits')->call('startEditLimit', $member->id); + + $this->actingAs($member); + + $component->set('notesLimitInput', '2500')->call('saveNotesLimit')->assertForbidden(); + + expect($member->fresh()->notes_limit)->toBe(1000); +}); + test('non-admins do not see the notes limits navigation item', function () { $user = User::factory()->create(); $this->actingAs($user); @@ -33,6 +63,36 @@ test('admins see the notes limits navigation item', function () { ->assertSee('Notes limits'); }); +test('site admins see the site admin navigation group', function () { + $user = User::factory()->asAdmin()->create(); + $this->actingAs($user); + + $this->get(route('dashboard')) + ->assertOk() + ->assertSee('Site admin'); +}); + +test('workspace admins do not see the site admin navigation group', function () { + $workspaceAdmin = User::factory()->create(); + Organization::factory()->family() + ->withMember($workspaceAdmin, OrganizationRole::Admin) + ->create(); + + $this->actingAs($workspaceAdmin); + + $this->get(route('dashboard')) + ->assertOk() + ->assertDontSee('Site admin'); +}); + +test('the notes limits page identifies site administrators', function () { + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + Livewire::test('pages::admin.notes-limits') + ->assertSee('Site admin'); +}); + test('admins can view the notes limits page', function () { $user = User::factory()->asAdmin()->create(); $this->actingAs($user); @@ -70,3 +130,46 @@ test('a notes limit must be a valid positive number', function () { expect($member->fresh()->notes_limit)->toBe(1000); }); + +test('admins can search users by name or email', function () { + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + $match = User::factory()->create(['name' => 'Ada Lovelace', 'email' => 'ada@example.com']); + $emailMatch = User::factory()->create(['name' => 'Grace Hopper', 'email' => 'grace@searchable.test']); + $other = User::factory()->create(['name' => 'Alan Turing', 'email' => 'alan@example.com']); + + Livewire::test('pages::admin.notes-limits') + ->set('search', 'lovelace') + ->assertSee('Ada Lovelace') + ->assertDontSee('Alan Turing') + ->set('search', 'searchable.test') + ->assertSee('Grace Hopper') + ->assertDontSee($match->name) + ->assertDontSee($other->name); +}); + +test('searching resets the page', function () { + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + User::factory()->count(11)->create(); + + Livewire::test('pages::admin.notes-limits') + ->call('gotoPage', 2) + ->assertSet('paginators.page', 2) + ->set('search', 'anything') + ->assertSet('paginators.page', 1); +}); + +test('the notes limits list is paginated', function () { + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + User::factory()->count(12)->create(); + + $component = Livewire::test('pages::admin.notes-limits'); + + expect($component->instance()->users->perPage())->toBe(10) + ->and($component->instance()->users->total())->toBe(13); +}); diff --git a/tests/Feature/BaseDataSeederTest.php b/tests/Feature/BaseDataSeederTest.php index 0c54f50..f5f431c 100644 --- a/tests/Feature/BaseDataSeederTest.php +++ b/tests/Feature/BaseDataSeederTest.php @@ -13,7 +13,7 @@ test('base data includes a default admin user', function () { expect($admin)->not->toBeNull() ->and($admin->name)->toBe('Administrator') ->and($admin->notes_limit)->toBe(1000); - $this->assertTrue($admin->isAdmin()); + $this->assertTrue($admin->isSiteAdmin()); }); test('base data seeding is idempotent', function () { diff --git a/tests/Feature/Billing/PlanPricingTest.php b/tests/Feature/Billing/PlanPricingTest.php index 4a3e4bc..526bdb7 100644 --- a/tests/Feature/Billing/PlanPricingTest.php +++ b/tests/Feature/Billing/PlanPricingTest.php @@ -3,6 +3,7 @@ use App\Models\Organization; use App\Models\Setting; use App\Models\User; +use App\OrganizationRole; use Livewire\Livewire; test('guests are redirected from the plan pricing page', function () { @@ -16,6 +17,38 @@ test('non-admins cannot access the plan pricing page', function () { $this->get(route('admin.plan-pricing'))->assertForbidden(); }); +test('workspace admins are not site admins and cannot access the plan pricing page', function () { + $workspaceAdmin = User::factory()->create(); + $organization = Organization::factory()->family() + ->withMember($workspaceAdmin, OrganizationRole::Admin) + ->create(); + + $this->actingAs($workspaceAdmin); + + expect($organization->userHasRole($workspaceAdmin, OrganizationRole::Admin))->toBeTrue(); + + $this->get(route('admin.plan-pricing'))->assertForbidden(); +}); + +test('a non-admin cannot save plan amounts through a direct action call', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $admin = User::factory()->asAdmin()->create(); + $this->actingAs($admin); + + $member = User::factory()->create(); + + $component = Livewire::test('pages::admin.plan-pricing'); + + $this->actingAs($member); + + $component->set('amounts.pro', '99.00')->call('saveAmounts')->assertForbidden(); + + expect(Organization::planAmount('pro'))->toBe(1000); +}); + test('non-admins do not see the plan pricing navigation item', function () { $this->actingAs(User::factory()->create()); diff --git a/tests/Feature/FolderAccessTest.php b/tests/Feature/FolderAccessTest.php new file mode 100644 index 0000000..3b78908 --- /dev/null +++ b/tests/Feature/FolderAccessTest.php @@ -0,0 +1,276 @@ +family()->withMember($owner)->create(); + $owner->forceFill(['current_organization_id' => $org->id])->save(); + + return $org; +} + +function addWorkspaceMember(Organization $org, User $user, OrganizationRole $role = OrganizationRole::Member): void +{ + $org->users()->attach($user, ['role' => $role->value]); +} + +test('the folder creating hook assigns the owner workspace and personal folders stay private', function () { + $user = User::factory()->create(); + + $folder = Folder::factory()->for($user)->create(['name' => 'Personal Project']); + + expect($folder->organization_id)->toBe($user->current_organization_id); + expect($folder->visibility)->toBe(FolderVisibility::Private); +}); + +test('folders in a family workspace default to workspace visibility', function () { + $owner = User::factory()->create(); + familyWorkspace($owner); + + $folder = Folder::factory()->for($owner)->create(['name' => 'Shared List']); + + expect($folder->organization_id)->toBe($owner->current_organization_id); + expect($folder->visibility)->toBe(FolderVisibility::Workspace); +}); + +test('the todo creating hook inherits the workspace of its folder', function () { + $user = User::factory()->create(); + $folder = Folder::factory()->for($user)->create(['name' => 'Work']); + + $todo = Todo::factory()->for($folder)->create(['description' => 'A task']); + + expect($todo->organization_id)->toBe($folder->organization_id); +}); + +test('the folder owner holds admin on their own folder', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Mine']); + + expect($folder->effectiveRoleFor($owner))->toBe(FolderRole::Admin); +}); + +test('a workspace member sees workspace folders as a viewer', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + + expect($folder->effectiveRoleFor($member))->toBe(FolderRole::Viewer); +}); + +test('a workspace admin holds admin on workspace folders', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $admin = User::factory()->create(); + addWorkspaceMember($org, $admin, OrganizationRole::Admin); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + + expect($folder->effectiveRoleFor($admin))->toBe(FolderRole::Admin); +}); + +test('an explicit share grants the shared role on a private folder', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Private']); + + $folder->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + expect($folder->effectiveRoleFor($member))->toBe(FolderRole::Editor); +}); + +test('the strongest of overlapping roles wins', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + $folder->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + expect($folder->effectiveRoleFor($member))->toBe(FolderRole::Editor); +}); + +test('a workspace member cannot access a private folder', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Private']); + + expect($folder->effectiveRoleFor($member))->toBeNull(); +}); + +test('a share on a parent folder cascades to its descendants', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + + $parent = Folder::factory()->for($owner)->private()->create(['name' => 'Parent']); + $child = Folder::factory()->childOf($parent)->private()->create(['name' => 'Child']); + + $parent->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + expect($parent->effectiveRoleFor($member))->toBe(FolderRole::Editor); + expect($child->effectiveRoleFor($member))->toBe(FolderRole::Editor); +}); + +test('a private folder drops out of inherited workspace access', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $parent = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Parent']); + $child = Folder::factory()->childOf($parent)->private()->create(['name' => 'Private Child']); + + expect($parent->effectiveRoleFor($member))->toBe(FolderRole::Viewer); + expect($child->effectiveRoleFor($member))->toBeNull(); +}); + +test('the visibleTo scope covers workspace folders and excludes strangers', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + $stranger = User::factory()->create(); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + + expect(Folder::query()->visibleTo($member)->pluck('id'))->toContain($folder->id); + expect(Folder::query()->visibleTo($stranger)->pluck('id'))->not->toContain($folder->id); +}); + +test('the visibleTo scope includes folders shared with the user anywhere', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Shared With Me']); + $stranger = User::factory()->create(); + + $folder->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + expect(Folder::query()->visibleTo($member)->pluck('id'))->toContain($folder->id); + expect(Folder::query()->visibleTo($stranger)->pluck('id'))->not->toContain($folder->id); +}); + +test('todo visibility follows the folder access', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + $stranger = User::factory()->create(); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + $todo = Todo::factory()->for($folder)->create(['description' => 'Shared task']); + + expect(Todo::query()->visibleTo($member)->pluck('id'))->toContain($todo->id); + expect(Todo::query()->visibleTo($stranger)->pluck('id'))->not->toContain($todo->id); +}); + +test('workspace members can view workspace folders', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + + $this->actingAs($member); + expect($member->can('view', $folder))->toBeTrue(); +}); + +test('strangers cannot view folders they have no role on', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Private']); + $stranger = User::factory()->create(); + + $this->actingAs($stranger); + expect($stranger->can('view', $folder))->toBeFalse(); +}); + +test('viewers cannot rename a folder', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + + $folder = Folder::factory()->for($owner)->sharedWithWorkspace()->create(['name' => 'Shared']); + + $this->actingAs($member); + expect($member->can('update', $folder))->toBeFalse(); +}); + +test('a folder admin can share a folder and create folders beneath it', function () { + $owner = User::factory()->create(); + $admin = User::factory()->create(); + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Dir']); + + $folder->shares()->attach($admin, ['role' => FolderRole::Admin->value]); + + $this->actingAs($admin); + expect($admin->can('manageShares', $folder))->toBeTrue(); + expect($admin->can('createChild', $folder))->toBeTrue(); +}); + +test('only workspace admins create top-level folders', function () { + $owner = User::factory()->create(); + $org = familyWorkspace($owner); + $member = User::factory()->create(); + addWorkspaceMember($org, $member); + $workspaceAdmin = User::factory()->create(); + addWorkspaceMember($org, $workspaceAdmin, OrganizationRole::Admin); + + $this->actingAs($member); + expect($member->can('create', [Folder::class, $org]))->toBeFalse(); + + $this->actingAs($workspaceAdmin); + expect($workspaceAdmin->can('create', [Folder::class, $org]))->toBeTrue(); +}); + +test('editors can add and edit todos while markers only mark complete', function () { + $owner = User::factory()->create(); + $editor = User::factory()->create(); + $marker = User::factory()->create(); + $viewer = User::factory()->create(); + + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Dir']); + $folder->shares()->attach($editor, ['role' => FolderRole::Editor->value]); + $folder->shares()->attach($marker, ['role' => FolderRole::Marker->value]); + $folder->shares()->attach($viewer, ['role' => FolderRole::Viewer->value]); + + $todo = Todo::factory()->for($folder)->create(['description' => 'A task']); + + $this->actingAs($editor); + expect($editor->can('create', [Todo::class, $folder]))->toBeTrue(); + expect($editor->can('update', $todo))->toBeTrue(); + + $this->actingAs($marker); + expect($marker->can('create', [Todo::class, $folder]))->toBeFalse(); + expect($marker->can('update', $todo))->toBeFalse(); + expect($marker->can('markComplete', $todo))->toBeTrue(); + + $this->actingAs($viewer); + expect($viewer->can('markComplete', $todo))->toBeFalse(); +}); + +test('strangers cannot touch todos in a folder', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->private()->create(['name' => 'Dir']); + $todo = Todo::factory()->for($folder)->create(['description' => 'A task']); + $stranger = User::factory()->create(); + + $this->actingAs($stranger); + expect($stranger->can('view', $todo))->toBeFalse(); + expect($stranger->can('update', $todo))->toBeFalse(); + expect($stranger->can('delete', $todo))->toBeFalse(); + expect($stranger->can('markComplete', $todo))->toBeFalse(); +}); diff --git a/tests/Feature/FolderSharingTest.php b/tests/Feature/FolderSharingTest.php new file mode 100644 index 0000000..aaaf7b8 --- /dev/null +++ b/tests/Feature/FolderSharingTest.php @@ -0,0 +1,137 @@ +family()->withMember($owner)->create(); + $owner->forceFill(['current_organization_id' => $organization->id])->save(); + + return $organization; +} + +test('a folder admin can invite a collaborator by email', function () { + Mail::fake(); + + $owner = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $folder = Folder::factory()->for($owner)->inOrganization($organization)->create(['name' => 'Dir']); + + $this->actingAs($owner); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->set('inviteEmail', 'New.Person@example.com') + ->set('inviteRole', FolderRole::Editor->value) + ->call('inviteCollaborator') + ->assertHasNoErrors(); + + $this->assertDatabaseHas('invitations', [ + 'inviteable_type' => Folder::class, + 'inviteable_id' => $folder->id, + 'email' => 'new.person@example.com', + 'role' => FolderRole::Editor->value, + ]); + + Mail::assertSent(InvitationMail::class); +}); + +test('inviting someone who already has access is rejected', function () { + Mail::fake(); + + $owner = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $collaborator = User::factory()->create(); + $folder = Folder::factory()->for($owner)->inOrganization($organization)->create(['name' => 'Dir']); + $folder->shares()->attach($collaborator, ['role' => FolderRole::Editor->value]); + + $this->actingAs($owner); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->set('inviteEmail', $collaborator->email) + ->call('inviteCollaborator') + ->assertHasErrors('inviteEmail'); + + Mail::assertNothingSent(); +}); + +test('a folder admin can change and remove a collaborator', function () { + $owner = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $collaborator = User::factory()->create(); + $folder = Folder::factory()->for($owner)->inOrganization($organization)->create(['name' => 'Dir']); + $folder->shares()->attach($collaborator, ['role' => FolderRole::Editor->value]); + + $this->actingAs($owner); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->set('collaboratorRoles.'.$collaborator->id, FolderRole::Viewer->value) + ->assertHasNoErrors(); + + expect($folder->sharedRoleFor($collaborator))->toBe(FolderRole::Viewer); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->call('removeCollaborator', $collaborator->id); + + expect($folder->sharedRoleFor($collaborator))->toBeNull(); +}); + +test('a folder admin can share a folder with the whole workspace', function () { + $owner = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $folder = Folder::factory()->for($owner)->inOrganization($organization)->private()->create(['name' => 'Dir']); + + $this->actingAs($owner); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->set('shareVisibility', FolderVisibility::Workspace->value) + ->assertHasNoErrors(); + + expect($folder->fresh()->visibility)->toBe(FolderVisibility::Workspace); +}); + +test('a folder admin can revoke a pending invitation', function () { + $owner = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $folder = Folder::factory()->for($owner)->inOrganization($organization)->create(['name' => 'Dir']); + $invitation = Invitation::factory()->forFolder($folder)->create(['inviter_id' => $owner->id]); + + $this->actingAs($owner); + + Livewire::test('pages::folders') + ->call('startShare', $folder->id) + ->call('revokeFolderInvitation', $invitation->id); + + $this->assertDatabaseMissing('invitations', ['id' => $invitation->id]); +}); + +test('a non-admin cannot open the share panel', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = familyWorkspaceFor($owner); + $organization->users()->attach($member, ['role' => OrganizationRole::Member->value]); + $member->forceFill(['current_organization_id' => $organization->id])->save(); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Dir']); + + $this->actingAs($member); + + Livewire::test('pages::folders')->call('startShare', $folder->id)->assertStatus(403); +}); diff --git a/tests/Feature/FoldersTest.php b/tests/Feature/FoldersTest.php index dff39a0..4b9a562 100644 --- a/tests/Feature/FoldersTest.php +++ b/tests/Feature/FoldersTest.php @@ -334,6 +334,25 @@ test('users cannot move a todo to another user folder', function () { ->call('moveTodoToFolder', $todo->id, $foreign->id); }); +test('the folder tree knows which workspace each folder belongs to', function () { + $user = User::factory()->create(); + $work = Folder::factory()->for($user)->create(['name' => 'Work']); + + $node = Folder::treeForUser($user)->first()['folder']; + + expect($node->organization?->name)->toBe($user->currentOrganization()->first()->name); +}); + +test('folders show which workspace they belong to', function () { + $user = User::factory()->create(); + $work = Folder::factory()->for($user)->create(['name' => 'Work']); + $this->actingAs($user); + + Livewire::test('pages::folders') + ->assertSee($user->currentOrganization()->first()->name) + ->assertSeeHtml('data-test="folder-workspace-'.$work->id.'"', false); +}); + test('users cannot move another user todo', function () { $owner = User::factory()->create(); $ownerFolder = Folder::factory()->for($owner)->create(['name' => 'Owner Folder']); diff --git a/tests/Feature/InvitationAcceptPageTest.php b/tests/Feature/InvitationAcceptPageTest.php new file mode 100644 index 0000000..b4811f1 --- /dev/null +++ b/tests/Feature/InvitationAcceptPageTest.php @@ -0,0 +1,103 @@ +create(); + + $this->get(route('invitations.accept', $invitation->token)) + ->assertRedirect(route('login')); +}); + +test('an authenticated invitee can load the accept page through its token', function () { + $invitation = Invitation::factory()->create(); + + $this->actingAs(User::factory()->create()) + ->get(route('invitations.accept', $invitation->token)) + ->assertOk() + ->assertSee('Accept invitation'); +}); + +test('an authenticated user can accept a folder invitation', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $invitee = User::factory()->create(); + + $invitation = Invitation::factory()->forFolder($folder, FolderRole::Editor)->create(); + + $this->actingAs($invitee); + + Livewire::test('pages::invitations.accept', ['invitation' => $invitation]) + ->call('accept') + ->assertRedirect(route('dashboard')); + + expect($folder->sharedRoleFor($invitee))->toBe(FolderRole::Editor); +}); + +test('an authenticated user can accept a workspace invitation', function () { + $owner = User::factory()->create(); + $organization = Organization::factory()->family()->withMember($owner)->create(); + $invitee = User::factory()->create(); + + $invitation = Invitation::factory()->forOrganization($organization)->create(); + + $this->actingAs($invitee); + + Livewire::test('pages::invitations.accept', ['invitation' => $invitation]) + ->call('accept') + ->assertRedirect(route('dashboard')); + + expect($organization->users()->where('users.id', $invitee->id)->exists())->toBeTrue(); + expect($invitee->fresh()->current_organization_id)->toBe($organization->id); +}); + +test('a full workspace refuses a workspace invitation', function () { + $owner = User::factory()->create(); + $organization = Organization::factory()->family()->withMember($owner)->create(); + + for ($i = 0; $i < 5; $i++) { + $organization->users()->attach(User::factory()->create(), ['role' => OrganizationRole::Member->value]); + } + + $invitee = User::factory()->create(); + $invitation = Invitation::factory()->forOrganization($organization)->create(); + + $this->actingAs($invitee); + + Livewire::test('pages::invitations.accept', ['invitation' => $invitation]) + ->call('accept') + ->assertHasErrors('invitation'); + + expect($organization->users()->where('users.id', $invitee->id)->exists())->toBeFalse(); +}); + +test('an accepted invitation shows its accepted state and grants nothing new', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $invitee = User::factory()->create(); + $invitation = Invitation::factory()->forFolder($folder)->accepted()->create(); + + $this->actingAs($invitee); + + Livewire::test('pages::invitations.accept', ['invitation' => $invitation]) + ->assertSeeHtml('data-test="invitation-accepted"') + ->call('accept'); + + expect($folder->sharedRoleFor($invitee))->toBeNull(); +}); + +test('an expired invitation shows its expired state', function () { + $invitation = Invitation::factory()->expired()->create(); + $invitee = User::factory()->create(); + + $this->actingAs($invitee); + + Livewire::test('pages::invitations.accept', ['invitation' => $invitation]) + ->assertSeeHtml('data-test="invitation-expired"'); +}); diff --git a/tests/Feature/InvitationTest.php b/tests/Feature/InvitationTest.php new file mode 100644 index 0000000..49ff875 --- /dev/null +++ b/tests/Feature/InvitationTest.php @@ -0,0 +1,177 @@ +create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + + $invitation = Invitation::factory()->forFolder($folder, FolderRole::Editor)->create(); + + expect($invitation->inviteable()->first())->toBeInstanceOf(Folder::class); + expect($invitation->inviteable->is($folder))->toBeTrue(); + expect($invitation->role)->toBe(FolderRole::Editor->value); + expect($invitation->isValid())->toBeTrue(); +}); + +test('a workspace invitation resolves its inviteable and stays valid', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + + $invitation = Invitation::factory()->forOrganization($org, OrganizationRole::Member->value)->create(); + + expect($invitation->inviteable->is($org))->toBeTrue(); + expect($invitation->isValid())->toBeTrue(); +}); + +test('an invitation that has been redeemed is no longer valid', function () { + $invitation = Invitation::factory()->accepted()->create(); + + expect($invitation->isAccepted())->toBeTrue(); + expect($invitation->isValid())->toBeFalse(); +}); + +test('an invitation that has lapsed is no longer valid', function () { + $invitation = Invitation::factory()->expired()->create(); + + expect($invitation->isExpired())->toBeTrue(); + expect($invitation->isValid())->toBeFalse(); +}); + +test('an invitation token is unique', function () { + $invitation = Invitation::factory()->create(); + + expect(Invitation::query()->where('token', $invitation->token)->count())->toBe(1); +}); + +test('only folder admins can invite people into a folder', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $editor = User::factory()->create(); + $folder->shares()->attach($editor, ['role' => FolderRole::Editor->value]); + $admin = User::factory()->create(); + $folder->shares()->attach($admin, ['role' => FolderRole::Admin->value]); + + $this->actingAs($editor); + expect($editor->can('create', [Invitation::class, $folder]))->toBeFalse(); + + $this->actingAs($admin); + expect($admin->can('create', [Invitation::class, $folder]))->toBeTrue(); +}); + +test('only workspace admins can invite people into a workspace', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + $member = User::factory()->create(); + $org->users()->attach($member, ['role' => OrganizationRole::Member->value]); + $admin = User::factory()->create(); + $org->users()->attach($admin, ['role' => OrganizationRole::Admin->value]); + + $this->actingAs($member); + expect($member->can('create', [Invitation::class, $org]))->toBeFalse(); + + $this->actingAs($admin); + expect($admin->can('create', [Invitation::class, $org]))->toBeTrue(); +}); + +test('an invitation can be revoked by its sender or a folder admin', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $inviter = User::factory()->create(); + + $invitation = Invitation::factory()->forFolder($folder)->create(['inviter_id' => $inviter->id]); + + $stranger = User::factory()->create(); + $this->actingAs($stranger); + expect($stranger->can('delete', $invitation))->toBeFalse(); + + $this->actingAs($inviter); + expect($inviter->can('delete', $invitation))->toBeTrue(); +}); + +test('the pending scope omits accepted and expired invitations', function () { + Invitation::factory()->create(); + Invitation::factory()->accepted()->create(); + Invitation::factory()->expired()->create(); + + expect(Invitation::query()->pending()->count())->toBe(1); +}); + +test('the role helpers reflect the kind of inviteable', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + + $folderInvitation = Invitation::factory()->forFolder($folder, FolderRole::Marker)->create(); + + expect($folderInvitation->isForFolder())->toBeTrue(); + expect($folderInvitation->isForWorkspace())->toBeFalse(); + expect($folderInvitation->folderRole())->toBe(FolderRole::Marker); + expect($folderInvitation->organizationRole())->toBeNull(); + expect($folderInvitation->roleLabel())->toBe('Marker'); + + $organization = Organization::factory()->family()->withMember($owner)->create(); + $workspaceInvitation = Invitation::factory()->forOrganization($organization, OrganizationRole::Admin->value)->create(); + + expect($workspaceInvitation->isForWorkspace())->toBeTrue(); + expect($workspaceInvitation->organizationRole())->toBe(OrganizationRole::Admin); + expect($workspaceInvitation->folderRole())->toBeNull(); + expect($workspaceInvitation->roleLabel())->toBe('Admin'); +}); + +test('accepting a folder invitation grants the shared role and records the acceptor', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $invitee = User::factory()->create(); + + $invitation = Invitation::factory()->forFolder($folder, FolderRole::Editor)->create(); + + $invitation->accept($invitee); + + expect($folder->sharedRoleFor($invitee))->toBe(FolderRole::Editor); + expect($invitation->fresh()->isAccepted())->toBeTrue(); + expect($invitation->fresh()->accepted_by_id)->toBe($invitee->id); +}); + +test('accepting a workspace invitation adds the member and switches their active workspace', function () { + $owner = User::factory()->create(); + $organization = Organization::factory()->family()->withMember($owner)->create(); + $invitee = User::factory()->create(); + + $invitation = Invitation::factory()->forOrganization($organization)->create(); + + $invitation->accept($invitee); + + expect($organization->users()->where('users.id', $invitee->id)->exists())->toBeTrue(); + expect($invitee->fresh()->current_organization_id)->toBe($organization->id); +}); + +test('an expired invitation cannot be accepted', function () { + $owner = User::factory()->create(); + $folder = Folder::factory()->for($owner)->create(['name' => 'Dir']); + $invitee = User::factory()->create(); + + $invitation = Invitation::factory()->forFolder($folder)->expired()->create(); + + $invitation->accept($invitee); + + expect($folder->sharedRoleFor($invitee))->toBeNull(); + expect($invitation->fresh()->accepted_at)->toBeNull(); +}); + +test('the invitation mail links to the accept page with the invite details', function () { + $owner = User::factory()->create(['name' => 'Ada Owner']); + $folder = Folder::factory()->for($owner)->create(['name' => 'Shared Dir']); + $invitation = Invitation::factory()->forFolder($folder, FolderRole::Editor)->create(['inviter_id' => $owner->id]); + + $rendered = (new InvitationMail($invitation))->render(); + + expect($rendered)->toContain('Shared Dir'); + expect($rendered)->toContain('Ada Owner'); + expect($rendered)->toContain(route('invitations.accept', $invitation->token)); +}); diff --git a/tests/Feature/SharedAccessPagesTest.php b/tests/Feature/SharedAccessPagesTest.php new file mode 100644 index 0000000..ffb5823 --- /dev/null +++ b/tests/Feature/SharedAccessPagesTest.php @@ -0,0 +1,180 @@ +family()->withMember($owner)->create(); + $owner->forceFill(['current_organization_id' => $organization->id])->save(); + + if ($member !== null) { + $organization->users()->attach($member, ['role' => $role->value]); + $member->forceFill(['current_organization_id' => $organization->id])->save(); + } + + return $organization; +} + +test('a workspace member sees a workspace folder on the folders page', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + + $this->actingAs($member); + + Livewire::test('pages::folders') + ->assertSee('Shared List') + ->assertSeeHtml('data-test="folder-row-'.$folder->id.'"'); +}); + +test('a workspace member sees workspace todos on the todos page and dashboard', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + $todo = Todo::factory()->recycle($owner)->for($folder)->create(['description' => 'Shared task']); + + $this->actingAs($member); + + Livewire::test('pages::todos') + ->assertSee('Shared task') + ->assertSeeHtml('data-test="todo-description-'.$todo->id.'"'); + + Livewire::test('pages::dashboard') + ->assertSee('Shared task') + ->assertSet('todoCounts.open', 1); +}); + +test('a workspace member cannot access another members private folders', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + Folder::factory()->for($owner)->inOrganization($organization)->private()->create(['name' => 'Owner Private']); + + $this->actingAs($member); + + Livewire::test('pages::folders')->assertDontSee('Owner Private'); +}); + +test('a viewer can see a shared folder but not manage it', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + + $this->actingAs($member); + + Livewire::test('pages::folders') + ->assertSeeHtml('data-test="view-todos-'.$folder->id.'"') + ->assertDontSeeHtml('data-test="rename-folder-'.$folder->id.'"') + ->assertDontSeeHtml('data-test="delete-folder-'.$folder->id.'"') + ->assertDontSeeHtml('data-test="add-child-'.$folder->id.'"') + ->assertDontSeeHtml('data-test="add-todo-'.$folder->id.'"'); + + Livewire::test('pages::folders') + ->call('startRename', $folder->id) + ->assertStatus(403); +}); + +test('an editor can create and complete todos in a shared folder', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + $folder->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + $this->actingAs($member); + + Livewire::test('pages::todos') + ->call('openCreateForm') + ->set('description', 'Member task') + ->set('formFolderId', $folder->id) + ->call('saveTodo') + ->assertHasNoErrors(); + + $this->assertDatabaseHas('todos', [ + 'user_id' => $member->id, + 'folder_id' => $folder->id, + 'description' => 'Member task', + ]); + + $todo = Todo::where('description', 'Member task')->firstOrFail(); + + Livewire::test('pages::todos') + ->call('toggleComplete', $todo->id); + + expect($todo->fresh()->completed_at)->not->toBeNull(); +}); + +test('a viewer cannot create todos in a shared folder', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + + $this->actingAs($member); + + Livewire::test('pages::todos') + ->call('openCreateForm') + ->set('description', 'Snooping') + ->set('formFolderId', $folder->id) + ->call('saveTodo') + ->assertStatus(403); + + $this->assertDatabaseCount('todos', 0); +}); + +test('a stranger cannot see or manage another workspace folders', function () { + $owner = User::factory()->create(); + $organization = sharedWorkspace($owner); + + $folder = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + + $stranger = User::factory()->create(); + $this->actingAs($stranger); + + Livewire::test('pages::folders')->assertDontSee('Shared List'); + + expect(fn () => Livewire::test('pages::folders')->call('startRename', $folder->id)) + ->toThrow(ModelNotFoundException::class); +}); + +test('a member cannot move a shared todo into a folder they cannot edit', function () { + $owner = User::factory()->create(); + $member = User::factory()->create(); + $organization = sharedWorkspace($owner, $member); + + $shared = Folder::factory()->for($owner)->inOrganization($organization)->sharedWithWorkspace()->create(['name' => 'Shared List']); + $shared->shares()->attach($member, ['role' => FolderRole::Editor->value]); + + $privateTarget = Folder::factory()->for($owner)->inOrganization($organization)->private()->create(['name' => 'Owner Private']); + + $todo = Todo::factory()->recycle($owner)->for($shared)->create(['description' => 'Movable']); + + $this->actingAs($member); + + // The private target is not visible to the member at all. + expect(fn () => Livewire::test('pages::folders')->call('moveTodoToFolder', $todo->id, $privateTarget->id)) + ->toThrow(ModelNotFoundException::class); + + $this->assertSame($shared->id, $todo->fresh()->folder_id); +}); diff --git a/tests/Feature/WorkspaceMembersTest.php b/tests/Feature/WorkspaceMembersTest.php new file mode 100644 index 0000000..65037a9 --- /dev/null +++ b/tests/Feature/WorkspaceMembersTest.php @@ -0,0 +1,151 @@ +family()->withMember($owner)->create(); + $owner->forceFill(['current_organization_id' => $organization->id])->save(); + + return $organization; +} + +test('a workspace admin can invite a member by email', function () { + Mail::fake(); + + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members') + ->set('inviteEmail', 'Invitee@example.com') + ->set('inviteRole', OrganizationRole::Member->value) + ->call('inviteMember') + ->assertHasNoErrors(); + + $this->assertDatabaseHas('invitations', [ + 'inviteable_type' => Organization::class, + 'inviteable_id' => $organization->id, + 'email' => 'invitee@example.com', + 'role' => OrganizationRole::Member->value, + ]); + + Mail::assertSent(InvitationMail::class); +}); + +test('a full family workspace refuses new member invitations', function () { + Mail::fake(); + + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + + for ($i = 0; $i < 5; $i++) { + $organization->users()->attach(User::factory()->create(), ['role' => OrganizationRole::Member->value]); + } + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members') + ->set('inviteEmail', 'overflow@example.com') + ->call('inviteMember') + ->assertHasErrors('inviteEmail') + ->assertSeeHtml('data-test="workspace-full-notice"'); + + $this->assertDatabaseCount('invitations', 0); + Mail::assertNothingSent(); +}); + +test('a workspace admin can change a member role and remove them', function () { + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + $member = User::factory()->create(); + $organization->users()->attach($member, ['role' => OrganizationRole::Member->value]); + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members') + ->set('memberRoles.'.$member->id, OrganizationRole::Admin->value) + ->assertHasNoErrors(); + + expect($organization->userHasRole($member->fresh(), OrganizationRole::Admin))->toBeTrue(); + + Livewire::test('pages::workspace.members') + ->call('removeMember', $member->id); + + expect($organization->users()->where('users.id', $member->id)->exists())->toBeFalse(); +}); + +test('removing a member moves them back to their personal workspace', function () { + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + $member = User::factory()->create(); + $organization->users()->attach($member, ['role' => OrganizationRole::Member->value]); + $member->forceFill(['current_organization_id' => $organization->id])->save(); + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members')->call('removeMember', $member->id); + + $personal = $member->fresh()->currentOrganization()->first(); + + expect($personal)->not->toBeNull(); + expect($personal->type)->toBe(WorkspaceType::Personal); +}); + +test('the owner cannot be removed', function () { + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members')->call('removeMember', $owner->id); + + expect($organization->users()->where('users.id', $owner->id)->exists())->toBeTrue(); +}); + +test('a workspace admin can revoke a pending invitation', function () { + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + $invitation = Invitation::factory()->forOrganization($organization)->create(['inviter_id' => $owner->id]); + + $this->actingAs($owner); + + Livewire::test('pages::workspace.members') + ->call('revokeInvitation', $invitation->id); + + $this->assertDatabaseMissing('invitations', ['id' => $invitation->id]); +}); + +test('a plain member sees the member list but cannot manage it', function () { + $owner = User::factory()->create(); + $organization = membersWorkspaceFor($owner); + $member = User::factory()->create(['name' => 'Plain Member']); + $organization->users()->attach($member, ['role' => OrganizationRole::Member->value]); + $member->forceFill(['current_organization_id' => $organization->id])->save(); + + $this->actingAs($member); + + Livewire::test('pages::workspace.members') + ->assertSee('Plain Member') + ->assertDontSeeHtml('data-test="invite-member-button"') + ->assertDontSeeHtml('data-test="remove-member-'.$owner->id.'"'); + + Livewire::test('pages::workspace.members') + ->set('inviteEmail', 'sneaky@example.com') + ->call('inviteMember') + ->assertStatus(403); + + $this->assertDatabaseCount('invitations', 0); +}); diff --git a/tests/Feature/WorkspaceTest.php b/tests/Feature/WorkspaceTest.php new file mode 100644 index 0000000..5824432 --- /dev/null +++ b/tests/Feature/WorkspaceTest.php @@ -0,0 +1,141 @@ +firstWhere('name', 'organization_id'); + $todoColumn = collect(Schema::getColumns('todos'))->firstWhere('name', 'organization_id'); + + expect($folderColumn['nullable'])->toBeFalse(); + expect($todoColumn['nullable'])->toBeFalse(); +}); + +test('organization workspaces default to the organization type', function () { + $org = Organization::factory()->create(); + + expect($org->type)->toBe(WorkspaceType::Organization); +}); + +test('the personal factory state marks a personal workspace', function () { + $org = Organization::factory()->personal()->create(); + + expect($org->type)->toBe(WorkspaceType::Personal); + expect($org->personal_workspace)->toBeTrue(); +}); + +test('the family factory state marks a family workspace', function () { + $org = Organization::factory()->family()->create(); + + expect($org->type)->toBe(WorkspaceType::Family); + expect($org->isFamily())->toBeTrue(); +}); + +test('seat limits cap personal and family workspaces but not organizations', function () { + expect(Organization::factory()->personal()->create()->seatLimit())->toBe(1); + expect(Organization::factory()->family()->create()->seatLimit())->toBe(6); + expect(Organization::factory()->create()->seatLimit())->toBeNull(); +}); + +test('a workspace at its seat limit cannot accept another member', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + + for ($i = 0; $i < 5; $i++) { + $org->users()->attach(User::factory()->create(), ['role' => OrganizationRole::Member->value]); + } + + expect($org->canAddMember())->toBeFalse(); +}); + +test('organization workspaces never hit a seat limit', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->create(); + $org->users()->attach($owner, ['role' => OrganizationRole::Owner->value]); + + expect($org->seatLimit())->toBeNull(); + expect($org->canAddMember())->toBeTrue(); +}); + +test('workspace members and admins are counted by memberCount', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + $org->users()->attach(User::factory()->create(), ['role' => OrganizationRole::Member->value]); + + expect($org->memberCount())->toBe(2); +}); + +test('only workspace admins manage members and billing', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + $admin = User::factory()->create(); + $org->users()->attach($admin, ['role' => OrganizationRole::Admin->value]); + $member = User::factory()->create(); + $org->users()->attach($member, ['role' => OrganizationRole::Member->value]); + + $this->actingAs($member); + expect($member->can('manageMembers', $org))->toBeFalse(); + expect($member->can('manageBilling', $org))->toBeFalse(); + expect($member->can('update', $org))->toBeFalse(); + + $this->actingAs($admin); + expect($admin->can('manageMembers', $org))->toBeTrue(); + expect($admin->can('manageBilling', $org))->toBeTrue(); +}); + +test('owners and admins are organization admins while members and strangers are not', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + $admin = User::factory()->create(); + $org->users()->attach($admin, ['role' => OrganizationRole::Admin->value]); + $member = User::factory()->create(); + $org->users()->attach($member, ['role' => OrganizationRole::Member->value]); + $stranger = User::factory()->create(); + + expect($owner->isOrganizationAdmin($org))->toBeTrue() + ->and($admin->isOrganizationAdmin($org))->toBeTrue() + ->and($member->isOrganizationAdmin($org))->toBeFalse() + ->and($stranger->isOrganizationAdmin($org))->toBeFalse(); +}); + +test('a site admin is not an organization admin of a workspace they do not belong to', function () { + $siteAdmin = User::factory()->asAdmin()->create(); + $org = Organization::factory()->family()->withMember(User::factory()->create())->create(); + + expect($siteAdmin->isSiteAdmin())->toBeTrue() + ->and($siteAdmin->isOrganizationAdmin($org))->toBeFalse(); +}); + +test('only the owner can delete a workspace', function () { + $owner = User::factory()->create(); + $org = Organization::factory()->family()->withMember($owner)->create(); + $admin = User::factory()->create(); + $org->users()->attach($admin, ['role' => OrganizationRole::Admin->value]); + + $this->actingAs($admin); + expect($admin->can('delete', $org))->toBeFalse(); + + $this->actingAs($owner); + expect($owner->can('delete', $org))->toBeTrue(); +}); + +test('strangers cannot view a workspace', function () { + $org = Organization::factory()->create(); + $stranger = User::factory()->create(); + + $this->actingAs($stranger); + expect($stranger->can('view', $org))->toBeFalse(); +}); + +test('users get a personal organization when created', function () { + $user = User::factory()->create(); + + expect($user->current_organization_id)->not->toBeNull(); + $org = $user->currentOrganization()->first(); + expect($org->type)->toBe(WorkspaceType::Personal); + expect($org->isPersonal())->toBeTrue(); + expect($user->organizations()->wherePivot('role', OrganizationRole::Owner->value)->count())->toBe(1); +});