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

This commit is contained in:
2026-10-15 20:59:32 -07:00
parent 2ca3860557
commit 177f122c10
57 changed files with 6378 additions and 247 deletions
+510
View File
@@ -0,0 +1,510 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Cookie\CookieValuePrefix;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Seeds a dataset shaped like real usage, plus a manifest of ready-made
* authenticated sessions for the k6 load tests.
*
* The sessions are written through the framework's own session store rather
* than by posting to /login, because Fortify's login form runs bcrypt at
* BCRYPT_ROUNDS=12 and that would dominate the latency figures the tests are
* trying to measure.
*/
#[Signature(
signature: 'app:seed-load-test
{--users=1000 : Number of entitled users to create}
{--folders=50 : Folders per user, nested up to three levels deep}
{--todos=500 : Todos per user, spread across their folders}
{--admins=2 : Admin users to create}
{--chunk=50 : Users to create and populate per chunk}
{--sessions= : Where to write the k6 session manifest (defaults to load-tests/sessions.json)}
{--fresh : Delete previously seeded load-test users first}
{--force : Allow running when APP_ENV is production}',
)]
#[Description('Seed load-test users, folders, todos and authenticated sessions for k6')]
class SeedLoadTestData extends Command
{
/**
* Every seeded account uses this domain so --fresh can find them again
* without a database migration to track them.
*/
private const EMAIL_DOMAIN = 'loadtest.invalid';
/**
* How the todos of a user are distributed across the statuses the
* application branches on. The dashboard counts open, completed, overdue
* and due-today separately, so each of those buckets needs to be non-empty
* for the counts to mean anything.
*
* @var array<string, int>
*/
private const STATUS_MIX = [
'open' => 40,
'in-progress' => 15,
'on-hold' => 8,
'blocked' => 8,
'completed' => 20,
'cancelled' => 5,
'deferred' => 4,
];
/**
* Folder colours, matching the palette the folder UI offers.
*
* @var list<string>
*/
private const COLORS = ['red', 'orange', 'amber', 'green', 'emerald', 'blue', 'indigo', 'purple', 'pink'];
/**
* Execute the console command.
*/
public function handle(): int
{
if (app()->environment('production') && ! $this->option('force')) {
$this->error('Refusing to seed load-test data in production without --force.');
return self::FAILURE;
}
$users = (int) $this->option('users');
$admins = (int) $this->option('admins');
$folders = (int) $this->option('folders');
$todos = (int) $this->option('todos');
$chunk = max(1, (int) $this->option('chunk'));
if ($folders < 1) {
$this->error('--folders must be at least 1, because every todo belongs to a folder.');
return self::FAILURE;
}
if ($this->option('fresh')) {
$this->deleteSeededUsers();
}
$this->line(sprintf(
'Seeding %d user(s) and %d admin(s), %d folder(s) and %d todo(s) each...',
$users,
$admins,
$folders,
$todos,
));
$manifest = [];
$progress = $this->output->createProgressBar($users + $admins);
$progress->start();
for ($index = 0; $index < $users + $admins; $index += $chunk) {
$size = min($chunk, $users + $admins - $index);
foreach ($this->createChunk($index, $size, $folders, $todos) as $entry) {
$manifest[] = $entry;
}
$progress->advance($size);
}
$progress->finish();
$this->newLine(2);
$path = $this->writeManifest($manifest);
$this->line(sprintf('Wrote %d session(s) to %s', count($manifest), $path));
$this->newLine();
$this->line('Run the load tests against a served copy of this app with:');
$this->line(' k6 run load-tests/app.js');
return self::SUCCESS;
}
/**
* Create one batch of users and populate each with folders and todos.
*
* @return list<array{userId: int, email: string, isAdmin: bool, sessionId: string, cookie: string, todoIds: list<int>, folderIds: list<int>}>
*/
private function createChunk(int $offset, int $size, int $folders, int $todos): array
{
$entries = [];
$cookieName = (string) config('session.cookie');
for ($i = $offset; $i < $offset + $size; $i++) {
$isAdmin = $i >= (int) $this->option('users');
$user = $this->createUser($i, $isAdmin);
$organizationId = (int) $user->current_organization_id;
$folderIds = $this->seedFolders($user->id, $organizationId, $folders);
$this->seedTodos($user->id, $organizationId, $folderIds, $todos);
$sessionId = $this->createSession($user);
$entries[] = [
'userId' => $user->id,
'email' => $user->email,
'isAdmin' => $isAdmin,
'sessionId' => $sessionId,
'cookieName' => $cookieName,
'cookie' => $this->sessionCookie($sessionId),
'todoIds' => $this->sampleTodoIds($user->id, $folderIds),
'folderIds' => array_slice($folderIds, 0, 10),
];
}
return $entries;
}
/**
* Create one entitled user.
*
* UserFactory already attaches a personal organization and a local
* subscription row, which is all EnsureSubscribed reads, so no Stripe
* call is involved and none is possible.
*/
private function createUser(int $index, bool $isAdmin): User
{
$factory = User::factory();
if ($isAdmin) {
$factory = $factory->asAdmin();
}
return $factory->create([
'name' => $isAdmin ? 'Load Admin' : 'Load User '.$index,
'email' => sprintf('loadtest%05d@%s', $index, self::EMAIL_DOMAIN),
]);
}
/**
* Insert a folder tree for a user and return the ids of every folder.
*
* Parents are inserted in their own batch ahead of their children so the
* self-referencing foreign key is always satisfied by a row that already
* exists.
*
* @return list<int>
*/
private function seedFolders(int $userId, int $organizationId, int $count): array
{
$now = now();
$visibility = $this->visibilityFor($organizationId);
$insert = fn (string $name, ?int $parentId, int $position): array => [
'user_id' => $userId,
'organization_id' => $organizationId,
'name' => $name,
'visibility' => $visibility,
'parent_id' => $parentId,
'color' => self::COLORS[($position + $userId) % count(self::COLORS)],
'created_at' => $now,
'updated_at' => $now,
];
$rootCount = max(1, (int) round($count / 3));
$childCount = (int) round(($count - $rootCount) / 2);
$rows = [];
for ($i = 0; $i < $rootCount && $i < $count; $i++) {
$rows[] = $insert('Project '.($i + 1), null, $i);
}
DB::table('folders')->insert($rows);
$rootIds = $this->folderIds($userId);
$childIds = [];
if ($childCount > 0 && $rootIds !== []) {
$rows = [];
for ($i = 0; $i < $childCount; $i++) {
$rows[] = $insert('Milestone '.($i + 1), $rootIds[$i % count($rootIds)], $i);
}
DB::table('folders')->insert($rows);
$childIds = array_values(array_diff($this->folderIds($userId), $rootIds));
}
$remaining = $count - count($rootIds) - count($childIds);
if ($remaining > 0 && $childIds !== []) {
$rows = [];
for ($i = 0; $i < $remaining; $i++) {
$rows[] = $insert('Task '.($i + 1), $childIds[$i % count($childIds)], $i);
}
DB::table('folders')->insert($rows);
$childIds = array_values(array_diff($this->folderIds($userId), $rootIds));
}
return $childIds;
}
/**
* Read back a user's folder ids in insertion order.
*
* Ids are read rather than predicted because a cascade delete advances
* MySQL's auto-increment counter without lowering MAX(id), so the next
* insert is not guaranteed to continue from the current maximum.
*
* @return list<int>
*/
private function folderIds(int $userId): array
{
return DB::table('folders')
->where('user_id', $userId)
->orderBy('id')
->pluck('id')
->map(fn ($id): int => (int) $id)
->all();
}
/**
* Get the folder visibility a workspace defaults to, so bulk inserts match
* what the application would have written.
*/
private function visibilityFor(int $organizationId): string
{
$type = DB::table('organizations')->where('id', $organizationId)->value('type');
return strval($type) === 'personal' ? 'private' : 'workspace';
}
/**
* Insert a user's todos, spread across their folders.
*
* @param list<int> $folderIds
*/
private function seedTodos(int $userId, int $organizationId, array $folderIds, int $count): void
{
if ($folderIds === [] || $count < 1) {
return;
}
$statuses = $this->weightedStatuses();
$now = now();
$today = $now->copy()->startOfDay();
foreach (array_chunk(range(0, $count - 1), 500) as $batch) {
$rows = [];
$completedSeen = 0;
foreach ($batch as $index) {
$status = $statuses[$index % count($statuses)];
$isTerminal = $status === 'completed';
if ($isTerminal) {
$completedSeen++;
}
// Only active statuses can be overdue or due today, because
// both dashboard counts filter on active() as well.
$dueDate = $this->dueDateFor($status, $today, $index);
$rows[] = [
'user_id' => $userId,
'organization_id' => $organizationId,
'folder_id' => $folderIds[$index % count($folderIds)],
'description' => $this->descriptionFor($index),
'notes' => $index % 4 === 0 ? 'Context for item '.$index.'. '.str_repeat('Additional detail. ', 4) : null,
'status' => $status,
// Leaving roughly a third without a position exercises the
// "position IS NULL" branch of the priority sort.
'position' => $index % 3 === 0 ? $completedSeen + 1 : null,
'due_date' => $dueDate,
'completed_at' => $isTerminal ? $today->copy()->subDays($index % 30)->setTime(12, 0) : null,
'created_at' => $now->copy()->subDays($index % 60),
'updated_at' => $now,
];
}
DB::table('todos')->insert($rows);
}
}
/**
* Expand the status mix into one entry per todo.
*
* @return list<string>
*/
private function weightedStatuses(): array
{
$statuses = [];
foreach (self::STATUS_MIX as $status => $weight) {
for ($i = 0; $i < $weight; $i++) {
$statuses[] = $status;
}
}
return $statuses;
}
/**
* Choose a due date so the overdue, due-today and future buckets are all
* populated for the active statuses.
*/
private function dueDateFor(string $status, CarbonInterface $today, int $index): ?string
{
$active = ! in_array($status, ['completed', 'cancelled', 'deferred'], true);
if ($index % 5 === 0) {
return null;
}
if ($active && $index % 5 === 1) {
return $today->copy()->subDays(($index % 21) + 1)->toDateString();
}
if ($active && $index % 5 === 2) {
return $today->toDateString();
}
return $today->copy()->addDays(($index % 90) + 1)->toDateString();
}
/**
* Build a todo description, varying length so the search column holds a
* realistic mix rather than one uniform string.
*/
private function descriptionFor(int $index): string
{
$short = [
'Review pull request',
'Reply to inbox',
'Book dentist',
'Water the plants',
'Refill prescriptions',
'Pay the invoice',
'Update the changelog',
'Renew the domain',
];
$base = $short[$index % count($short)];
if ($index % 3 === 0) {
return $base.' #'.($index + 1);
}
if ($index % 3 === 1) {
return $base.' for the '.['launch', 'quarterly review', 'migration', 'handover'][$index % 4].' workstream';
}
return $base.' and confirm the follow-up items with the team before the '.['standup', 'review', 'retro'][$index % 3].' on Friday';
}
/**
* Pick todo ids for the write scenarios to act on.
*
* The load tests need real ids because the write calls go through
* findOrFail against the requesting user, so a fabricated id would measure
* a 404 instead of a write. Rotating over several ids keeps the write
* spread across rows the way real clicking does, rather than hammering
* one row that stays hot in the buffer pool.
*
* @param list<int> $folderIds
* @return list<int>
*/
private function sampleTodoIds(int $userId, array $folderIds): array
{
return DB::table('todos')
->where('user_id', $userId)
->whereIn('folder_id', $folderIds === [] ? [0] : $folderIds)
->whereNull('completed_at')
->orderBy('id')
->limit(5)
->pluck('id')
->map(fn ($id): int => (int) $id)
->all();
}
/**
* Create a logged-in session row for a user and return its id.
*
* Writing through the session store keeps the stored payload in exactly
* the shape the framework's own session handler reads back, which is what
* the load tests need in order to authenticate by cookie alone.
*
* The id is read back only after logging in, because SessionGuard::login()
* calls migrate() internally and replaces it with a fresh one.
*/
private function createSession(User $user): string
{
$store = app('session.store');
$store->setId(Str::random(40));
$store->start();
Auth::guard('web')->login($user);
$store->save();
return $store->getId();
}
/**
* Build the cookie header value a browser would present for a session.
*
* EncryptCookies wraps every cookie value in an HMAC prefix and then
* encrypts it, so a bare session id is not accepted on the wire. The
* seeder therefore has to produce the same envelope, using the same
* serializer flag the middleware reports for itself.
*/
private function sessionCookie(string $sessionId): string
{
$name = (string) config('session.cookie');
$prefix = CookieValuePrefix::create($name, app('encrypter')->getKey());
return app('encrypter')->encrypt(
$prefix.$sessionId,
EncryptCookies::serialized($name),
);
}
/**
* Remove previously seeded accounts, relying on cascades for their data.
*/
private function deleteSeededUsers(): void
{
$count = DB::table('users')->where('email', 'like', '%@'.self::EMAIL_DOMAIN)->count();
if ($count === 0) {
$this->line('No previously seeded load-test users to remove.');
return;
}
$userIds = DB::table('users')->where('email', 'like', '%@'.self::EMAIL_DOMAIN)->pluck('id');
DB::table('sessions')->whereIn('user_id', $userIds)->delete();
User::query()->whereIn('id', $userIds)->delete();
$this->line("Removed {$count} previously seeded load-test user(s).");
}
/**
* Write the session manifest that the k6 script reads at init time.
*
* @param list<array{userId: int, email: string, isAdmin: bool, sessionId: string, cookie: string}> $manifest
*/
private function writeManifest(array $manifest): string
{
$path = (string) ($this->option('sessions') ?: base_path('load-tests/sessions.json'));
$directory = dirname($path);
if (! is_dir($directory)) {
mkdir($directory, 0755, recursive: true);
}
file_put_contents($path, json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
return $path;
}
}
+75 -1
View File
@@ -78,6 +78,7 @@ class TransferSqliteData extends Command
$this->transferTable($table, $key); $this->transferTable($table, $key);
} }
$this->backfillWorkspaces();
$this->resetAutoIncrements(); $this->resetAutoIncrements();
} catch (Throwable $e) { } catch (Throwable $e) {
$this->error('Transfer failed: '.$e->getMessage()); $this->error('Transfer failed: '.$e->getMessage());
@@ -117,12 +118,85 @@ class TransferSqliteData extends Command
->table($table) ->table($table)
->orderBy($key) ->orderBy($key)
->chunk(500, function ($rows) use ($table): void { ->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}."); $this->line(" transferred {$count} row(s) into {$table}.");
} }
/**
* Folders and todos cannot be inserted without a workspace, but the source
* database predates workspaces. Folders inherit the current organization of
* their owner, and todos inherit the organization of their folder. Rows
* that already carry the value are left untouched.
*
* @param iterable<object> $rows
* @return list<array<string, mixed>>
*/
private function prepareRows(string $table, iterable $rows): array
{
$records = collect($rows)->map(fn ($row): array => (array) $row)->all();
if ($table === 'folders') {
$userIds = collect($records)->pluck('user_id')->all();
$organizationByUser = DB::table('users')
->whereIn('id', $userIds)
->pluck('current_organization_id', 'id')
->all();
foreach ($records as &$record) {
$record['organization_id'] ??= $organizationByUser[$record['user_id']] ?? null;
}
unset($record);
return $records;
}
if ($table === 'todos') {
$folderIds = collect($records)->pluck('folder_id')->all();
$organizationByFolder = DB::table('folders')
->whereIn('id', $folderIds)
->pluck('organization_id', 'id')
->all();
foreach ($records as &$record) {
$record['organization_id'] ??= $organizationByFolder[$record['folder_id']] ?? null;
}
unset($record);
return $records;
}
return $records;
}
/**
* The source database predates workspaces, so folders and todos arrive
* without an organization id and folders without a visibility. Fold them
* into the workspace their owner had active, exactly as the workspace
* migration does for existing rows.
*/
private function backfillWorkspaces(): void
{
DB::table('folders')
->join('users', 'users.id', '=', 'folders.user_id')
->whereNull('folders.organization_id')
->update(['folders.organization_id' => DB::raw('users.current_organization_id')]);
DB::table('todos')
->join('folders', 'folders.id', '=', 'todos.folder_id')
->whereNull('todos.organization_id')
->update(['todos.organization_id' => DB::raw('folders.organization_id')]);
DB::table('folders')
->join('organizations', 'organizations.id', '=', 'folders.organization_id')
->update([
'folders.visibility' => DB::raw(
"CASE WHEN organizations.personal_workspace = 1 THEN 'private' ELSE 'workspace' END"
),
]);
}
/** /**
* Bump each auto-increment counter past the highest transferred id so * Bump each auto-increment counter past the highest transferred id so
* newly created records never collide with the preserved ids. * newly created records never collide with the preserved ids.
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App;
enum FolderRole: string
{
case Admin = 'admin';
case Editor = 'editor';
case Marker = 'marker';
case Viewer = 'viewer';
/**
* Get the human-friendly label for the role.
*/
public function label(): string
{
return match ($this) {
self::Admin => 'Admin',
self::Editor => 'Editor',
self::Marker => 'Marker',
self::Viewer => 'Viewer',
};
}
/**
* Determine whether the role may change a todo's completion state.
*/
public function canMarkComplete(): bool
{
return $this !== self::Viewer;
}
/**
* Determine whether the role may create, edit or delete todos. Editors
* manage todo content only; folder structure and collaborators are an
* admin concern.
*/
public function canEditTodos(): bool
{
return in_array($this, [self::Admin, self::Editor], true);
}
/**
* Determine whether the role may manage the folder itself: its structure,
* visibility and collaborators, and new folders beneath it.
*/
public function canManage(): bool
{
return $this === self::Admin;
}
/**
* Get the folder roles a collaborator may be assigned, most privileged
* first.
*
* @return list<self>
*/
public static function assignable(): array
{
return [self::Admin, self::Editor, self::Marker, self::Viewer];
}
/**
* Get this role's rank, so the strongest of two roles can be picked.
*/
public function rank(): int
{
return match ($this) {
self::Admin => 3,
self::Editor => 2,
self::Marker => 1,
self::Viewer => 0,
};
}
/**
* Get the strongest of the two roles, ignoring missing ones.
*/
public static function higherOf(?self $left, ?self $right): ?self
{
if ($left === null) {
return $right;
}
if ($right === null) {
return $left;
}
return $left->rank() >= $right->rank() ? $left : $right;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App;
enum FolderVisibility: string
{
case Private = 'private';
case Workspace = 'workspace';
/**
* Get the human-friendly label for the visibility.
*/
public function label(): string
{
return match ($this) {
self::Private => 'Private',
self::Workspace => 'Shared with workspace',
};
}
/**
* Determine whether a folder at this visibility is opened up to every
* member of its workspace.
*/
public function isSharedWithWorkspace(): bool
{
return $this === self::Workspace;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;
class EnsureAdmin
{
/**
* Restrict access to the site-wide administrator area. Organization
* owners/admins are not site administrators and are rejected here.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
Gate::authorize('accessAdmin');
return $next($request);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Mail;
use App\Models\Invitation;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class InvitationMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*/
public function __construct(public Invitation $invitation) {}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
$inviter = $this->invitation->inviterName();
$name = $this->invitation->inviteableName();
return new Envelope(
subject: $this->invitation->isForFolder()
? __(':inviter shared the folder ":name" with you', ['inviter' => $inviter, 'name' => $name])
: __(':inviter invited you to the ":name" workspace', ['inviter' => $inviter, 'name' => $name]),
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
markdown: 'mail.invitation',
with: [
'inviterName' => $this->invitation->inviterName(),
'inviteableName' => $this->invitation->inviteableName(),
'roleLabel' => $this->invitation->roleLabel(),
'isFolder' => $this->invitation->isForFolder(),
'url' => route('invitations.accept', $this->invitation->token),
],
);
}
/**
* Get the attachments for the message.
*
* @return array<int, Attachment>
*/
public function attachments(): array
{
return [];
}
}
+257 -7
View File
@@ -2,27 +2,38 @@
namespace App\Models; namespace App\Models;
use App\FolderRole;
use App\FolderVisibility;
use App\OrganizationRole;
use App\WorkspaceType;
use Database\Factories\FolderFactory; use Database\Factories\FolderFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/** /**
* @property int $id * @property int $id
* @property int $user_id * @property int $user_id
* @property int|null $organization_id
* @property string $name * @property string $name
* @property FolderVisibility $visibility
* @property string|null $color * @property string|null $color
* @property int|null $parent_id * @property int|null $parent_id
* @property Folder|null $parent * @property Folder|null $parent
* @property Organization|null $organization
* @property Collection<int, User> $shares
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property Carbon|null $updated_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 class Folder extends Model
{ {
/** @use HasFactory<FolderFactory> */ /** @use HasFactory<FolderFactory> */
@@ -33,12 +44,60 @@ class Folder extends Model
'sky', 'blue', 'indigo', 'violet', 'fuchsia', 'pink', 'sky', 'blue', 'indigo', 'violet', 'fuchsia', 'pink',
]; ];
/**
* Folders always belong to a workspace and carry an explicit visibility.
* Much of the app inserts rows in bulk without Eloquent, so rather than
* enforcing these in the schema we fill them in here whenever they are
* missing.
*/
protected static function booted(): void
{
static::creating(function (Folder $folder): void {
// Sub-folders inherit the workspace of the parent, so creating a
// child inside a folder shared from another workspace never leaks
// it into the creator's current workspace.
if ($folder->organization_id === null && $folder->parent_id !== null) {
$folder->organization_id = Folder::query()
->whereKey($folder->parent_id)
->value('organization_id');
}
$folder->organization_id ??= User::query()
->whereKey($folder->user_id)
->value('current_organization_id');
if ($folder->organization_id !== null) {
$folder->organization_id = (int) $folder->organization_id;
}
$folder->visibility ??= Folder::defaultVisibilityFor((int) $folder->organization_id);
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'visibility' => FolderVisibility::class,
];
}
/** @return BelongsTo<User, $this> */ /** @return BelongsTo<User, $this> */
public function user(): BelongsTo public function user(): BelongsTo
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
/** @return BelongsTo<Organization, $this> */
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class);
}
/** @return BelongsTo<Folder, $this> */ /** @return BelongsTo<Folder, $this> */
public function parent(): BelongsTo public function parent(): BelongsTo
{ {
@@ -57,6 +116,20 @@ class Folder extends Model
return $this->hasMany(Todo::class); return $this->hasMany(Todo::class);
} }
/** @return BelongsToMany<User, $this> */
public function shares(): BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('role', 'invited_by')
->withTimestamps();
}
/** @return MorphMany<Invitation, $this> */
public function invitations(): MorphMany
{
return $this->morphMany(Invitation::class, 'inviteable');
}
/** /**
* Scope the query to folders owned by the given user. * Scope the query to folders owned by the given user.
* *
@@ -79,6 +152,144 @@ class Folder extends Model
return $query->whereNull('parent_id'); return $query->whereNull('parent_id');
} }
/**
* Scope the query to folders the given user can access. Pass a workspace
* id to narrow the workspace-wide folders to the active workspace while
* still surfacing folders explicitly shared with the user from anywhere.
*
* @param Builder<Folder> $query
* @return Builder<Folder>
*/
public function scopeVisibleTo(Builder $query, User|int $user, ?int $workspaceId = null): Builder
{
$userId = $user instanceof User ? $user->id : $user;
return $query->where(function (Builder $query) use ($userId, $workspaceId): void {
$query->where(function (Builder $owned) use ($userId, $workspaceId): void {
$owned->where('folders.user_id', $userId);
if ($workspaceId !== null) {
$owned->where('folders.organization_id', $workspaceId);
}
})
->orWhereHas('shares', function (Builder $shares) use ($userId): void {
$shares->where('folder_user.user_id', $userId);
})
->orWhere(function (Builder $member) use ($userId, $workspaceId): void {
$member->where('folders.visibility', FolderVisibility::Workspace->value);
if ($workspaceId !== null) {
$member->where('folders.organization_id', $workspaceId);
return;
}
$memberships = DB::table('organization_user')
->where('organization_user.user_id', $userId)
->select('organization_user.organization_id');
$member->whereIn('folders.organization_id', $memberships);
});
});
}
/**
* Get the visibility new folders should adopt in the given workspace.
* Personal workspaces keep folders private; shared workspaces default new
* folders to workspace-wide access. Falls back to private when the
* workspace cannot be found.
*/
public static function defaultVisibilityFor(int $organizationId): FolderVisibility
{
$type = Organization::query()->whereKey($organizationId)->value('type');
$workspaceType = $type instanceof WorkspaceType
? $type
: WorkspaceType::tryFrom(is_string($type) ? $type : '');
return $workspaceType?->defaultFolderVisibility() ?? FolderVisibility::Private;
}
/**
* Get the role explicitly granted to the user on this folder, or null
* when the folder has not been shared with them.
*/
public function sharedRoleFor(User $user): ?FolderRole
{
$share = $this->relationLoaded('shares')
? $this->shares->firstWhere('id', $user->id)
: $this->shares()->whereKey($user->id)->first();
if ($share === null) {
return null;
}
return FolderRole::tryFrom((string) $share->pivot->role);
}
/**
* Get the role the user holds through a workspace membership on this
* folder, or null when they are not a member or the folder is private.
*
* @internal Only meaningful for folders shared with the workspace.
*/
public function workspaceMembershipRoleFor(User $user): ?FolderRole
{
if ($this->organization_id === null) {
return null;
}
$role = OrganizationRole::tryFrom((string) DB::table('organization_user')
->where('organization_id', $this->organization_id)
->where('user_id', $user->id)
->value('role'));
return $role?->defaultFolderRole();
}
/**
* Get the strongest role the user holds anywhere on this folder's
* ancestry: their own grant if the folder is theirs, explicit shares
* (which cascade through the whole subtree), and workspace-wide access
* which flows down through folders that are themselves shared with the
* workspace.
*
* Personal workspaces never share folders, and a private folder drops out
* of workspace-wide access above it. Returns null when the user has no
* access at all.
*/
public function effectiveRoleFor(User $user): ?FolderRole
{
if ($this->user_id === $user->id) {
return FolderRole::Admin;
}
$role = $this->sharedRoleFor($user);
// Workspace-wide access only reaches this folder and its descendants
// while every folder between the grant and this folder is shared with
// the workspace. A private folder therefore stops inherited workspace
// access, though explicit shares above it still cascade.
$inheritsWorkspace = $this->visibility === FolderVisibility::Workspace;
if ($inheritsWorkspace) {
$role = FolderRole::higherOf($role, $this->workspaceMembershipRoleFor($user));
}
$ancestor = $this->parent;
while ($ancestor !== null) {
$role = FolderRole::higherOf($role, $ancestor->sharedRoleFor($user));
if ($inheritsWorkspace && $ancestor->visibility === FolderVisibility::Workspace) {
$role = FolderRole::higherOf($role, $ancestor->workspaceMembershipRoleFor($user));
}
$ancestor = $ancestor->parent;
}
return $role;
}
/** /**
* Build a flattened, depth-aware tree of the user's folders * Build a flattened, depth-aware tree of the user's folders
* ordered top-down, with the full path (e.g. "Work / Acme Corp"). * ordered top-down, with the full path (e.g. "Work / Acme Corp").
@@ -89,12 +300,47 @@ class Folder extends Model
{ {
$folders = Folder::query() $folders = Folder::query()
->forUser($user) ->forUser($user)
->with('organization')
->orderBy('name') ->orderBy('name')
->get() ->get();
->keyBy('id');
return static::flattenTree($folders);
}
/**
* Build the flattened tree of every folder the user can see in the given
* workspace: their own folders, folders shared with the workspace, and
* folders explicitly shared with them from any workspace.
*
* @return Collection<int, array{folder: Folder, depth: int, path: string}>
*/
public static function treeForVisibleTo(User|int $user, int $workspaceId): Collection
{
$folders = Folder::query()
->visibleTo($user, $workspaceId)
->with('organization')
->withCount('shares')
->orderBy('name')
->get();
return static::flattenTree($folders);
}
/**
* Flatten a flat collection of folders into a depth-aware tree. A folder
* whose parent is missing from the collection (for example a folder shared
* from outside the active workspace) is treated as a root so it is never
* dropped from the tree.
*
* @param Collection<int, Folder> $folders
* @return Collection<int, array{folder: Folder, depth: int, path: string}>
*/
private static function flattenTree(Collection $folders): Collection
{
$indexed = $folders->keyBy('id');
$tree = collect(); $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; $path = $prefix === '' ? $folder->name : $prefix.' / '.$folder->name;
$tree->push([ $tree->push([
@@ -103,13 +349,17 @@ class Folder extends Model
'path' => $path, '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); $visit($child, $depth + 1, $path);
} }
}; };
foreach ($folders->whereNull('parent_id')->values() as $topLevel) { $roots = $indexed->filter(
$visit($topLevel, 0, ''); fn (Folder $folder): bool => $folder->parent_id === null || ! $indexed->has($folder->parent_id)
);
foreach ($roots->values() as $root) {
$visit($root, 0, '');
} }
return $tree; return $tree;
+242
View File
@@ -0,0 +1,242 @@
<?php
namespace App\Models;
use App\FolderRole;
use App\OrganizationRole;
use Database\Factories\InvitationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* An invitation grants someone access to a folder or a workspace. The
* inviteable is polymorphic so folders and workspaces share the same flow; the
* token is the bearer credential the invitee exchanges for access, which is
* why it is mailed rather than shown.
*
* @property int $id
* @property int $inviter_id
* @property string $email
* @property string $role
* @property string $inviteable_type
* @property int $inviteable_id
* @property string $token
* @property Carbon|null $expires_at
* @property Carbon|null $accepted_at
* @property int|null $accepted_by_id
* @property Organization|Folder $inviteable
* @property User $inviter
* @property User|null $acceptedBy
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable([
'inviter_id',
'email',
'role',
'inviteable_type',
'inviteable_id',
'token',
'expires_at',
'accepted_at',
'accepted_by_id',
])]
class Invitation extends Model
{
/** @use HasFactory<InvitationFactory> */
use HasFactory;
/**
* How long an invitation stays redeemable after it is sent.
*/
public const EXPIRY_DAYS = 14;
/**
* Every invitation is addressed by a fresh token and gets a sensible
* expiry, so callers only ever supply the inviteable and the role.
*/
protected static function booted(): void
{
static::creating(function (Invitation $invitation): void {
$invitation->token ??= Str::random(64);
$invitation->expires_at ??= Carbon::now()->addDays(self::EXPIRY_DAYS);
});
}
/** @return MorphTo<Model, $this> */
public function inviteable(): MorphTo
{
return $this->morphTo();
}
/** @return BelongsTo<User, $this> */
public function inviter(): BelongsTo
{
return $this->belongsTo(User::class, 'inviter_id');
}
/** @return BelongsTo<User, $this> */
public function acceptedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'accepted_by_id');
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'expires_at' => 'datetime',
'accepted_at' => 'datetime',
];
}
/**
* Determine whether the invitation has been used.
*/
public function isAccepted(): bool
{
return $this->accepted_at !== null;
}
/**
* Determine whether the invitation has lapsed.
*/
public function isExpired(): bool
{
return $this->expires_at !== null && $this->expires_at->isPast();
}
/**
* Determine whether the invitation can still be redeemed.
*/
public function isValid(): bool
{
return ! $this->isAccepted() && ! $this->isExpired();
}
/**
* Scope the query to invitations that can still be redeemed.
*
* @param Builder<Invitation> $query
* @return Builder<Invitation>
*/
public function scopePending(Builder $query): Builder
{
return $query->whereNull('accepted_at')
->where(function (Builder $query): void {
$query->whereNull('expires_at')
->orWhere('expires_at', '>', now());
});
}
/**
* Determine whether this invitation grants access to a folder.
*/
public function isForFolder(): bool
{
return $this->inviteable_type === Folder::class;
}
/**
* Determine whether this invitation grants access to a workspace.
*/
public function isForWorkspace(): bool
{
return $this->inviteable_type === Organization::class;
}
/**
* Get the folder role this invitation grants, or null when it does not
* invite into a folder.
*/
public function folderRole(): ?FolderRole
{
return $this->isForFolder() ? FolderRole::tryFrom($this->role) : null;
}
/**
* Get the workspace role this invitation grants, or null when it does not
* invite into a workspace.
*/
public function organizationRole(): ?OrganizationRole
{
return $this->isForWorkspace() ? OrganizationRole::tryFrom($this->role) : null;
}
/**
* Get a human-readable label for the role this invitation grants.
*/
public function roleLabel(): string
{
return $this->folderRole()?->label()
?? $this->organizationRole()?->label()
?? $this->role;
}
/**
* Get the name of the person who sent the invitation.
*/
public function inviterName(): string
{
return $this->inviter->name;
}
/**
* Get the name of the folder or workspace the invitation is for.
*/
public function inviteableName(): string
{
if (! $this->isForFolder() && ! $this->isForWorkspace()) {
return '';
}
return (string) $this->inviteable->name;
}
/**
* Redeem the invitation for the given user, granting membership on the
* invited folder or workspace and recording who accepted it. Already
* accepted or expired invitations are left untouched.
*/
public function accept(User $user): void
{
if (! $this->isValid()) {
return;
}
$inviteable = $this->inviteable;
if ($inviteable instanceof Folder) {
$inviteable->shares()->syncWithoutDetaching([
$user->id => [
'role' => ($this->folderRole() ?? FolderRole::Viewer)->value,
'invited_by' => $this->inviter_id,
],
]);
} elseif ($inviteable instanceof Organization) {
$inviteable->users()->syncWithoutDetaching([
$user->id => [
'role' => ($this->organizationRole() ?? OrganizationRole::Member)->value,
],
]);
// Drop the invitee straight into the workspace they just joined.
$user->forceFill(['current_organization_id' => $inviteable->id])->save();
}
$this->forceFill([
'accepted_at' => now(),
'accepted_by_id' => $user->id,
])->save();
}
}
+71 -5
View File
@@ -3,12 +3,15 @@
namespace App\Models; namespace App\Models;
use App\OrganizationRole; use App\OrganizationRole;
use App\WorkspaceType;
use Database\Factories\OrganizationFactory; use Database\Factories\OrganizationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; 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\Carbon;
use Illuminate\Support\Number; use Illuminate\Support\Number;
use Laravel\Cashier\Billable; use Laravel\Cashier\Billable;
@@ -17,13 +20,14 @@ use Laravel\Cashier\Subscription;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
/** /**
* An organization owns the subscription and is the Stripe customer. Every user * An organization is a workspace: it owns the subscription, is the Stripe
* is given a personal organization when their account is created; group and * customer, and its members share access to the folders inside it. Every user
* company organizations are created later, which is why the model is not named * is given a personal organization when their account is created; family and
* after a person. * organization workspaces are created later.
* *
* @property int $id * @property int $id
* @property string $name * @property string $name
* @property WorkspaceType $type
* @property bool $personal_workspace * @property bool $personal_workspace
* @property bool $lifetime_access * @property bool $lifetime_access
* @property string|null $stripe_id * @property string|null $stripe_id
@@ -33,7 +37,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property Carbon|null $updated_at * @property Carbon|null $updated_at
*/ */
#[Fillable(['name', 'personal_workspace', 'lifetime_access'])] #[Fillable(['name', 'type', 'personal_workspace', 'lifetime_access'])]
#[Hidden(['stripe_id'])] #[Hidden(['stripe_id'])]
class Organization extends Model class Organization extends Model
{ {
@@ -48,6 +52,7 @@ class Organization extends Model
protected function casts(): array protected function casts(): array
{ {
return [ return [
'type' => WorkspaceType::class,
'personal_workspace' => 'boolean', 'personal_workspace' => 'boolean',
'lifetime_access' => 'boolean', 'lifetime_access' => 'boolean',
'trial_ends_at' => 'datetime', 'trial_ends_at' => 'datetime',
@@ -64,6 +69,67 @@ class Organization extends Model
->withTimestamps(); ->withTimestamps();
} }
/**
* @return HasMany<Folder, $this>
*/
public function folders(): HasMany
{
return $this->hasMany(Folder::class);
}
/**
* @return MorphMany<Invitation, $this>
*/
public function invitations(): MorphMany
{
return $this->morphMany(Invitation::class, 'inviteable');
}
public function isPersonal(): bool
{
return $this->type === WorkspaceType::Personal;
}
public function isFamily(): bool
{
return $this->type === WorkspaceType::Family;
}
public function isOrganization(): bool
{
return $this->type === WorkspaceType::Organization;
}
/**
* Get how many users this workspace may hold, or null for an unlimited
* organization.
*/
public function seatLimit(): ?int
{
return config("workspaces.seat_limits.{$this->type->value}");
}
/**
* Get how many users this workspace currently holds.
*/
public function memberCount(): int
{
return $this->users()->count();
}
/**
* Determine whether another member can join this workspace.
*
* Organization workspaces are provisioned separately and are therefore
* never constrained by a seat limit.
*/
public function canAddMember(): bool
{
$limit = $this->seatLimit();
return $limit === null || $this->memberCount() < $limit;
}
/** /**
* Get the subscription type that Cashier stores this organization's * Get the subscription type that Cashier stores this organization's
* subscriptions under. * subscriptions under.
+40 -4
View File
@@ -14,6 +14,7 @@ use Illuminate\Support\Carbon;
/** /**
* @property int $id * @property int $id
* @property int $user_id * @property int $user_id
* @property int|null $organization_id
* @property int $folder_id * @property int $folder_id
* @property string $description * @property string $description
* @property string|null $notes * @property string|null $notes
@@ -25,18 +26,38 @@ use Illuminate\Support\Carbon;
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property Carbon|null $updated_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 class Todo extends Model
{ {
/** @use HasFactory<TodoFactory> */ /** @use HasFactory<TodoFactory> */
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<User, $this> */ /** @return BelongsTo<User, $this> */
public function user(): BelongsTo public function user(): BelongsTo
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
/** @return BelongsTo<Organization, $this> */
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class);
}
/** @return BelongsTo<Folder, $this> */ /** @return BelongsTo<Folder, $this> */
public function folder(): BelongsTo public function folder(): BelongsTo
{ {
@@ -68,6 +89,19 @@ class Todo extends Model
return $query->where('user_id', $user instanceof User ? $user->id : $user); return $query->where('user_id', $user instanceof User ? $user->id : $user);
} }
/**
* Scope the query to todos the given user can access, which follows the
* folder the todo sits in. Pass a workspace id to narrow the query to the
* active workspace, matching {@see Folder::scopeVisibleTo()}.
*
* @param Builder<Todo> $query
* @return Builder<Todo>
*/
public function scopeVisibleTo(Builder $query, User|int $user, ?int $workspaceId = null): Builder
{
return $query->whereIn('folder_id', Folder::query()->visibleTo($user, $workspaceId)->select('folders.id'));
}
/** /**
* Scope the query to todos that have not been completed. * 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 * 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; return $min === null ? 1 : $min - 1;
} }
+31 -2
View File
@@ -4,6 +4,7 @@ namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail; // use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\OrganizationRole; use App\OrganizationRole;
use App\WorkspaceType;
use Database\Factories\UserFactory; use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -71,6 +72,16 @@ class User extends Authenticatable implements PasskeyUser
->withTimestamps(); ->withTimestamps();
} }
/**
* @return BelongsToMany<Folder, $this>
*/
public function sharedFolders(): BelongsToMany
{
return $this->belongsToMany(Folder::class)
->withPivot('role', 'invited_by')
->withTimestamps();
}
/** /**
* Create a personal organization owned by this user and make it current. * 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([ $organization = Organization::create([
'name' => $this->name."'s Workspace", 'name' => $this->name."'s Workspace",
'type' => WorkspaceType::Personal,
'personal_workspace' => true, '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; 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. * Get the maximum length allowed for todo notes.
*/ */
+24
View File
@@ -5,6 +5,7 @@ namespace App;
enum OrganizationRole: string enum OrganizationRole: string
{ {
case Owner = 'owner'; case Owner = 'owner';
case Admin = 'admin';
case Member = 'member'; case Member = 'member';
/** /**
@@ -14,7 +15,30 @@ enum OrganizationRole: string
{ {
return match ($this) { return match ($this) {
self::Owner => 'Owner', self::Owner => 'Owner',
self::Admin => 'Admin',
self::Member => 'Member', self::Member => 'Member',
}; };
} }
/**
* Determine whether the role may manage the workspace: its members and its
* billing. Owners and admins may; members may not.
*/
public function canManageWorkspace(): bool
{
return in_array($this, [self::Owner, self::Admin], true);
}
/**
* Get the folder role a member of this workspace receives by default on a
* folder shared with the whole workspace. Admins and owners manage folders;
* plain members start as viewers until reassigned on a folder.
*/
public function defaultFolderRole(): FolderRole
{
return match ($this) {
self::Owner, self::Admin => FolderRole::Admin,
self::Member => FolderRole::Viewer,
};
}
} }
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
class FolderPolicy
{
/**
* Anyone with a role anywhere on the folder's ancestry may see it.
*/
public function view(User $user, Folder $folder): bool
{
return $folder->effectiveRoleFor($user) !== null;
}
/**
* Only workspace admins create folders at the top of a workspace.
*/
public function create(User $user, Organization $organization): bool
{
$role = $this->organizationRoleFor($user, $organization);
return $role !== null && $role->canManageWorkspace();
}
/**
* Folder admins create folders beneath an existing folder.
*/
public function createChild(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
public function update(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
public function delete(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
/**
* Only folder admins invite collaborators and change visibility.
*/
public function manageShares(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canManage();
}
private function organizationRoleFor(User $user, Organization $organization): ?OrganizationRole
{
return OrganizationRole::tryFrom((string) $organization->users()
->where('users.id', $user->id)
->withPivot('role')
->first()?->pivot->role);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
class InvitationPolicy
{
/**
* Inviting people into a folder or workspace is gated by the inviteable's
* own policies.
*/
public function create(User $user, Organization|Folder $inviteable): bool
{
if ($inviteable instanceof Folder) {
return $user->can('manageShares', $inviteable);
}
return $user->can('manageMembers', $inviteable);
}
/**
* The invitation may be revoked by whoever sent it or by an admin of the
* thing it invites into.
*/
public function delete(User $user, Invitation $invitation): bool
{
return $user->id === $invitation->inviter_id
|| $user->can('delete', $invitation->inviteable);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Policies;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
class OrganizationPolicy
{
public function view(User $user, Organization $organization): bool
{
return $this->roleFor($user, $organization) !== null;
}
public function update(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
public function manageMembers(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
public function manageBilling(User $user, Organization $organization): bool
{
return $this->canManage($user, $organization);
}
/**
* Only the owner may dissolve a workspace.
*/
public function delete(User $user, Organization $organization): bool
{
return $this->roleFor($user, $organization) === OrganizationRole::Owner;
}
private function roleFor(User $user, Organization $organization): ?OrganizationRole
{
return OrganizationRole::tryFrom((string) $organization->users()
->where('users.id', $user->id)
->withPivot('role')
->first()?->pivot->role);
}
private function canManage(User $user, Organization $organization): bool
{
return $user->isOrganizationAdmin($organization);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Policies;
use App\Models\Folder;
use App\Models\Todo;
use App\Models\User;
class TodoPolicy
{
public function view(User $user, Todo $todo): bool
{
return $todo->folder?->effectiveRoleFor($user) !== null;
}
/**
* Workspace folders are shared with editors so they can add todos to them.
*/
public function create(User $user, Folder $folder): bool
{
$role = $folder->effectiveRoleFor($user);
return $role !== null && $role->canEditTodos();
}
public function update(User $user, Todo $todo): bool
{
return $this->canEdit($user, $todo);
}
public function delete(User $user, Todo $todo): bool
{
return $this->canEdit($user, $todo);
}
/**
* Markers and above may flip a todo's completion state.
*/
public function markComplete(User $user, Todo $todo): bool
{
$role = $todo->folder?->effectiveRoleFor($user);
return $role !== null && $role->canMarkComplete();
}
private function canEdit(User $user, Todo $todo): bool
{
$role = $todo->folder?->effectiveRoleFor($user);
return $role !== null && $role->canEditTodos();
}
}
+13
View File
@@ -4,9 +4,11 @@ namespace App\Providers;
use App\Http\Responses\RegisterResponse; use App\Http\Responses\RegisterResponse;
use App\Models\Organization; use App\Models\Organization;
use App\Models\User;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier; use Laravel\Cashier\Cashier;
@@ -41,6 +43,17 @@ class AppServiceProvider extends ServiceProvider
{ {
$this->configureDefaults(); $this->configureDefaults();
$this->configureCashier(); $this->configureCashier();
$this->defineGates();
}
/**
* Define the site-wide administrator ability. This is deliberately separate
* from an organization's Owner/Admin roles, which only ever grant rights
* inside a single workspace.
*/
protected function defineGates(): void
{
Gate::define('accessAdmin', fn (User $user): bool => $user->isSiteAdmin());
} }
/** /**
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App;
enum WorkspaceType: string
{
case Personal = 'personal';
case Family = 'family';
case Organization = 'organization';
/**
* Get the human-friendly label for the workspace type.
*/
public function label(): string
{
return match ($this) {
self::Personal => 'Personal',
self::Family => 'Family',
self::Organization => 'Organization',
};
}
/**
* Get the visibility a new top-level folder receives by default in this
* kind of workspace. Personal workspaces are single-user, so their folders
* start private; family and organization folders are shared with every
* member until an admin narrows them.
*/
public function defaultFolderVisibility(): FolderVisibility
{
return match ($this) {
self::Personal => FolderVisibility::Private,
self::Family, self::Organization => FolderVisibility::Workspace,
};
}
/**
* Determine whether folders in this workspace are shared with members by
* default.
*/
public function sharesByDefault(): bool
{
return $this !== self::Personal;
}
}
+2
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Http\Middleware\EnsureAdmin;
use App\Http\Middleware\EnsureSubscribed; use App\Http\Middleware\EnsureSubscribed;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Exceptions;
@@ -14,6 +15,7 @@ return Application::configure(basePath: dirname(__DIR__))
) )
->withMiddleware(function (Middleware $middleware): void { ->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([ $middleware->alias([
'admin' => EnsureAdmin::class,
'subscribed' => EnsureSubscribed::class, 'subscribed' => EnsureSubscribed::class,
]); ]);
+20
View File
@@ -0,0 +1,20 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Workspace Seat Limits
|--------------------------------------------------------------------------
|
| The maximum number of members each workspace type may hold. A null value
| means unlimited; organization workspaces are provisioned separately and
| are never capped here.
|
*/
'seat_limits' => [
'personal' => 1,
'family' => 6,
'organization' => null,
],
];
+34
View File
@@ -2,7 +2,9 @@
namespace Database\Factories; namespace Database\Factories;
use App\FolderVisibility;
use App\Models\Folder; use App\Models\Folder;
use App\Models\Organization;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
@@ -36,4 +38,36 @@ class FolderFactory extends Factory
'user_id' => $folder->user_id, '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,
]);
}
} }
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace Database\Factories;
use App\FolderRole;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
/**
* @extends Factory<Invitation>
*/
class InvitationFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
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(),
]);
}
}
@@ -5,6 +5,7 @@ namespace Database\Factories;
use App\Models\Organization; use App\Models\Organization;
use App\Models\User; use App\Models\User;
use App\OrganizationRole; use App\OrganizationRole;
use App\WorkspaceType;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
/** /**
@@ -21,6 +22,7 @@ class OrganizationFactory extends Factory
{ {
return [ return [
'name' => fake()->unique()->company(), 'name' => fake()->unique()->company(),
'type' => WorkspaceType::Organization,
'personal_workspace' => false, 'personal_workspace' => false,
'lifetime_access' => false, 'lifetime_access' => false,
]; ];
@@ -32,10 +34,22 @@ class OrganizationFactory extends Factory
public function personal(): static public function personal(): static
{ {
return $this->state(fn (array $attributes) => [ return $this->state(fn (array $attributes) => [
'type' => WorkspaceType::Personal,
'personal_workspace' => true, '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 * Give the organization perpetual access, as granted to accounts that
* predate subscriptions. * predate subscriptions.
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('organizations', function (Blueprint $table) {
// Personal for every workspace created so far; family and
// organization workspaces are introduced later.
$table->string('type')->default('personal')->after('name');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('organizations', function (Blueprint $table) {
$table->dropColumn('type');
});
}
};
@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('folders', function (Blueprint $table) {
// Nullable so existing rows can be backfilled in a separate
// migration; the Folder model always writes a value.
$table->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');
});
}
};
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('todos', function (Blueprint $table) {
// Nullable so existing rows can be backfilled in a separate
// migration; the Todo model always writes a value.
$table->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');
});
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('folder_user', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('invitations', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Give every existing folder and todo a workspace so the access rules have
* something to hang off. A folder belongs to whatever workspace its owner
* had active at the time the schema changed, which is the personal
* workspace every account receives. Todos inherit the workspace of their
* folder.
*
* The visibility backfill mirrors predated behaviour: folders in personal
* workspaces are private, and folders in any other workspace start shared
* with members. Rows that already have a value are left untouched, which
* makes this safe to re-run.
*/
public function up(): 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"
),
]);
}
/**
* 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]);
}
};
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Every folder and todo must belong to a workspace: the workspace backfill
* has run by this point, the models fill the id on create, and the bulk
* seeding and transfer paths set it explicitly. Enforce it so no row can
* ever exist without knowing which workspace it belongs to.
*/
public function up(): void
{
Schema::table('folders', function (Blueprint $table) {
$table->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();
});
}
};
+8 -2
View File
@@ -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 // Grandfather the admin so a fresh install is usable before any Stripe
// price is configured. The organization itself is created by the // price is configured.
// model's created hook.
$admin->currentOrganization()->first()?->forceFill([ $admin->currentOrganization()->first()?->forceFill([
'lifetime_access' => true, 'lifetime_access' => true,
])->save(); ])->save();
+18 -3
View File
@@ -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'); $work = $this->createTopLevelFolder($user, 'Work');
$business = $this->createTopLevelFolder($user, 'Business'); $business = $this->createTopLevelFolder($user, 'Business');
$personal = $this->createTopLevelFolder($user, 'Personal'); $personal = $this->createTopLevelFolder($user, 'Personal');
@@ -69,7 +75,10 @@ class DatabaseSeeder extends Seeder
foreach ($samples as [$description, $folderName, $daysFromToday, $status]) { foreach ($samples as [$description, $folderName, $daysFromToday, $status]) {
$todo = Todo::firstOrCreate( $todo = Todo::firstOrCreate(
['user_id' => $user->id, 'folder_id' => $foldersByName[$folderName]->id, 'description' => $description], ['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) { if ($daysFromToday === null) {
@@ -97,7 +106,10 @@ class DatabaseSeeder extends Seeder
{ {
return Folder::firstOrCreate( return Folder::firstOrCreate(
['user_id' => $user->id, 'name' => $name, 'parent_id' => null], ['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( return Folder::firstOrCreate(
['user_id' => $parent->user_id, 'name' => $name, 'parent_id' => $parent->id], ['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),
],
); );
} }
} }
+528
View File
@@ -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(/&quot;/g, '"')
.replace(/&#039;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/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;
}
File diff suppressed because it is too large Load Diff
@@ -6,6 +6,8 @@
<flux:sidebar.brand :name="config('app.name', 'Laravel')" {{ $attributes }}> <flux:sidebar.brand :name="config('app.name', 'Laravel')" {{ $attributes }}>
<x-slot name="logo" class="flex aspect-square size-8 items-center justify-center rounded-md bg-accent-content text-accent-foreground"> <x-slot name="logo" class="flex aspect-square size-8 items-center justify-center rounded-md bg-accent-content text-accent-foreground">
<x-app-logo-icon class="size-5 fill-current text-white dark:text-black" /> <x-app-logo-icon class="size-5 fill-current text-white dark:text-black" />
<x-slot name="logo">
<img src="{{ asset('mytodos_main_logo.svg') }}" alt="{{ config('app.name', 'Laravel') }}" class="size-8" />
</x-slot> </x-slot>
</flux:sidebar.brand> </flux:sidebar.brand>
@else @else
@@ -19,6 +19,9 @@
<flux:navbar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate> <flux:navbar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate>
{{ __('Folders') }} {{ __('Folders') }}
</flux:navbar.item> </flux:navbar.item>
<flux:navbar.item icon="users" :href="route('members')" :current="request()->routeIs('members')" wire:navigate>
{{ __('Members') }}
</flux:navbar.item>
</flux:navbar> </flux:navbar>
<flux:spacer /> <flux:spacer />
@@ -68,6 +71,9 @@
<flux:sidebar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate> <flux:sidebar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate>
{{ __('Folders') }} {{ __('Folders') }}
</flux:sidebar.item> </flux:sidebar.item>
<flux:sidebar.item icon="users" :href="route('members')" :current="request()->routeIs('members')" wire:navigate>
{{ __('Members') }}
</flux:sidebar.item>
</flux:sidebar.group> </flux:sidebar.group>
</flux:sidebar.nav> </flux:sidebar.nav>
@@ -21,10 +21,13 @@
<flux:sidebar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate> <flux:sidebar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate>
{{ __('Folders') }} {{ __('Folders') }}
</flux:sidebar.item> </flux:sidebar.item>
<flux:sidebar.item icon="users" :href="route('members')" :current="request()->routeIs('members')" wire:navigate>
{{ __('Members') }}
</flux:sidebar.item>
</flux:sidebar.group> </flux:sidebar.group>
@if (auth()->user()->isAdmin()) @if (auth()->user()->isSiteAdmin())
<flux:sidebar.group :heading="__('Admin')" class="grid"> <flux:sidebar.group :heading="__('Site admin')" class="grid">
<flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate> <flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate>
{{ __('Notes limits') }} {{ __('Notes limits') }}
</flux:sidebar.item> </flux:sidebar.item>
+16
View File
@@ -0,0 +1,16 @@
<x-mail::message>
# {{ $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 }}**.
<x-mail::button :url="$url">
{{ __('Accept invitation') }}
</x-mail::button>
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,<br>
{{ config('app.name') }}
</x-mail::message>
@@ -2,19 +2,24 @@
use App\Models\User; use App\Models\User;
use Flux\Flux; 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\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Attributes\Title; use Livewire\Attributes\Title;
use Livewire\Component; use Livewire\Component;
use Livewire\WithPagination;
new #[Title('Notes limits')] class extends Component new #[Title('Notes limits')] class extends Component
{ {
use WithPagination;
private const PER_PAGE = 10;
public function mount(): void public function mount(): void
{ {
if (! auth()->user()->isAdmin()) { Gate::authorize('accessAdmin');
abort(403);
}
} }
#[Locked] #[Locked]
@@ -24,12 +29,33 @@ new #[Title('Notes limits')] class extends Component
public string $notesLimitInput = ''; public string $notesLimitInput = '';
public string $search = '';
public function updatedSearch(): void
{
$this->resetPage();
}
#[Computed] #[Computed]
public function users(): Collection public function users(): LengthAwarePaginator
{
return $this->filteredUserQuery()
->orderBy('name')
->paginate(self::PER_PAGE);
}
/**
* @return Builder<User>
*/
private function filteredUserQuery(): Builder
{ {
return User::query() return User::query()
->orderBy('name') ->when(
->get(); $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 public function startEditLimit(int $userId): void
@@ -44,6 +70,8 @@ new #[Title('Notes limits')] class extends Component
public function saveNotesLimit(): void public function saveNotesLimit(): void
{ {
Gate::authorize('accessAdmin');
$user = $this->userById($this->editingUserId); $user = $this->userById($this->editingUserId);
$validated = $this->validate([ $validated = $this->validate([
@@ -69,24 +97,49 @@ new #[Title('Notes limits')] class extends Component
<flux:text class="mt-1">{{ __('Set how many characters each user may write in todo notes.') }}</flux:text> <flux:text class="mt-1">{{ __('Set how many characters each user may write in todo notes.') }}</flux:text>
</div> </div>
<div class="flex flex-wrap items-center gap-2">
<flux:input
size="sm"
type="search"
icon="magnifying-glass"
wire:model.live.debounce.300ms="search"
placeholder="{{ __('Search users…') }}"
class="w-full sm:w-64"
data-test="search-input"
/>
@if ($search !== '')
<flux:button
size="sm"
variant="danger"
icon="x-mark"
wire:click="$set('search', '')"
class="shrink-0"
data-test="clear-search"
>
{{ __('Clear') }}
</flux:button>
@endif
</div>
<flux:card> <flux:card>
<flux:table> <flux:table :paginate="$this->users">
<flux:table.columns> <flux:table.columns>
<flux:table.column>{{ __('Name') }}</flux:table.column> <flux:table.column>{{ __('Name') }}</flux:table.column>
<flux:table.column>{{ __('Email') }}</flux:table.column> <flux:table.column>{{ __('Email') }}</flux:table.column>
<flux:table.column>{{ __('Role') }}</flux:table.column> <flux:table.column>{{ __('Site role') }}</flux:table.column>
<flux:table.column>{{ __('Notes limit') }}</flux:table.column> <flux:table.column>{{ __('Notes limit') }}</flux:table.column>
<flux:table.column align="end" width="5rem">{{ __('Actions') }}</flux:table.column> <flux:table.column align="end" width="5rem">{{ __('Actions') }}</flux:table.column>
</flux:table.columns> </flux:table.columns>
<flux:table.rows> <flux:table.rows>
@foreach ($this->users as $user) @forelse ($this->users as $user)
<flux:table.row :key="$user->id" data-test="user-row-{{ $user->id }}"> <flux:table.row :key="$user->id" data-test="user-row-{{ $user->id }}">
<flux:table.cell>{{ $user->name }}</flux:table.cell> <flux:table.cell>{{ $user->name }}</flux:table.cell>
<flux:table.cell class="text-zinc-500">{{ $user->email }}</flux:table.cell> <flux:table.cell class="text-zinc-500">{{ $user->email }}</flux:table.cell>
<flux:table.cell> <flux:table.cell>
@if ($user->isAdmin()) @if ($user->isSiteAdmin())
<flux:badge size="sm" color="blue">{{ __('Admin') }}</flux:badge> <flux:badge size="sm" color="blue">{{ __('Site admin') }}</flux:badge>
@else @else
<flux:badge size="sm" color="zinc">{{ __('Member') }}</flux:badge> <flux:badge size="sm" color="zinc">{{ __('Member') }}</flux:badge>
@endif @endif
@@ -107,7 +160,13 @@ new #[Title('Notes limits')] class extends Component
</div> </div>
</flux:table.cell> </flux:table.cell>
</flux:table.row> </flux:table.row>
@endforeach @empty
<flux:table.row>
<flux:table.cell colspan="5" align="center" class="py-10">
<flux:text>{{ __('No users match your search.') }}</flux:text>
</flux:table.cell>
</flux:table.row>
@endforelse
</flux:table.rows> </flux:table.rows>
</flux:table> </flux:table>
</flux:card> </flux:card>
@@ -4,6 +4,7 @@ use App\Models\Organization;
use App\Models\Setting; use App\Models\Setting;
use Flux\Flux; use Flux\Flux;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Title; use Livewire\Attributes\Title;
use Livewire\Component; use Livewire\Component;
@@ -12,9 +13,7 @@ new #[Title('Plan pricing')] class extends Component
{ {
public function mount(): void public function mount(): void
{ {
if (! auth()->user()->isAdmin()) { Gate::authorize('accessAdmin');
abort(403);
}
$this->amounts = $this->plans() $this->amounts = $this->plans()
->mapWithKeys(fn (array $plan): array => [ ->mapWithKeys(fn (array $plan): array => [
@@ -61,6 +60,8 @@ new #[Title('Plan pricing')] class extends Component
public function saveAmounts(): void public function saveAmounts(): void
{ {
Gate::authorize('accessAdmin');
$validated = $this->validate([ $validated = $this->validate([
'amounts' => ['required', 'array'], 'amounts' => ['required', 'array'],
'amounts.*' => ['required', 'numeric', 'min:0', 'decimal:0,2'], 'amounts.*' => ['required', 'numeric', 'min:0', 'decimal:0,2'],
@@ -0,0 +1,82 @@
<?php
use App\Models\Invitation;
use App\Models\Organization;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Invitation')] class extends Component
{
public Invitation $invitation;
public function mount(Invitation $invitation): void
{
$this->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);
}
}; ?>
<div class="mx-auto flex w-full max-w-xl flex-col gap-6">
<flux:heading size="xl">{{ __('Invitation') }}</flux:heading>
@if ($invitation->isAccepted())
<flux:callout variant="success" icon="check-circle" data-test="invitation-accepted">
{{ __('This invitation has already been accepted.') }}
</flux:callout>
@elseif ($invitation->isExpired())
<flux:callout variant="warning" icon="clock" data-test="invitation-expired">
{{ __('This invitation has expired. Ask the sender to invite you again.') }}
</flux:callout>
@else
<flux:callout icon="envelope" data-test="invitation-summary">
@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
</flux:callout>
@error('invitation')
<flux:callout variant="danger" data-test="invitation-error">{{ $message }}</flux:callout>
@enderror
<div class="flex justify-end gap-3">
<flux:button variant="ghost" :href="route('dashboard')" wire:navigate>
{{ __('Not now') }}
</flux:button>
<flux:button variant="primary" wire:click="accept" data-test="accept-invitation-button">
{{ __('Accept invitation') }}
</flux:button>
</div>
@endif
</div>
@@ -0,0 +1,334 @@
<?php
use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use App\WorkspaceType;
use Flux\Flux;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Members')] class extends Component
{
public string $inviteEmail = '';
public string $inviteRole = 'member';
/** @var array<int, string> */
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<int, User>
*/
#[Computed]
public function members(): Collection
{
return $this->organization->users()->orderBy('name')->get();
}
/**
* @return Collection<int, Invitation>
*/
#[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();
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div>
<flux:heading size="xl">{{ __('Members') }}</flux:heading>
<flux:text class="mt-1">
{{ __('People with access to the ":name" workspace.', ['name' => $this->organization->name]) }}
</flux:text>
</div>
@php($limit = $this->organization->seatLimit())
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400" data-test="seat-usage">
@if ($limit === null)
{{ __(':count members', ['count' => $this->organization->memberCount()]) }}
@else
{{ __(':count of :limit seats used', ['count' => $this->organization->memberCount(), 'limit' => $limit]) }}
@endif
</flux:text>
<flux:card>
<div class="space-y-4">
<flux:heading size="sm">{{ __('Current members') }}</flux:heading>
@foreach ($this->members as $member)
@php($role = OrganizationRole::tryFrom((string) $member->pivot->role))
<div class="flex flex-wrap items-center justify-between gap-3" data-test="member-row-{{ $member->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $member->name }}</flux:text>
<flux:text size="sm" class="truncate text-zinc-500 dark:text-zinc-400">{{ $member->email }}</flux:text>
</div>
<div class="flex items-center gap-2">
@if ($role === OrganizationRole::Owner || ! $this->canManage || $member->id === auth()->id())
<flux:badge size="sm" color="{{ $role === OrganizationRole::Owner ? 'blue' : 'zinc' }}" data-test="member-role-{{ $member->id }}">
{{ $role?->label() ?? $member->pivot->role }}
</flux:badge>
@else
<flux:select
size="sm"
wire:model.live="memberRoles.{{ $member->id }}"
data-test="member-role-select-{{ $member->id }}"
>
@foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option)
<flux:select.option value="{{ $option->value }}">{{ $option->label() }}</flux:select.option>
@endforeach
</flux:select>
@if ($role !== OrganizationRole::Owner)
<flux:button
size="sm"
variant="ghost"
icon="trash"
wire:click="removeMember({{ $member->id }})"
data-test="remove-member-{{ $member->id }}"
/>
@endif
@endif
</div>
</div>
@endforeach
</div>
</flux:card>
@if ($this->canManage)
@if ($this->organization->canAddMember())
<flux:card>
<form wire:submit="inviteMember" class="space-y-4">
<flux:heading size="sm">{{ __('Invite a member') }}</flux:heading>
<div class="flex flex-wrap items-start gap-3">
<div class="min-w-56 flex-1">
<flux:input
wire:model="inviteEmail"
type="email"
placeholder="name@example.com"
data-test="member-invite-email-input"
/>
<flux:error name="inviteEmail" />
</div>
<div>
<flux:select wire:model="inviteRole" data-test="member-invite-role-select">
@foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option)
<flux:select.option value="{{ $option->value }}">{{ $option->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="inviteRole" />
</div>
<flux:button type="submit" variant="primary" icon="paper-airplane" data-test="invite-member-button">
{{ __('Send invite') }}
</flux:button>
</div>
</form>
</flux:card>
@else
<flux:callout variant="warning" icon="users" data-test="workspace-full-notice">
{{ __('Every seat in this workspace is taken, so no more members can be invited.') }}
</flux:callout>
@endif
@if ($this->invitations->isNotEmpty())
<flux:card>
<div class="space-y-4">
<flux:heading size="sm">{{ __('Pending invitations') }}</flux:heading>
@foreach ($this->invitations as $invitation)
<div class="flex flex-wrap items-center justify-between gap-3" data-test="member-invitation-row-{{ $invitation->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $invitation->email }}</flux:text>
<flux:badge size="sm">{{ $invitation->roleLabel() }}</flux:badge>
</div>
<flux:button
size="sm"
variant="ghost"
icon="x-mark"
wire:click="revokeInvitation({{ $invitation->id }})"
data-test="revoke-member-invitation-{{ $invitation->id }}"
>
{{ __('Revoke') }}
</flux:button>
</div>
@endforeach
</div>
</flux:card>
@endif
@endif
</div>
+47 -20
View File
@@ -55,7 +55,7 @@ new #[Title('Dashboard')] class extends Component
$folderId = (int) $folderId; $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; $this->folderId = $folderId;
} }
} }
@@ -93,7 +93,7 @@ new #[Title('Dashboard')] class extends Component
public function openEditForm(int $todoId): void public function openEditForm(int $todoId): void
{ {
$todo = $this->todoForUser($todoId); $todo = $this->todoForAction($todoId, 'update');
$this->editingTodoId = $todo->id; $this->editingTodoId = $todo->id;
$this->description = $todo->description; $this->description = $todo->description;
@@ -113,11 +113,20 @@ new #[Title('Dashboard')] class extends Component
'todoStatus' => ['required', Rule::enum(TodoStatus::class)], 'todoStatus' => ['required', Rule::enum(TodoStatus::class)],
'dueDate' => ['nullable', 'date'], 'dueDate' => ['nullable', 'date'],
'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()], '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 = [ $data = [
'folder_id' => $validated['formFolderId'], 'folder_id' => $folder->id,
'description' => $validated['description'], 'description' => $validated['description'],
'status' => TodoStatus::from($validated['todoStatus']), 'status' => TodoStatus::from($validated['todoStatus']),
'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null, 'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null,
@@ -125,11 +134,11 @@ new #[Title('Dashboard')] class extends Component
]; ];
if ($this->editingTodoId !== null) { if ($this->editingTodoId !== null) {
$this->todoForUser($this->editingTodoId)->update($data); $this->todoForAction($this->editingTodoId, 'update')->update($data);
} else { } else {
Todo::create($data + [ Todo::create($data + [
'user_id' => auth()->id(), '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 public function toggleComplete(int $todoId): void
{ {
$todo = $this->todoForUser($todoId); $todo = $this->todoForAction($todoId, 'markComplete');
$data = ['completed_at' => $todo->completed_at === null ? now() : null]; $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 public function confirmTodoDelete(int $todoId): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'delete');
$this->confirmingTodoDelete = $todoId; $this->confirmingTodoDelete = $todoId;
$this->modal('confirm-todo-delete')->show(); $this->modal('confirm-todo-delete')->show();
@@ -161,7 +170,7 @@ new #[Title('Dashboard')] class extends Component
public function deleteTodo(): void public function deleteTodo(): void
{ {
$this->todoForUser($this->confirmingTodoDelete)->delete(); $this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete();
$this->confirmingTodoDelete = null; $this->confirmingTodoDelete = null;
$this->modal('confirm-todo-delete')->close(); $this->modal('confirm-todo-delete')->close();
@@ -176,7 +185,7 @@ new #[Title('Dashboard')] class extends Component
#[Computed] #[Computed]
public function todoCounts(): array public function todoCounts(): array
{ {
$query = Todo::query()->forUser(auth()->id()); $query = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId());
return [ return [
'open' => (clone $query)->active()->count(), 'open' => (clone $query)->active()->count(),
@@ -189,7 +198,7 @@ new #[Title('Dashboard')] class extends Component
#[Computed] #[Computed]
public function folderTree(): Collection public function folderTree(): Collection
{ {
return Folder::treeForUser(auth()->id()); return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId());
} }
#[Computed] #[Computed]
@@ -208,12 +217,12 @@ new #[Title('Dashboard')] class extends Component
$tree = $this->folderTree; $tree = $this->folderTree;
$openByFolder = Todo::query() $openByFolder = Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->active() ->active()
->pluck('folder_id') ->pluck('folder_id')
->countBy(); ->countBy();
$overdueByFolder = Todo::query() $overdueByFolder = Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->overdue() ->overdue()
->pluck('folder_id') ->pluck('folder_id')
->countBy(); ->countBy();
@@ -264,7 +273,7 @@ new #[Title('Dashboard')] class extends Component
public function moveTodo(int $todoId, string $direction): void public function moveTodo(int $todoId, string $direction): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'update');
$ids = $this->orderedTodoIds; $ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true); $currentIndex = array_search($todoId, $ids, true);
@@ -284,7 +293,7 @@ new #[Title('Dashboard')] class extends Component
public function handleSort(int $todoId, int $position): void public function handleSort(int $todoId, int $position): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'update');
$offset = ($this->todos->currentPage() - 1) * self::PER_PAGE; $offset = ($this->todos->currentPage() - 1) * self::PER_PAGE;
@@ -317,7 +326,7 @@ new #[Title('Dashboard')] class extends Component
unset($visibleOrder[$currentIndex]); unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId); 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)); $slots = array_keys(array_intersect($ids, $visibleIds));
@@ -326,7 +335,7 @@ new #[Title('Dashboard')] class extends Component
} }
foreach ($ids as $position => $id) { 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); unset($this->todos, $this->orderedTodoIds);
@@ -338,7 +347,7 @@ new #[Title('Dashboard')] class extends Component
private function filteredTodoQuery(): Builder private function filteredTodoQuery(): Builder
{ {
return Todo::query() return Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->when( ->when(
$this->search !== '', $this->search !== '',
fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%') fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%')
@@ -369,9 +378,21 @@ new #[Title('Dashboard')] class extends Component
return $ids; 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) @forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row"> <flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600"> <flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
@can('update', $todo)
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}"> <div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
</div> </div>
@endcan
</flux:table.cell> </flux:table.cell>
<flux:table.cell class="py-0"> <flux:table.cell class="py-0">
@can('markComplete', $todo)
<flux:checkbox <flux:checkbox
:checked="$todo->completed_at !== null" :checked="$todo->completed_at !== null"
:title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')" :title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')"
wire:click="toggleComplete({{ $todo->id }})" wire:click="toggleComplete({{ $todo->id }})"
data-test="toggle-complete-{{ $todo->id }}" data-test="toggle-complete-{{ $todo->id }}"
/> />
@endcan
</flux:table.cell> </flux:table.cell>
<flux:table.cell :variant="$todo->completed_at ? 'strong' : 'default'" data-test="todo-description-{{ $todo->id }}"> <flux:table.cell :variant="$todo->completed_at ? 'strong' : 'default'" data-test="todo-description-{{ $todo->id }}">
@@ -581,6 +606,7 @@ new #[Title('Dashboard')] class extends Component
<flux:table.cell class="py-0"> <flux:table.cell class="py-0">
<div class="flex justify-end gap-1"> <div class="flex justify-end gap-1">
@can('update', $todo)
@if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) @if ($todo->id !== ($this->orderedTodoIds[0] ?? null))
<flux:button <flux:button
size="sm" size="sm"
@@ -619,6 +645,7 @@ new #[Title('Dashboard')] class extends Component
wire:click="confirmTodoDelete({{ $todo->id }})" wire:click="confirmTodoDelete({{ $todo->id }})"
data-test="delete-todo-{{ $todo->id }}" data-test="delete-todo-{{ $todo->id }}"
/> />
@endcan
</div> </div>
</flux:table.cell> </flux:table.cell>
</flux:table.row> </flux:table.row>
+434 -30
View File
@@ -1,10 +1,19 @@
<?php <?php
use App\FolderRole;
use App\FolderVisibility;
use App\Mail\InvitationMail;
use App\Models\Folder; use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\Todo; use App\Models\Todo;
use App\Models\User;
use App\TodoStatus; use App\TodoStatus;
use Flux\Flux;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed; use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
@@ -40,6 +49,18 @@ new #[Title('Folders')] class extends Component
public string $colorDraft = ''; public string $colorDraft = '';
#[Locked]
public ?int $sharingFolderId = null;
public string $inviteEmail = '';
public string $inviteRole = 'viewer';
public string $shareVisibility = 'private';
/** @var array<int, string> */
public array $collaboratorRoles = [];
public bool $showTodoForm = false; public bool $showTodoForm = false;
#[Locked] #[Locked]
@@ -55,8 +76,15 @@ new #[Title('Folders')] class extends Component
public function createTopLevelFolder(): void public function createTopLevelFolder(): void
{ {
$organization = auth()->user()->currentOrganization()->first();
abort_unless(
$organization !== null && auth()->user()->can('create', [Folder::class, $organization]),
403
);
$validated = $this->validate([ $validated = $this->validate([
'newFolderName' => $this->folderNameRules(parentId: null), 'newFolderName' => $this->folderNameRules($organization->id, parentId: null),
'newFolderColor' => $this->folderColorRules(), 'newFolderColor' => $this->folderColorRules(),
]); ]);
@@ -72,7 +100,7 @@ new #[Title('Folders')] class extends Component
public function startChildCreate(int $folderId): void public function startChildCreate(int $folderId): void
{ {
$this->folderForUser($folderId); $this->folderForAction($folderId, 'createChild');
$this->creatingChildOf = $folderId; $this->creatingChildOf = $folderId;
$this->reset('newChildName', 'newChildColor'); $this->reset('newChildName', 'newChildColor');
@@ -86,18 +114,19 @@ new #[Title('Folders')] class extends Component
public function createChildFolder(): void public function createChildFolder(): void
{ {
$this->folderForUser($this->creatingChildOf); $parent = $this->folderForAction($this->creatingChildOf ?? 0, 'createChild');
$validated = $this->validate([ $validated = $this->validate([
'newChildName' => $this->folderNameRules(parentId: $this->creatingChildOf), 'newChildName' => $this->folderNameRules($parent->organization_id, parentId: $parent->id),
'newChildColor' => $this->folderColorRules(), 'newChildColor' => $this->folderColorRules(),
]); ]);
Folder::create([ Folder::create([
'user_id' => auth()->id(), 'user_id' => auth()->id(),
'organization_id' => $parent->organization_id,
'name' => $validated['newChildName'], 'name' => $validated['newChildName'],
'color' => filled($validated['newChildColor']) ? $validated['newChildColor'] : null, 'color' => filled($validated['newChildColor']) ? $validated['newChildColor'] : null,
'parent_id' => $this->creatingChildOf, 'parent_id' => $parent->id,
]); ]);
$this->reset('creatingChildOf', 'newChildName', 'newChildColor'); $this->reset('creatingChildOf', 'newChildName', 'newChildColor');
@@ -105,7 +134,7 @@ new #[Title('Folders')] class extends Component
public function startRename(int $folderId): void public function startRename(int $folderId): void
{ {
$folder = $this->folderForUser($folderId); $folder = $this->folderForAction($folderId, 'update');
$this->renamingFolderId = $folder->id; $this->renamingFolderId = $folder->id;
$this->renameName = $folder->name; $this->renameName = $folder->name;
@@ -119,10 +148,10 @@ new #[Title('Folders')] class extends Component
public function saveRename(): void public function saveRename(): void
{ {
$folder = $this->folderForUser($this->renamingFolderId); $folder = $this->folderForAction($this->renamingFolderId ?? 0, 'update');
$validated = $this->validate([ $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']]); $folder->update(['name' => $validated['renameName']]);
@@ -132,7 +161,7 @@ new #[Title('Folders')] class extends Component
public function confirmFolderDelete(int $folderId): void public function confirmFolderDelete(int $folderId): void
{ {
$this->folderForUser($folderId); $this->folderForAction($folderId, 'delete');
$this->confirmingFolderDelete = $folderId; $this->confirmingFolderDelete = $folderId;
$this->modal('confirm-folder-delete')->show(); $this->modal('confirm-folder-delete')->show();
@@ -140,7 +169,7 @@ new #[Title('Folders')] class extends Component
public function deleteFolder(): void public function deleteFolder(): void
{ {
$folder = $this->folderForUser($this->confirmingFolderDelete); $folder = $this->folderForAction($this->confirmingFolderDelete ?? 0, 'delete');
if ($this->expandedFolderId === $folder->id) { if ($this->expandedFolderId === $folder->id) {
$this->expandedFolderId = null; $this->expandedFolderId = null;
@@ -154,14 +183,14 @@ new #[Title('Folders')] class extends Component
public function toggleExpandFolder(int $folderId): void public function toggleExpandFolder(int $folderId): void
{ {
$this->folderForUser($folderId); $this->visibleFolder($folderId);
$this->expandedFolderId = $this->expandedFolderId === $folderId ? null : $folderId; $this->expandedFolderId = $this->expandedFolderId === $folderId ? null : $folderId;
} }
public function startColorEdit(int $folderId): void public function startColorEdit(int $folderId): void
{ {
$folder = $this->folderForUser($folderId); $folder = $this->folderForAction($folderId, 'update');
$this->colorEditingFolderId = $folder->id; $this->colorEditingFolderId = $folder->id;
$this->colorDraft = $folder->color ?? ''; $this->colorDraft = $folder->color ?? '';
@@ -171,7 +200,7 @@ new #[Title('Folders')] class extends Component
public function saveFolderColor(): void public function saveFolderColor(): void
{ {
$folder = $this->folderForUser($this->colorEditingFolderId ?? 0); $folder = $this->folderForAction($this->colorEditingFolderId ?? 0, 'update');
$validated = $this->validate([ $validated = $this->validate([
'colorDraft' => $this->folderColorRules(), 'colorDraft' => $this->folderColorRules(),
@@ -185,21 +214,179 @@ new #[Title('Folders')] class extends Component
$this->modal('folder-color')->close(); $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 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]); $todo->update(['folder_id' => $folder->id]);
} }
public function moveFolderToTopLevel(int $folderId): void public function moveFolderToTopLevel(int $folderId): void
{ {
$folder = $this->folderForUser($folderId); $folder = $this->folderForAction($folderId, 'update');
$hasSiblingConflict = Folder::query() $hasSiblingConflict = Folder::query()
->forUser(auth()->id()) ->where('organization_id', $folder->organization_id)
->whereNull('parent_id') ->whereNull('parent_id')
->whereKeyNot($folder->id) ->whereKeyNot($folder->id)
->where('name', $folder->name) ->where('name', $folder->name)
@@ -214,8 +401,8 @@ new #[Title('Folders')] class extends Component
public function moveFolderToFolder(int $folderId, int $targetFolderId): void public function moveFolderToFolder(int $folderId, int $targetFolderId): void
{ {
$folder = $this->folderForUser($folderId); $folder = $this->folderForAction($folderId, 'update');
$target = $this->folderForUser($targetFolderId); $target = $this->folderForAction($targetFolderId, 'createChild');
if ($folder->id === $target->id || $this->isDescendantOf($target, $folder)) { if ($folder->id === $target->id || $this->isDescendantOf($target, $folder)) {
return; return;
@@ -251,7 +438,7 @@ new #[Title('Folders')] class extends Component
public function todosForFolder(int $folderId): Collection public function todosForFolder(int $folderId): Collection
{ {
return Todo::query() return Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->where('folder_id', $folderId) ->where('folder_id', $folderId)
->active() ->active()
->priority() ->priority()
@@ -260,7 +447,7 @@ new #[Title('Folders')] class extends Component
public function startTodoCreate(int $folderId): void public function startTodoCreate(int $folderId): void
{ {
$this->folderForUser($folderId); $this->folderForTodoCreate($folderId);
$this->todoFolderId = $folderId; $this->todoFolderId = $folderId;
$this->reset('todoDescription', 'todoStatus', 'todoDueDate', 'todoNotes'); $this->reset('todoDescription', 'todoStatus', 'todoDueDate', 'todoNotes');
@@ -270,7 +457,7 @@ new #[Title('Folders')] class extends Component
public function saveFolderTodo(): void public function saveFolderTodo(): void
{ {
$folder = $this->folderForUser($this->todoFolderId ?? 0); $folder = $this->folderForTodoCreate($this->todoFolderId ?? 0);
$validated = $this->validate([ $validated = $this->validate([
'todoDescription' => ['required', 'string', 'max:255'], 'todoDescription' => ['required', 'string', 'max:255'],
@@ -286,7 +473,7 @@ new #[Title('Folders')] class extends Component
'status' => TodoStatus::from($validated['todoStatus']), 'status' => TodoStatus::from($validated['todoStatus']),
'due_date' => filled($validated['todoDueDate']) ? Carbon::parse($validated['todoDueDate']) : null, 'due_date' => filled($validated['todoDueDate']) ? Carbon::parse($validated['todoDueDate']) : null,
'notes' => filled($validated['todoNotes']) ? $validated['todoNotes'] : 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'); $this->reset('showTodoForm', 'todoFolderId', 'todoDescription', 'todoStatus', 'todoDueDate', 'todoNotes');
@@ -295,7 +482,7 @@ new #[Title('Folders')] class extends Component
#[Computed] #[Computed]
public function folderTree(): Collection public function folderTree(): Collection
{ {
return Folder::treeForUser(auth()->id()); return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId());
} }
#[Computed] #[Computed]
@@ -305,7 +492,10 @@ new #[Title('Folders')] class extends Component
return null; 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] #[Computed]
@@ -324,12 +514,43 @@ new #[Title('Folders')] class extends Component
public function openCounts(): Collection public function openCounts(): Collection
{ {
return Todo::query() return Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->active() ->active()
->pluck('folder_id') ->pluck('folder_id')
->countBy(); ->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<int, User>
*/
#[Computed]
public function sharingCollaborators(): Collection
{
return $this->sharingFolder?->shares()->orderBy('name')->get() ?? collect();
}
/**
* @return Collection<int, Invitation>
*/
#[Computed]
public function sharingInvitations(): Collection
{
return $this->sharingFolder?->invitations()->pending()->orderBy('email')->get() ?? collect();
}
/** /**
* @return array<int, mixed> * @return array<int, mixed>
*/ */
@@ -341,7 +562,7 @@ new #[Title('Folders')] class extends Component
/** /**
* @return array<int, mixed> * @return array<int, mixed>
*/ */
private function folderNameRules(?int $parentId = null, ?int $ignoreId = null): array private function folderNameRules(int $organizationId, ?int $parentId = null, ?int $ignoreId = null): array
{ {
return [ return [
'required', 'required',
@@ -350,14 +571,39 @@ new #[Title('Folders')] class extends Component
Rule::unique('folders', 'name') Rule::unique('folders', 'name')
->ignore($ignoreId) ->ignore($ignoreId)
->where(fn ($query) => $query ->where(fn ($query) => $query
->where('user_id', auth()->id()) ->where('organization_id', $organizationId)
->where('parent_id', $parentId)), ->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,6 +711,7 @@ new #[Title('Folders')] class extends Component
</form> </form>
@else @else
<div class="flex min-w-0 items-center gap-2"> <div class="flex min-w-0 items-center gap-2">
@can('update', $node['folder'])
<div <div
x-data="{ dragging: false }" x-data="{ dragging: false }"
draggable="true" draggable="true"
@@ -477,10 +724,23 @@ new #[Title('Folders')] class extends Component
> >
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
</div> </div>
@endcan
<x-folder-dot :color="$node['folder']->color" data-test="folder-dot-{{ $node['folder']->id }}" /> <x-folder-dot :color="$node['folder']->color" data-test="folder-dot-{{ $node['folder']->id }}" />
<flux:heading size="sm" class="truncate" data-test="folder-name-{{ $node['folder']->id }}"> <flux:heading size="sm" class="truncate" data-test="folder-name-{{ $node['folder']->id }}">
{{ $node['folder']->name }} {{ $node['folder']->name }}
</flux:heading> </flux:heading>
<span
class="truncate text-xs text-zinc-400 dark:text-zinc-500"
title="{{ __('Workspace') }}"
data-test="folder-workspace-{{ $node['folder']->id }}"
>
{{ $node['folder']->organization?->name }}
</span>
@if ($node['folder']->visibility === \App\FolderVisibility::Workspace || $node['folder']->shares_count > 0)
<flux:badge size="sm" color="zinc" icon="users" data-test="folder-shared-{{ $node['folder']->id }}">
{{ __('Shared') }}
</flux:badge>
@endif
</div> </div>
<flux:badge <flux:badge
@@ -500,6 +760,18 @@ new #[Title('Folders')] class extends Component
<flux:spacer /> <flux:spacer />
<div class="flex items-center gap-1"> <div class="flex items-center gap-1">
@can('manageShares', $node['folder'])
<flux:tooltip :content="__('Share')">
<flux:button
size="sm"
variant="ghost"
icon="user-plus"
wire:click="startShare({{ $node['folder']->id }})"
data-test="share-folder-{{ $node['folder']->id }}"
/>
</flux:tooltip>
@endcan
@can('update', $node['folder'])
<flux:tooltip :content="__('Choose color')"> <flux:tooltip :content="__('Choose color')">
<flux:button <flux:button
size="sm" size="sm"
@@ -509,6 +781,7 @@ new #[Title('Folders')] class extends Component
data-test="color-folder-{{ $node['folder']->id }}" data-test="color-folder-{{ $node['folder']->id }}"
/> />
</flux:tooltip> </flux:tooltip>
@endcan
<flux:tooltip :content="__('View todos')"> <flux:tooltip :content="__('View todos')">
<flux:button <flux:button
size="sm" size="sm"
@@ -519,6 +792,7 @@ new #[Title('Folders')] class extends Component
data-test="view-todos-{{ $node['folder']->id }}" data-test="view-todos-{{ $node['folder']->id }}"
/> />
</flux:tooltip> </flux:tooltip>
@can('create', [App\Models\Todo::class, $node['folder']])
<flux:tooltip :content="__('Add todo')"> <flux:tooltip :content="__('Add todo')">
<flux:button <flux:button
size="sm" size="sm"
@@ -528,6 +802,8 @@ new #[Title('Folders')] class extends Component
data-test="add-todo-{{ $node['folder']->id }}" data-test="add-todo-{{ $node['folder']->id }}"
/> />
</flux:tooltip> </flux:tooltip>
@endcan
@can('createChild', $node['folder'])
<flux:tooltip :content="__('Add sub-folder')"> <flux:tooltip :content="__('Add sub-folder')">
<flux:button <flux:button
size="sm" size="sm"
@@ -537,6 +813,8 @@ new #[Title('Folders')] class extends Component
data-test="add-child-{{ $node['folder']->id }}" data-test="add-child-{{ $node['folder']->id }}"
/> />
</flux:tooltip> </flux:tooltip>
@endcan
@can('update', $node['folder'])
<flux:tooltip :content="__('Rename')"> <flux:tooltip :content="__('Rename')">
<flux:button <flux:button
size="sm" size="sm"
@@ -555,6 +833,7 @@ new #[Title('Folders')] class extends Component
data-test="delete-folder-{{ $node['folder']->id }}" data-test="delete-folder-{{ $node['folder']->id }}"
/> />
</flux:tooltip> </flux:tooltip>
@endcan
</div> </div>
@endif @endif
</div> </div>
@@ -739,4 +1018,129 @@ new #[Title('Folders')] class extends Component
</div> </div>
</div> </div>
</flux:modal> </flux:modal>
<flux:modal name="folder-share" class="md:w-2xl">
@if ($this->sharingFolder !== null)
<div class="space-y-6" data-test="folder-share-panel">
<div>
<flux:heading size="lg">{{ __('Share folder') }}</flux:heading>
<flux:text class="mt-2">
{{ __('Manage who can access ":name" and what they can do.', ['name' => $this->sharingFolder->name]) }}
</flux:text>
</div>
@if ($this->sharingFolder->organization !== null && ! $this->sharingFolder->organization->isPersonal())
<flux:field>
<flux:label>{{ __('Visibility') }}</flux:label>
<flux:select wire:model.live="shareVisibility" data-test="visibility-select">
@foreach (FolderVisibility::cases() as $visibility)
<flux:select.option value="{{ $visibility->value }}">{{ $visibility->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="shareVisibility" />
<flux:description>
{{ __('Workspace folders are visible to every member of :name.', ['name' => $this->sharingFolder->organization->name]) }}
</flux:description>
</flux:field>
@else
<flux:callout icon="lock-closed" data-test="personal-share-notice">
{{ __('This folder is only visible to you. Personal workspaces cannot hold other members.') }}
</flux:callout>
@endif
<div class="space-y-3">
<flux:heading size="sm">{{ __('Collaborators') }}</flux:heading>
<div class="flex items-center justify-between gap-3" data-test="folder-owner-row">
<flux:text>{{ $this->sharingFolder->user?->name }}</flux:text>
<flux:badge size="sm" color="blue">{{ __('Owner') }}</flux:badge>
</div>
@forelse ($this->sharingCollaborators as $collaborator)
<div class="flex flex-wrap items-center justify-between gap-3" data-test="collaborator-row-{{ $collaborator->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $collaborator->name }}</flux:text>
<flux:text size="sm" class="truncate text-zinc-500 dark:text-zinc-400">{{ $collaborator->email }}</flux:text>
</div>
<div class="flex items-center gap-2">
<flux:select
size="sm"
wire:model.live="collaboratorRoles.{{ $collaborator->id }}"
data-test="collaborator-role-{{ $collaborator->id }}"
>
@foreach (FolderRole::assignable() as $role)
<flux:select.option value="{{ $role->value }}">{{ $role->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:button
size="sm"
variant="ghost"
icon="trash"
wire:click="removeCollaborator({{ $collaborator->id }})"
data-test="remove-collaborator-{{ $collaborator->id }}"
/>
</div>
</div>
@empty
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">{{ __('No one else has access yet.') }}</flux:text>
@endforelse
</div>
<form wire:submit="inviteCollaborator" class="space-y-3">
<flux:heading size="sm">{{ __('Invite by email') }}</flux:heading>
<div class="flex flex-wrap items-start gap-3">
<div class="min-w-56 flex-1">
<flux:input
wire:model="inviteEmail"
type="email"
placeholder="name@example.com"
data-test="invite-email-input"
/>
<flux:error name="inviteEmail" />
</div>
<div>
<flux:select wire:model="inviteRole" data-test="invite-role-select">
@foreach (FolderRole::assignable() as $role)
<flux:select.option value="{{ $role->value }}">{{ $role->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="inviteRole" />
</div>
<flux:button type="submit" variant="primary" icon="paper-airplane" data-test="invite-collaborator-button">
{{ __('Send invite') }}
</flux:button>
</div>
</form>
@if ($this->sharingInvitations->isNotEmpty())
<div class="space-y-3">
<flux:heading size="sm">{{ __('Pending invitations') }}</flux:heading>
@foreach ($this->sharingInvitations as $invitation)
<div class="flex flex-wrap items-center justify-between gap-3" data-test="invitation-row-{{ $invitation->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $invitation->email }}</flux:text>
<flux:badge size="sm">{{ $invitation->roleLabel() }}</flux:badge>
</div>
<flux:button
size="sm"
variant="ghost"
icon="x-mark"
wire:click="revokeFolderInvitation({{ $invitation->id }})"
data-test="revoke-invitation-{{ $invitation->id }}"
>
{{ __('Revoke') }}
</flux:button>
</div>
@endforeach
</div>
@endif
<div class="flex justify-end gap-3">
<flux:button variant="ghost" wire:click="closeShare" data-test="close-share-button">
{{ __('Done') }}
</flux:button>
</div>
</div>
@endif
</flux:modal>
</div> </div>
+44 -17
View File
@@ -52,7 +52,7 @@ new #[Title('Todos')] class extends Component
$folderId = (int) $folderId; $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; $this->folderId = $folderId;
} }
} }
@@ -90,7 +90,7 @@ new #[Title('Todos')] class extends Component
public function openEditForm(int $todoId): void public function openEditForm(int $todoId): void
{ {
$todo = $this->todoForUser($todoId); $todo = $this->todoForAction($todoId, 'update');
$this->editingTodoId = $todo->id; $this->editingTodoId = $todo->id;
$this->description = $todo->description; $this->description = $todo->description;
@@ -110,11 +110,20 @@ new #[Title('Todos')] class extends Component
'todoStatus' => ['required', Rule::enum(TodoStatus::class)], 'todoStatus' => ['required', Rule::enum(TodoStatus::class)],
'dueDate' => ['nullable', 'date'], 'dueDate' => ['nullable', 'date'],
'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()], '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 = [ $data = [
'folder_id' => $validated['formFolderId'], 'folder_id' => $folder->id,
'description' => $validated['description'], 'description' => $validated['description'],
'status' => TodoStatus::from($validated['todoStatus']), 'status' => TodoStatus::from($validated['todoStatus']),
'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null, 'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null,
@@ -122,11 +131,11 @@ new #[Title('Todos')] class extends Component
]; ];
if ($this->editingTodoId !== null) { if ($this->editingTodoId !== null) {
$this->todoForUser($this->editingTodoId)->update($data); $this->todoForAction($this->editingTodoId, 'update')->update($data);
} else { } else {
Todo::create($data + [ Todo::create($data + [
'user_id' => auth()->id(), '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 public function toggleComplete(int $todoId): void
{ {
$todo = $this->todoForUser($todoId); $todo = $this->todoForAction($todoId, 'markComplete');
$data = ['completed_at' => $todo->completed_at === null ? now() : null]; $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 public function confirmTodoDelete(int $todoId): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'delete');
$this->confirmingTodoDelete = $todoId; $this->confirmingTodoDelete = $todoId;
$this->modal('confirm-todo-delete')->show(); $this->modal('confirm-todo-delete')->show();
@@ -158,7 +167,7 @@ new #[Title('Todos')] class extends Component
public function deleteTodo(): void public function deleteTodo(): void
{ {
$this->todoForUser($this->confirmingTodoDelete)->delete(); $this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete();
$this->confirmingTodoDelete = null; $this->confirmingTodoDelete = null;
$this->modal('confirm-todo-delete')->close(); $this->modal('confirm-todo-delete')->close();
@@ -181,7 +190,7 @@ new #[Title('Todos')] class extends Component
#[Computed] #[Computed]
public function folderTree(): Collection public function folderTree(): Collection
{ {
return Folder::treeForUser(auth()->id()); return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId());
} }
#[Computed] #[Computed]
@@ -243,7 +252,7 @@ new #[Title('Todos')] class extends Component
public function moveTodo(int $todoId, string $direction): void public function moveTodo(int $todoId, string $direction): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'update');
$ids = $this->orderedTodoIds; $ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true); $currentIndex = array_search($todoId, $ids, true);
@@ -263,7 +272,7 @@ new #[Title('Todos')] class extends Component
public function handleSort(int $todoId, int $position): void public function handleSort(int $todoId, int $position): void
{ {
$this->todoForUser($todoId); $this->todoForAction($todoId, 'update');
$this->reorderTodo($todoId, $position); $this->reorderTodo($todoId, $position);
} }
@@ -294,7 +303,7 @@ new #[Title('Todos')] class extends Component
unset($visibleOrder[$currentIndex]); unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId); 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)); $slots = array_keys(array_intersect($ids, $visibleIds));
@@ -303,7 +312,7 @@ new #[Title('Todos')] class extends Component
} }
foreach ($ids as $position => $id) { 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); unset($this->todos, $this->orderedTodoIds);
@@ -315,7 +324,7 @@ new #[Title('Todos')] class extends Component
private function filteredTodoQuery(): Builder private function filteredTodoQuery(): Builder
{ {
return Todo::query() return Todo::query()
->forUser(auth()->id()) ->visibleTo(auth()->id(), $this->activeWorkspaceId())
->when( ->when(
$this->search !== '', $this->search !== '',
fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%') fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%')
@@ -346,9 +355,21 @@ new #[Title('Todos')] class extends Component
return $ids; 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) @forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row"> <flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600"> <flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
@can('update', $todo)
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}"> <div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
</div> </div>
@endcan
</flux:table.cell> </flux:table.cell>
<flux:table.cell class="py-0"> <flux:table.cell class="py-0">
@can('markComplete', $todo)
<flux:checkbox <flux:checkbox
:checked="$todo->completed_at !== null" :checked="$todo->completed_at !== null"
:title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')" :title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')"
wire:click="toggleComplete({{ $todo->id }})" wire:click="toggleComplete({{ $todo->id }})"
data-test="toggle-complete-{{ $todo->id }}" data-test="toggle-complete-{{ $todo->id }}"
/> />
@endcan
</flux:table.cell> </flux:table.cell>
<flux:table.cell :variant="$todo->completed_at ? 'strong' : 'default'" data-test="todo-description-{{ $todo->id }}"> <flux:table.cell :variant="$todo->completed_at ? 'strong' : 'default'" data-test="todo-description-{{ $todo->id }}">
@@ -491,6 +516,7 @@ new #[Title('Todos')] class extends Component
<flux:table.cell class="py-0"> <flux:table.cell class="py-0">
<div class="flex justify-end gap-1"> <div class="flex justify-end gap-1">
@can('update', $todo)
@if ($todo->id !== ($this->orderedTodoIds[0] ?? null)) @if ($todo->id !== ($this->orderedTodoIds[0] ?? null))
<flux:button <flux:button
size="sm" size="sm"
@@ -529,6 +555,7 @@ new #[Title('Todos')] class extends Component
wire:click="confirmTodoDelete({{ $todo->id }})" wire:click="confirmTodoDelete({{ $todo->id }})"
data-test="delete-todo-{{ $todo->id }}" data-test="delete-todo-{{ $todo->id }}"
/> />
@endcan
</div> </div>
</flux:table.cell> </flux:table.cell>
</flux:table.row> </flux:table.row>
+10
View File
@@ -10,14 +10,24 @@ Route::livewire('pricing', 'pages::pricing')->name('pricing');
Route::middleware(['auth'])->group(function () { Route::middleware(['auth'])->group(function () {
Route::livewire('subscription/confirmed', 'pages::subscription-confirmed')->name('subscription.confirmed'); 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::middleware(['auth', 'verified', 'subscribed'])->group(function () {
Route::livewire('dashboard', 'pages::dashboard')->name('dashboard'); Route::livewire('dashboard', 'pages::dashboard')->name('dashboard');
Route::livewire('todos', 'pages::todos')->name('todos'); Route::livewire('todos', 'pages::todos')->name('todos');
Route::livewire('folders', 'pages::folders')->name('folders'); Route::livewire('folders', 'pages::folders')->name('folders');
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/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('admin/plan-pricing', 'pages::admin.plan-pricing')->name('admin.plan-pricing');
}); });
});
require __DIR__.'/settings.php'; require __DIR__.'/settings.php';
+103
View File
@@ -1,6 +1,8 @@
<?php <?php
use App\Models\Organization;
use App\Models\User; use App\Models\User;
use App\OrganizationRole;
use Livewire\Livewire; use Livewire\Livewire;
test('guests are redirected from the notes limits page', function () { test('guests are redirected from the notes limits page', function () {
@@ -15,6 +17,34 @@ test('non-admins cannot access the notes limits page', function () {
$this->get(route('admin.notes-limits'))->assertForbidden(); $this->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 () { test('non-admins do not see the notes limits navigation item', function () {
$user = User::factory()->create(); $user = User::factory()->create();
$this->actingAs($user); $this->actingAs($user);
@@ -33,6 +63,36 @@ test('admins see the notes limits navigation item', function () {
->assertSee('Notes limits'); ->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 () { test('admins can view the notes limits page', function () {
$user = User::factory()->asAdmin()->create(); $user = User::factory()->asAdmin()->create();
$this->actingAs($user); $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); 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);
});
+1 -1
View File
@@ -13,7 +13,7 @@ test('base data includes a default admin user', function () {
expect($admin)->not->toBeNull() expect($admin)->not->toBeNull()
->and($admin->name)->toBe('Administrator') ->and($admin->name)->toBe('Administrator')
->and($admin->notes_limit)->toBe(1000); ->and($admin->notes_limit)->toBe(1000);
$this->assertTrue($admin->isAdmin()); $this->assertTrue($admin->isSiteAdmin());
}); });
test('base data seeding is idempotent', function () { test('base data seeding is idempotent', function () {
+33
View File
@@ -3,6 +3,7 @@
use App\Models\Organization; use App\Models\Organization;
use App\Models\Setting; use App\Models\Setting;
use App\Models\User; use App\Models\User;
use App\OrganizationRole;
use Livewire\Livewire; use Livewire\Livewire;
test('guests are redirected from the plan pricing page', function () { 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(); $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 () { test('non-admins do not see the plan pricing navigation item', function () {
$this->actingAs(User::factory()->create()); $this->actingAs(User::factory()->create());
+276
View File
@@ -0,0 +1,276 @@
<?php
use App\FolderRole;
use App\FolderVisibility;
use App\Models\Folder;
use App\Models\Organization;
use App\Models\Todo;
use App\Models\User;
use App\OrganizationRole;
function familyWorkspace(User $owner): Organization
{
$org = Organization::factory()->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();
});
+137
View File
@@ -0,0 +1,137 @@
<?php
use App\FolderRole;
use App\FolderVisibility;
use App\Mail\InvitationMail;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
/**
* Create a family workspace owned by the given user and make it their active
* workspace, which is what the folders page scopes to.
*/
function familyWorkspaceFor(User $owner): Organization
{
$organization = Organization::factory()->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);
});
+19
View File
@@ -334,6 +334,25 @@ test('users cannot move a todo to another user folder', function () {
->call('moveTodoToFolder', $todo->id, $foreign->id); ->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 () { test('users cannot move another user todo', function () {
$owner = User::factory()->create(); $owner = User::factory()->create();
$ownerFolder = Folder::factory()->for($owner)->create(['name' => 'Owner Folder']); $ownerFolder = Folder::factory()->for($owner)->create(['name' => 'Owner Folder']);
+103
View File
@@ -0,0 +1,103 @@
<?php
use App\FolderRole;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use Livewire\Livewire;
test('guests are redirected to login before they can accept', function () {
$invitation = Invitation::factory()->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"');
});
+177
View File
@@ -0,0 +1,177 @@
<?php
use App\FolderRole;
use App\Mail\InvitationMail;
use App\Models\Folder;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
test('a folder invitation resolves its inviteable and stays valid', function () {
$owner = User::factory()->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));
});
+180
View File
@@ -0,0 +1,180 @@
<?php
use App\FolderRole;
use App\Models\Folder;
use App\Models\Organization;
use App\Models\Todo;
use App\Models\User;
use App\OrganizationRole;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Livewire\Livewire;
/**
* Add a member to a fresh family workspace and make it the active workspace
* for both users, so the pages (which scope to the active workspace) show the
* folders the workspace shares.
*/
function sharedWorkspace(User $owner, ?User $member = null, OrganizationRole $role = OrganizationRole::Member): Organization
{
$organization = Organization::factory()->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);
});
+151
View File
@@ -0,0 +1,151 @@
<?php
use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use App\WorkspaceType;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
/**
* Create a family workspace owned by the given user and make it their active
* workspace.
*/
function membersWorkspaceFor(User $owner): Organization
{
$organization = Organization::factory()->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);
});
+141
View File
@@ -0,0 +1,141 @@
<?php
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use App\WorkspaceType;
use Illuminate\Support\Facades\Schema;
test('folder and todo workspace ids are enforced as not nullable', function () {
$folderColumn = collect(Schema::getColumns('folders'))->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);
});