update plans; assign lifetime;kanban; column sort;
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-04 11:10:05 -08:00
parent 177f122c10
commit 31a80ec4d1
26 changed files with 2984 additions and 672 deletions
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace App\Concerns;
use App\Models\Folder;
use App\Models\Todo;
use App\TodoStatus;
use Illuminate\Database\Eloquent\Builder;
/**
* Adds sortable column state and query ordering for todo tables.
*/
trait SortsTodos
{
public ?string $sortBy = null;
public string $sortDirection = 'asc';
/**
* Toggle the sort column and direction. Clicking the active column flips
* its direction, and clicking it once more restores the manual order.
*/
public function sort(string $column): void
{
if (! in_array($column, $this->sortableTodoColumns(), true)) {
return;
}
if ($this->sortBy !== $column) {
$this->sortBy = $column;
$this->sortDirection = 'asc';
} elseif ($this->sortDirection === 'asc') {
$this->sortDirection = 'desc';
} else {
$this->sortBy = null;
$this->sortDirection = 'asc';
}
$this->sortChanged();
}
/**
* Determine whether a column sort is currently applied.
*/
protected function hasActiveSort(): bool
{
return $this->sortBy !== null;
}
/**
* @return list<string>
*/
protected function sortableTodoColumns(): array
{
return ['description', 'status', 'folder', 'due_date', 'created_at', 'completed_at'];
}
/**
* @param Builder<Todo> $query
* @return Builder<Todo>
*/
protected function applyTodoSort(Builder $query): Builder
{
if ($this->sortBy === null) {
return $query->priority();
}
$direction = $this->sortDirection === 'desc' ? 'desc' : 'asc';
return (match ($this->sortBy) {
'description' => $query->orderBy('description', $direction),
'status' => $this->orderByStatus($query, $direction),
'folder' => $query->orderBy(
Folder::query()->select('name')->whereColumn('folders.id', 'todos.folder_id'),
$direction
),
'due_date' => $query
->orderByRaw('due_date IS NULL')
->orderBy('due_date', $direction),
'created_at' => $query->orderBy('created_at', $direction),
'completed_at' => $query
->orderByRaw('completed_at IS NULL')
->orderBy('completed_at', $direction),
default => $query->priority(),
})->orderBy('id');
}
/**
* @param Builder<Todo> $query
* @return Builder<Todo>
*/
private function orderByStatus(Builder $query, string $direction): Builder
{
$statuses = TodoStatus::cases();
$cases = collect($statuses)
->map(fn (TodoStatus $status, int $index) => 'WHEN ? THEN '.$index)
->implode(' ');
return $query->orderByRaw(
"CASE todos.status {$cases} ELSE 999 END {$direction}",
collect($statuses)->map(fn (TodoStatus $status) => $status->value)->all()
);
}
/**
* Hook for components to reset their pagination when the sort changes.
*/
protected function sortChanged(): void {}
}
+11 -1
View File
@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
@@ -30,6 +31,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
* @property WorkspaceType $type
* @property bool $personal_workspace
* @property bool $lifetime_access
* @property int|null $plan_id
* @property string|null $stripe_id
* @property string|null $pm_type
* @property string|null $pm_last_four
@@ -37,7 +39,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'type', 'personal_workspace', 'lifetime_access'])]
#[Fillable(['name', 'type', 'personal_workspace', 'lifetime_access', 'plan_id'])]
#[Hidden(['stripe_id'])]
class Organization extends Model
{
@@ -69,6 +71,14 @@ class Organization extends Model
->withTimestamps();
}
/**
* @return BelongsTo<Plan, $this>
*/
public function plan(): BelongsTo
{
return $this->belongsTo(Plan::class);
}
/**
* @return HasMany<Folder, $this>
*/
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Models;
use App\WorkspaceType;
use Database\Factories\PlanFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
/**
* A plan is a tier of access: it decides what kind of workspace a subscriber
* gets, how many members it may hold, and how many folders and notes its
* members may create. Every plan is editable by a site administrator, so the
* limits live in the database rather than in configuration.
*
* @property int $id
* @property string $key
* @property string $name
* @property WorkspaceType $workspace_type
* @property string|null $stripe_price
* @property string $interval
* @property int $amount
* @property int|null $seat_limit
* @property int|null $max_folders
* @property int|null $max_folder_depth
* @property int|null $max_notes_per_folder
* @property int|null $note_chars
* @property int $sort_order
* @property bool $is_active
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable([
'key',
'name',
'workspace_type',
'stripe_price',
'interval',
'amount',
'seat_limit',
'max_folders',
'max_folder_depth',
'max_notes_per_folder',
'note_chars',
'sort_order',
'is_active',
])]
class Plan extends Model
{
/** @use HasFactory<PlanFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'workspace_type' => WorkspaceType::class,
'amount' => 'integer',
'seat_limit' => 'integer',
'max_folders' => 'integer',
'max_folder_depth' => 'integer',
'max_notes_per_folder' => 'integer',
'note_chars' => 'integer',
'sort_order' => 'integer',
'is_active' => 'boolean',
];
}
/**
* @return HasMany<Organization, $this>
*/
public function organizations(): HasMany
{
return $this->hasMany(Organization::class);
}
/**
* Determine whether the plan can be sold, that is, it has a Stripe price.
*/
public function isPurchasable(): bool
{
return is_string($this->stripe_price) && $this->stripe_price !== '';
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
* @property Carbon|null $two_factor_confirmed_at
* @property string|null $remember_token
* @property bool $is_admin
* @property int $notes_limit
* @property int|null $notes_limit
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
Generated
+631 -588
View File
File diff suppressed because it is too large Load Diff
@@ -3,6 +3,7 @@
namespace Database\Factories;
use App\Models\Organization;
use App\Models\Plan;
use App\Models\User;
use App\OrganizationRole;
use App\WorkspaceType;
@@ -61,6 +62,20 @@ class OrganizationFactory extends Factory
]);
}
/**
* Give the organization the plan with the given key.
*/
public function withPlan(string $key): static
{
return $this->afterCreating(function (Organization $organization) use ($key): void {
$planId = Plan::query()->where('key', $key)->value('id');
if ($planId !== null) {
$organization->forceFill(['plan_id' => $planId])->save();
}
});
}
/**
* Add the given user to the organization with the given role.
*/
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace Database\Factories;
use App\Models\Plan;
use App\WorkspaceType;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends Factory<Plan>
*/
class PlanFactory extends Factory
{
/**
* Define the model's default state.
*
* A default plan is unlimited and not purchasable, matching the most
* permissive tier so tests can opt into limits explicitly.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'key' => fake()->unique()->slug(2),
'name' => fake()->words(2, true),
'workspace_type' => WorkspaceType::Personal,
'stripe_price' => null,
'interval' => 'month',
'amount' => 0,
'seat_limit' => null,
'max_folders' => null,
'max_folder_depth' => null,
'max_notes_per_folder' => null,
'note_chars' => null,
'sort_order' => 0,
'is_active' => true,
];
}
/**
* Indicate that the plan is sold through Stripe at the given price.
*/
public function purchasable(?string $price = null): static
{
return $this->state(fn (array $attributes) => [
'stripe_price' => $price ?? 'price_'.Str::random(12),
]);
}
/**
* Indicate that the plan caps the given limits.
*/
public function limited(int $maxFolders, int $maxFolderDepth, int $maxNotesPerFolder, int $noteChars): static
{
return $this->state(fn (array $attributes) => [
'max_folders' => $maxFolders,
'max_folder_depth' => $maxFolderDepth,
'max_notes_per_folder' => $maxNotesPerFolder,
'note_chars' => $noteChars,
]);
}
}
+61 -8
View File
@@ -2,6 +2,7 @@
namespace Database\Factories;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\Factory;
@@ -29,6 +30,14 @@ class UserFactory extends Factory
*/
protected bool $subscribed = true;
/**
* The plan given to the user's personal organization. Following the plan
* of record, a factory user starts on the unlimited plan so tests are not
* constrained by folder or note limits. Call withPlan() or withFreePlan()
* to opt into a specific tier.
*/
protected ?string $planKey = 'unlimited';
/**
* Define the model's default state.
*
@@ -49,10 +58,10 @@ class UserFactory extends Factory
}
/**
* Create the model and, unless opted out, give it an active subscription on
* the personal organization the model's created hook just made.
* Create the model and give its personal organization a plan. Unless opted
* out, the model also gets an active subscription on that organization.
*
* The flag is read here rather than in an afterCreating callback because
* The flags are read here rather than in an afterCreating callback because
* afterCreating() hands back a new factory instance, so a closure registered
* there would close over a copy that unsubscribed() never reaches.
*
@@ -63,13 +72,15 @@ class UserFactory extends Factory
{
$result = parent::create($attributes, $parent);
if (! $this->subscribed) {
return $result;
}
$users = $result instanceof SupportCollection ? $result : collect([$result]);
$users->each(fn (User $user) => $this->subscribe($user));
$users->each(function (User $user): void {
if ($this->subscribed) {
$this->subscribe($user);
}
$this->assignPlan($user, $this->planKey);
});
return $result;
}
@@ -85,6 +96,24 @@ class UserFactory extends Factory
return $this;
}
/**
* Give the user's personal organization the plan with the given key.
*/
public function withPlan(string $key): static
{
$this->planKey = $key;
return $this;
}
/**
* Give the user's personal organization the free plan.
*/
public function withFreePlan(): static
{
return $this->withPlan('free');
}
/**
* Indicate that the model's email address should be unverified.
*/
@@ -140,4 +169,28 @@ class UserFactory extends Factory
Subscription::factory()->create(['organization_id' => $organization->id]);
}
/**
* Assign a plan to the user's current organization.
*/
protected function assignPlan(User $user, ?string $planKey): void
{
if ($planKey === null) {
return;
}
$organization = $user->currentOrganization()->first();
if ($organization === null) {
return;
}
$planId = Plan::query()->where('key', $planKey)->value('id');
if ($planId === null) {
return;
}
$organization->forceFill(['plan_id' => $planId])->save();
}
}
@@ -0,0 +1,137 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('plans', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->string('name');
// Which kind of workspace the plan provisions. Free and personal
// plans map to a single-user personal workspace, family to a shared
// family workspace, and organization to a shared organization.
$table->string('workspace_type')->default('personal');
// The Stripe price id the plan is sold against. Plans without one
// are not purchasable and are hidden from the pricing page.
$table->string('stripe_price')->nullable();
$table->string('interval')->default('month');
// The advertised price, in minor units, so a bad edit cannot
// silently advertise a free plan.
$table->unsignedInteger('amount')->default(0);
// Limits. A null limit means unlimited.
$table->unsignedInteger('seat_limit')->nullable();
$table->unsignedInteger('max_folders')->nullable();
$table->unsignedInteger('max_folder_depth')->nullable();
$table->unsignedInteger('max_notes_per_folder')->nullable();
$table->unsignedInteger('note_chars')->nullable();
$table->unsignedInteger('sort_order')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
// The plans that ship with the application. The paid personal plan
// reuses the configured Pro price, so it stays in step with the Stripe
// product created in the dashboard.
$personalPrice = config('plans.plans.pro.price');
$personalPrice = is_string($personalPrice) && $personalPrice !== '' ? $personalPrice : null;
$plans = [
[
'key' => 'free',
'name' => 'Free',
'workspace_type' => 'personal',
'stripe_price' => null,
'amount' => 0,
'seat_limit' => 1,
'max_folders' => 3,
'max_folder_depth' => 1,
'max_notes_per_folder' => 50,
'note_chars' => 1000,
'sort_order' => 0,
],
[
'key' => 'personal',
'name' => 'Personal',
'workspace_type' => 'personal',
'stripe_price' => $personalPrice,
'amount' => 1000,
'seat_limit' => 1,
'max_folders' => null,
'max_folder_depth' => null,
'max_notes_per_folder' => null,
'note_chars' => null,
'sort_order' => 1,
],
[
'key' => 'family',
'name' => 'Family',
'workspace_type' => 'family',
'stripe_price' => null,
'amount' => 2500,
'seat_limit' => 6,
'max_folders' => null,
'max_folder_depth' => null,
'max_notes_per_folder' => null,
'note_chars' => null,
'sort_order' => 2,
],
[
'key' => 'organization',
'name' => 'Organization',
'workspace_type' => 'organization',
'stripe_price' => null,
'amount' => 9900,
'seat_limit' => null,
'max_folders' => null,
'max_folder_depth' => null,
'max_notes_per_folder' => null,
'note_chars' => null,
'sort_order' => 3,
],
[
'key' => 'unlimited',
'name' => 'Unlimited',
'workspace_type' => 'personal',
'stripe_price' => null,
'amount' => 0,
'seat_limit' => 1,
'max_folders' => null,
'max_folder_depth' => null,
'max_notes_per_folder' => null,
'note_chars' => null,
'sort_order' => 4,
],
];
foreach ($plans as $plan) {
DB::table('plans')->insert($plan + [
'interval' => 'month',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('plans');
}
};
@@ -0,0 +1,34 @@
<?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) {
// Nullable while the backfill migration assigns every existing
// workspace a plan; new workspaces are given one when created.
$table->foreignId('plan_id')
->nullable()
->after('lifetime_access')
->constrained()
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('organizations', function (Blueprint $table) {
$table->dropConstrainedForeignId('plan_id');
});
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* A null notes limit means the user has no per-user override and the limit
* comes from their workspace's plan instead.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('notes_limit')->nullable()->default(null)->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
DB::table('users')->whereNull('notes_limit')->update(['notes_limit' => 1000]);
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('notes_limit')->nullable(false)->default(1000)->change();
});
}
};
@@ -0,0 +1,72 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
*
* Give every workspace that predates plans one, so that entitlement and
* limits can be read from a plan instead of the legacy lifetime flag and
* subscription rows:
*
* - Grandfathered accounts stay entitled on the unlimited plan.
* - Existing subscribers move to the plan their Stripe price maps to.
* - Everyone else starts on the free plan.
*
* Idempotent: workspaces that already have a plan are left alone.
*/
public function up(): void
{
$unlimited = $this->planId('unlimited');
$personal = $this->planId('personal');
$free = $this->planId('free');
if ($unlimited === null || $personal === null || $free === null) {
return;
}
DB::table('organizations')
->where('lifetime_access', true)
->whereNull('plan_id')
->update(['plan_id' => $unlimited]);
$proPrice = config('plans.plans.pro.price');
if (is_string($proPrice) && $proPrice !== '') {
$subscribed = DB::table('subscriptions')
->where('stripe_price', $proPrice)
->distinct()
->pluck('organization_id');
DB::table('organizations')
->whereNull('plan_id')
->whereIn('id', $subscribed)
->update(['plan_id' => $personal]);
}
DB::table('organizations')
->whereNull('plan_id')
->update(['plan_id' => $free]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
DB::table('organizations')->update(['plan_id' => null]);
}
/**
* Get the id of the plan with the given key, if it exists.
*/
private function planId(string $key): ?int
{
$id = DB::table('plans')->where('key', $key)->value('id');
return $id === null ? null : (int) $id;
}
};
+117
View File
@@ -0,0 +1,117 @@
# Multi-User Access — Implementation Phases
Plan of record for adding multi-user access (workspaces, folder sharing, invitations)
to mytodos. Tech: Laravel 13 / PHP 8.4 / MySQL / Livewire 4 SFC pages / Pest / Flux UI (free).
**Status:** Phases 1–3 complete and green (303 tests, 714 assertions). Phase 4 pending.
---
## Access model (settled decisions)
- Roles: `admin > editor > marker > viewer` (additive).
- Effective folder role = max of:
- creator → admin,
- explicit `folder_user` share,
- inherited ancestor shares,
- workspace default: owner/admin → admin, member → viewer.
- Folder visibility: `private` / `workspace`. Defaults: personal → private, family/org → workspace.
- Explicit shares cascade down the subtree. A `private` folder drops out of inherited
workspace access (workspace-wide grants flow only through workspace-visibility folders).
- No deny semantics.
- Todos have no ACL — they inherit their folder's access and `organization_id`.
`todos.user_id` stays "created by".
- Page scope: folders in the user's active workspace (`users.current_organization_id`) the
user can access, plus folders explicitly shared with them from any workspace.
Workspace-membership folders in non-active workspaces are NOT shown on pages.
- `Folder::scopeVisibleTo(Builder, User|int $user, ?int $workspaceId = null)` and
`Todo::scopeVisibleTo(...)`. `null` workspaceId keeps broad behavior (model tests rely on it);
pages pass `activeWorkspaceId(): int`.
- `organization_id` is NOT NULL on `folders` and `todos`.
---
## Phase 1 — Foundations ✅
- Migrations `2026_10_10_214840`–`214847`: workspaces (`organizations`), `organization_user`
pivot (role), `folder_user` pivot (role, invited_by), `invitations`, plus `organization_id`
on `folders`/`todos`, `current_organization_id` on `users`.
- Models: `Organization`, `Invitation`; relations on `User`, `Folder`, `Todo`.
- Enums: `OrganizationRole`, `FolderRole`, `FolderVisibility` (each with `label()`).
- Policies: `FolderPolicy` (`manageShares`), `OrganizationPolicy` (`manageMembers`),
`InvitationPolicy` (`create`/`delete`), `TodoPolicy` (auto-discovered).
- Model scopes/helpers: `Folder::scopeVisibleTo` / `treeForVisibleTo` / `flattenTree` /
creating hook; `Todo::scopeVisibleTo` / `nextPositionFor`.
- Factories: `OrganizationFactory` (`personal`/`family`/`withMember`),
`FolderFactory` (`inOrganization`/`sharedWithWorkspace`/`private`/`childOf`),
`InvitationFactory` (`forFolder`/`forOrganization`/`accepted`/`expired`),
`UserFactory` (`unsubscribed`).
- Seeders pass `organization_id` explicitly.
## Phase 2 — Access scoping in pages ✅
- All three pages (folders, todo list, dashboard) use `visibleFolder` / `folderForAction` /
`activeWorkspaceId()` and authorize with `can()` / `@can`.
- Folder workspace label in the UI.
- Tests: `tests/Feature/SharedAccessPagesTest.php` plus model-level coverage.
## Phase 3 — Sharing & invitations ✅
- `Invitation` model: `EXPIRY_DAYS = 14`; `booted()` creating hook (token `Str::random(64)`,
`expires_at = Carbon::now()->addDays(14)`); `scopePending`; `isForFolder`/`isForWorkspace`;
`folderRole`/`organizationRole`; `roleLabel`; `inviterName`/`inviteableName`; `accept(User)`.
- `Folder::invitations()` MorphMany; `treeForVisibleTo` adds `withCount('shares')` (`shares_count`).
- Mail: `InvitationMail` + `resources/views/mail/invitation.blade.php`. Sent synchronously
(`Mail::to($email)->send(...)`); mail default driver `log`, `QUEUE_CONNECTION=database`.
Invitations upserted on (`inviteable_type`, `inviteable_id`, `email`) with fresh token/expiry.
- Accept page `resources/views/pages/invitations/⚡accept.blade.php`, route
`invitations/{invitation:token}` name `invitations.accept` (auth-only). Seat-limit check;
redirects to `dashboard`.
- Folders page share modal (gated `manageShares`): visibility select (hidden + server-guarded
for personal workspaces), collaborator list with role select + remove, invite-by-email +
role, pending invitations + revoke.
- Members page `resources/views/pages/workspace/⚡members.blade.php`, route `members` name
`members` (subscribed). Seat usage, role change, remove (blocks self + owner; reassigns
removed user to a personal workspace), invite (seat-limit aware), revoke.
- Nav: "Members" item in `resources/views/layouts/app/sidebar.blade.php` and `header.blade.php`.
- Tests: `InvitationTest`, `InvitationAcceptPageTest`, `FolderSharingTest`,
`WorkspaceMembersTest` (helpers `familyWorkspaceFor`, `membersWorkspaceFor`).
## Phase 4 — Workspace creation & switching + billing polish ⏳
Planned, not started. Candidate work:
- Workspace creation flow (create personal/family/organization workspace; ownership).
- Active-workspace switching UI (updates `users.current_organization_id`) in sidebar/header.
- Workspace settings (rename, members already on the members page).
- Billing polish: ensure plan/seat limits and upgrade prompts align with workspace type
(`config/workspaces.php` seat limits: personal=1, family=6, organization=null;
`config/plans.php`: `subscription_type='default'`, `trial_days=14`, plan `pro`).
- Additional migrations are allowed in Phase 4; Phases 1–3 migrations are frozen.
---
## Verification
- `php artisan test` → 303 passed, 714 assertions.
- `vendor/bin/pint --dirty --format agent` (Pint formats `.blade.php` too).
- `vendor/bin/phpstan analyse --memory-limit=1G` (Larastan, level 7). Note: the default
`composer types:check` crashes at the 128M memory limit — pass `--memory-limit=1G`.
17 pre-existing errors remain in unrelated files (console seeders, `Todo`, legacy `Folder`
helpers, policies). All Phase 1–3 feature files are clean.
## Conventions & gotchas
- `#[Fillable]`/`#[Hidden]` attributes; `scopeXxx()` naming; enums with `label()`.
- Create files via `php artisan make:* --no-interaction`.
- Livewire `Component` base has no `AuthorizesRequests`; pages use
`abort_unless(auth()->user()->can(...), 403)`; blade uses `@can`.
- **Blaze compiler bug:** Blade directives as attributes on a Flux component tag
(`@selected()`/`@checked()` on `<flux:select.option>`) are mangled into a `ParseError`.
Use `wire:model` (array dot paths) instead. Native `<input @checked>` is fine.
- Livewire test harness renders `HttpException`/`AuthorizationException` into responses
(`assertStatus(403)`); `ModelNotFoundException` propagates. `#[Locked]` props can't be `set()`.
- Livewire `->set()` fires `updated<Prop>` hooks (used with `memberRoles.{id}`,
`collaboratorRoles.{id}`).
- Guest invites: accept page behind `auth`; unsubscribed users bounce to pricing via
`subscribed`/`EnsureSubscribed`.
+12 -5
View File
@@ -4,20 +4,24 @@
@include('partials.head')
</head>
<body class="min-h-screen bg-white dark:bg-zinc-800">
<flux:sidebar sticky collapsible="mobile" class="border-e border-zinc-200 bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-900">
<flux:sidebar.header>
<x-app-logo :sidebar="true" href="{{ route('dashboard') }}" wire:navigate />
<flux:sidebar sticky collapsible class="border-e border-zinc-200 bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-900">
<flux:sidebar.header class="in-data-flux-sidebar-collapsed-desktop:justify-center">
<x-app-logo :sidebar="true" href="{{ route('dashboard') }}" wire:navigate class="in-data-flux-sidebar-collapsed-desktop:hidden!" />
<flux:sidebar.collapse class="lg:hidden" />
<flux:sidebar.toggle class="max-lg:hidden" icon="bars-2" />
</flux:sidebar.header>
<flux:sidebar.nav>
<flux:sidebar.group :heading="__('Platform')" class="grid">
<flux:sidebar.group :heading="__('Platform')" class="grid in-data-flux-sidebar-collapsed-desktop:flex!">
<flux:sidebar.item icon="home" :href="route('dashboard')" :current="request()->routeIs('dashboard')" wire:navigate>
{{ __('Dashboard') }}
</flux:sidebar.item>
<flux:sidebar.item icon="check-circle" :href="route('todos')" :current="request()->routeIs('todos')" wire:navigate>
{{ __('Todos') }}
</flux:sidebar.item>
<flux:sidebar.item icon="view-columns" :href="route('kanban')" :current="request()->routeIs('kanban')" wire:navigate>
{{ __('Kanban') }}
</flux:sidebar.item>
<flux:sidebar.item icon="folder" :href="route('folders')" :current="request()->routeIs('folders')" wire:navigate>
{{ __('Folders') }}
</flux:sidebar.item>
@@ -27,13 +31,16 @@
</flux:sidebar.group>
@if (auth()->user()->isSiteAdmin())
<flux:sidebar.group :heading="__('Site admin')" class="grid">
<flux:sidebar.group :heading="__('Site admin')" class="grid in-data-flux-sidebar-collapsed-desktop:flex!">
<flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate>
{{ __('Notes limits') }}
</flux:sidebar.item>
<flux:sidebar.item icon="currency-dollar" :href="route('admin.plan-pricing')" :current="request()->routeIs('admin.plan-pricing')" wire:navigate>
{{ __('Plan pricing') }}
</flux:sidebar.item>
<flux:sidebar.item icon="clock" :href="route('admin.lifetime-access')" :current="request()->routeIs('admin.lifetime-access')" wire:navigate>
{{ __('Lifetime access') }}
</flux:sidebar.item>
</flux:sidebar.group>
@endif
</flux:sidebar.nav>
@@ -0,0 +1,152 @@
<?php
use App\Models\User;
use Flux\Flux;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;
new #[Title('Lifetime access')] class extends Component
{
use WithPagination;
private const PER_PAGE = 10;
public function mount(): void
{
Gate::authorize('accessAdmin');
}
public string $search = '';
public function updatedSearch(): void
{
$this->resetPage();
}
/**
* Get the users whose lifetime access status can be toggled, eager-loading
* their current organization so we can show and flip its lifetime access
* flag without extra queries.
*
* @return LengthAwarePaginator<User>
*/
#[Computed]
public function users(): LengthAwarePaginator
{
return $this->filteredUserQuery()
->with('currentOrganization')
->orderBy('name')
->paginate(self::PER_PAGE);
}
/**
* @return Builder<User>
*/
private function filteredUserQuery(): Builder
{
return User::query()
->when(
$this->search !== '',
fn (Builder $query) => $query->where(fn (Builder $query) => $query
->where('name', 'like', '%'.$this->search.'%')
->orWhere('email', 'like', '%'.$this->search.'%'))
);
}
/**
* Flip the lifetime access flag on the given user's current organization.
* Every user has a personal organization, so this is the organization that
* controls whether they can use the app without a subscription.
*/
public function toggleLifetimeAccess(int $userId): void
{
Gate::authorize('accessAdmin');
$user = User::query()->findOrFail($userId);
$organization = $user->currentOrganization;
if ($organization === null) {
Flux::toast(variant: 'danger', text: __('This user has no organization.'));
return;
}
$organization->update(['lifetime_access' => ! $organization->lifetime_access]);
Flux::toast(
variant: 'success',
text: $organization->lifetime_access
? __('Lifetime access enabled for :name.', ['name' => $user->name])
: __('Lifetime access disabled for :name.', ['name' => $user->name]),
);
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div>
<flux:heading size="xl">{{ __('Lifetime access') }}</flux:heading>
<flux:text class="mt-1">{{ __('Grant or revoke perpetual access so users can use the app without a subscription.') }}</flux:text>
</div>
<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="lifetime-access-search-input"
/>
<flux:card>
<flux:table :paginate="$this->users">
<flux:table.columns>
<flux:table.column>{{ __('Name') }}</flux:table.column>
<flux:table.column>{{ __('Email') }}</flux:table.column>
<flux:table.column width="5rem">{{ __('Lifetime access') }}</flux:table.column>
<flux:table.column align="end" width="5rem">{{ __('Actions') }}</flux:table.column>
</flux:table.columns>
<flux:table.rows>
@forelse ($this->users as $user)
<?php
$organization = $user->currentOrganization;
$hasLifetime = $organization?->lifetime_access === true;
?>
<flux:table.row :key="$user->id" data-test="lifetime-access-user-row-{{ $user->id }}">
<flux:table.cell>{{ $user->name }}</flux:table.cell>
<flux:table.cell class="text-zinc-500">{{ $user->email }}</flux:table.cell>
<flux:table.cell data-test="lifetime-access-status-{{ $user->id }}">
@if ($hasLifetime)
<flux:badge size="sm" color="green">{{ __('Lifetime') }}</flux:badge>
@else
<flux:badge size="sm" color="zinc">{{ __('None') }}</flux:badge>
@endif
</flux:table.cell>
<flux:table.cell class="py-0">
<flux:button
size="sm"
variant="{{ $hasLifetime ? 'danger' : 'primary' }}"
icon="{{ $hasLifetime ? 'x-mark' : 'check' }}"
:title="$hasLifetime ? __('Disable lifetime access') : __('Enable lifetime access')"
wire:click="toggleLifetimeAccess({{ $user->id }})"
data-test="toggle-lifetime-access-{{ $user->id }}"
/>
</flux:table.cell>
</flux:table.row>
@empty
<flux:table.row>
<flux:table.cell colspan="4" 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>
</flux:card>
</div>
+27 -11
View File
@@ -1,5 +1,6 @@
<?php
use App\Concerns\SortsTodos;
use App\Models\Folder;
use App\Models\Todo;
use App\TodoStatus;
@@ -17,6 +18,7 @@ use Livewire\WithPagination;
new #[Title('Dashboard')] class extends Component
{
use SortsTodos;
use WithPagination;
private const PER_PAGE = 10;
@@ -77,6 +79,11 @@ new #[Title('Dashboard')] class extends Component
$this->resetPage();
}
protected function sortChanged(): void
{
$this->resetPage();
}
public function openCreateForm(?int $folderId = null): void
{
$this->reset('editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
@@ -259,10 +266,9 @@ new #[Title('Dashboard')] class extends Component
#[Computed]
public function todos(): LengthAwarePaginator
{
return $this->filteredTodoQuery()
->with('folder.parent')
->priority()
->paginate(self::PER_PAGE);
return $this->applyTodoSort(
$this->filteredTodoQuery()->with('folder.parent')
)->paginate(self::PER_PAGE);
}
#[Computed]
@@ -273,6 +279,10 @@ new #[Title('Dashboard')] class extends Component
public function moveTodo(int $todoId, string $direction): void
{
if ($this->hasActiveSort()) {
return;
}
$this->todoForAction($todoId, 'update');
$ids = $this->orderedTodoIds;
@@ -293,6 +303,10 @@ new #[Title('Dashboard')] class extends Component
public function handleSort(int $todoId, int $position): void
{
if ($this->hasActiveSort()) {
return;
}
$this->todoForAction($todoId, 'update');
$offset = ($this->todos->currentPage() - 1) * self::PER_PAGE;
@@ -518,12 +532,12 @@ new #[Title('Dashboard')] class extends Component
<flux:table.columns>
<flux:table.column width="3rem"></flux:table.column>
<flux:table.column width="3rem">{{ __('Done') }}</flux:table.column>
<flux:table.column>{{ __('Description') }}</flux:table.column>
<flux:table.column>{{ __('Status') }}</flux:table.column>
<flux:table.column>{{ __('Folder') }}</flux:table.column>
<flux:table.column>{{ __('Due') }}</flux:table.column>
<flux:table.column>{{ __('Created') }}</flux:table.column>
<flux:table.column>{{ __('Completed') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'description'" :direction="$sortDirection" wire:click="sort('description')">{{ __('Description') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'status'" :direction="$sortDirection" wire:click="sort('status')">{{ __('Status') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'folder'" :direction="$sortDirection" wire:click="sort('folder')">{{ __('Folder') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'due_date'" :direction="$sortDirection" wire:click="sort('due_date')">{{ __('Due') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'created_at'" :direction="$sortDirection" wire:click="sort('created_at')">{{ __('Created') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'completed_at'" :direction="$sortDirection" wire:click="sort('completed_at')">{{ __('Completed') }}</flux:table.column>
<flux:table.column align="end" width="10rem">{{ __('Actions') }}</flux:table.column>
</flux:table.columns>
@@ -532,7 +546,7 @@ new #[Title('Dashboard')] class extends Component
<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">
@can('update', $todo)
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<div wire:sort:handle class="{{ $sortBy === null ? 'inline-flex cursor-grab' : 'hidden' }}" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" />
</div>
@endcan
@@ -607,6 +621,7 @@ new #[Title('Dashboard')] class extends Component
<flux:table.cell class="py-0">
<div class="flex justify-end gap-1">
@can('update', $todo)
@if ($sortBy === null)
@if ($todo->id !== ($this->orderedTodoIds[0] ?? null))
<flux:button
size="sm"
@@ -628,6 +643,7 @@ new #[Title('Dashboard')] class extends Component
data-test="move-todo-down-{{ $todo->id }}"
/>
@endif
@endif
<flux:button
size="sm"
+661
View File
@@ -0,0 +1,661 @@
<?php
use App\Models\Folder;
use App\Models\Todo;
use App\TodoStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Kanban')] class extends Component
{
#[Locked]
public ?int $editingTodoId = null;
public string $search = '';
public ?int $folderId = null;
public bool $showTodoForm = false;
public string $description = '';
public string $todoStatus = 'open';
public ?string $dueDate = null;
public string $notes = '';
public ?int $formFolderId = null;
#[Locked]
public ?int $confirmingTodoDelete = null;
public function mount(): void
{
$folderId = request()->query('folder');
if ($folderId === null || $folderId === '') {
return;
}
$folderId = (int) $folderId;
if (Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($folderId)->exists()) {
$this->folderId = $folderId;
}
}
public function updatedSearch(): void
{
unset($this->columns);
}
public function updatedFolderId(): void
{
$this->folderId = $this->folderId === null || $this->folderId === '' ? null : (int) $this->folderId;
unset($this->columns, $this->filterFolderScope);
}
public function openCreateForm(?string $status = null): void
{
$this->reset('editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
$this->resetErrorBag();
if ($status !== null && TodoStatus::tryFrom($status) !== null) {
$this->todoStatus = $status;
}
if ($this->folderId !== null) {
$node = $this->folderTree->first(fn (array $node): bool => $node['folder']->id === $this->folderId);
if ($node !== null && auth()->user()->can('create', [Todo::class, $node['folder']])) {
$this->formFolderId = $this->folderId;
}
}
$this->showTodoForm = true;
}
public function openEditForm(int $todoId): void
{
$todo = $this->todoForAction($todoId, 'update');
$this->editingTodoId = $todo->id;
$this->description = $todo->description;
$this->todoStatus = $todo->status->value;
$this->dueDate = $todo->due_date?->format('Y-m-d') ?? '';
$this->notes = $todo->notes ?? '';
$this->formFolderId = $todo->folder_id;
$this->resetErrorBag();
$this->showTodoForm = true;
}
public function saveTodo(): void
{
$validated = $this->validate([
'description' => ['required', 'string', 'max:255'],
'todoStatus' => ['required', Rule::enum(TodoStatus::class)],
'dueDate' => ['nullable', 'date'],
'notes' => ['nullable', 'string', 'max:'.auth()->user()->notesLimit()],
'formFolderId' => ['required', 'integer', Rule::exists('folders', 'id')->whereIn(
'id',
Folder::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->select('folders.id')
)],
]);
$folder = Folder::query()
->visibleTo(auth()->id(), $this->activeWorkspaceId())
->findOrFail($validated['formFolderId']);
abort_unless(auth()->user()->can('create', [Todo::class, $folder]), 403);
$data = [
'folder_id' => $folder->id,
'description' => $validated['description'],
'status' => TodoStatus::from($validated['todoStatus']),
'due_date' => filled($validated['dueDate']) ? Carbon::parse($validated['dueDate']) : null,
'notes' => filled($validated['notes']) ? $validated['notes'] : null,
];
if ($this->editingTodoId !== null) {
$this->todoForAction($this->editingTodoId, 'update')->update($data);
} else {
Todo::create($data + [
'user_id' => auth()->id(),
'position' => Todo::nextPositionFor($folder),
]);
}
$this->reset('showTodoForm', 'editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
unset($this->columns);
}
public function toggleComplete(int $todoId): void
{
$todo = $this->todoForAction($todoId, 'markComplete');
$data = ['completed_at' => $todo->completed_at === null ? now() : null];
if ($todo->completed_at === null && in_array($todo->status, [TodoStatus::Open, TodoStatus::InProgress], true)) {
$data['status'] = TodoStatus::Completed;
} elseif ($todo->completed_at !== null && $todo->status === TodoStatus::Completed) {
$data['status'] = TodoStatus::Open;
}
$todo->update($data);
unset($this->columns);
}
public function confirmTodoDelete(int $todoId): void
{
$this->todoForAction($todoId, 'delete');
$this->confirmingTodoDelete = $todoId;
$this->modal('confirm-todo-delete')->show();
}
public function deleteTodo(): void
{
$this->todoForAction($this->confirmingTodoDelete ?? 0, 'delete')->delete();
$this->confirmingTodoDelete = null;
$this->modal('confirm-todo-delete')->close();
unset($this->columns);
}
public function resetFilters(): void
{
$this->reset('search', 'folderId');
unset($this->columns, $this->filterFolderScope);
}
public function moveTodo(int $todoId, int $position, string $columnId): void
{
if ($columnId !== 'completed' && TodoStatus::tryFrom($columnId) === null) {
return;
}
$todo = $this->todoForAction($todoId, 'update');
if ($columnId === 'completed') {
$data = ['completed_at' => $todo->completed_at ?? now()];
if ($todo->completed_at === null && in_array($todo->status, [TodoStatus::Open, TodoStatus::InProgress], true)) {
$data['status'] = TodoStatus::Completed;
}
$todo->update($data);
} else {
$todo->update([
'status' => TodoStatus::from($columnId),
'completed_at' => null,
]);
}
$this->reorderColumn($todo->id, $position, $columnId);
}
/**
* Move a todo to the given index of a board column. The reordered todos are
* written back into the slots they already occupy in the user's full
* priority order, so reordering under an active filter permutes the visible
* todos without renumbering them from zero and colliding with the todos the
* filter hides.
*/
private function reorderColumn(int $todoId, int $newIndex, string $columnId): void
{
$visibleIds = $this->columnTodoIds($columnId);
$currentIndex = array_search($todoId, $visibleIds, true);
if ($currentIndex === false) {
return;
}
$newIndex = max(0, min($newIndex, count($visibleIds) - 1));
if ($newIndex === $currentIndex) {
unset($this->columns);
return;
}
$visibleOrder = $visibleIds;
unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId);
$ids = Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->priority()->pluck('id')->all();
$slots = array_keys(array_intersect($ids, $visibleIds));
foreach ($slots as $visibleSlot => $slot) {
$ids[$slot] = $visibleOrder[$visibleSlot];
}
foreach ($ids as $position => $id) {
Todo::query()->visibleTo(auth()->id(), $this->activeWorkspaceId())->whereKey($id)->update(['position' => $position]);
}
unset($this->columns);
}
/**
* @return list<int>
*/
private function columnTodoIds(string $columnId): array
{
$query = $this->filteredTodoQuery()->priority();
if ($columnId === 'completed') {
$query->where(function (Builder $query): void {
$query->whereNotNull('completed_at')->orWhere('status', TodoStatus::Completed->value);
});
} else {
$query->where('status', $columnId)->whereNull('completed_at');
}
return $query->pluck('id')->all();
}
/**
* @return Builder<Todo>
*/
private function filteredTodoQuery(): Builder
{
return Todo::query()
->visibleTo(auth()->id(), $this->activeWorkspaceId())
->when(
$this->search !== '',
fn (Builder $query) => $query->where('description', 'like', '%'.$this->search.'%')
)
->when(
$this->folderId !== null,
fn (Builder $query) => $query->whereIn('folder_id', $this->filterFolderScope)
);
}
private function descendantIds(int $folderId): array
{
$ids = [$folderId];
foreach ($this->folderTree->where('folder.parent_id', $folderId)->values() as $child) {
$ids = [...$ids, ...$this->descendantIds($child['folder']->id)];
}
return $ids;
}
private function todoForAction(int $todoId, string $ability): Todo
{
$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;
}
#[Computed]
public function folderTree(): Collection
{
return Folder::treeForVisibleTo(auth()->id(), $this->activeWorkspaceId());
}
#[Computed]
public function filterFolderScope(): array
{
if ($this->folderId === null) {
return [];
}
return $this->descendantIds($this->folderId);
}
#[Computed]
public function hasActiveFilters(): bool
{
return $this->search !== '' || $this->folderId !== null;
}
#[Computed]
public function canCreateTodos(): bool
{
return $this->folderTree->contains(
fn (array $node): bool => auth()->user()->can('create', [Todo::class, $node['folder']])
);
}
/**
* @return list<array{id: string, label: string, color: string, todos: Collection<int, Todo>}>
*/
#[Computed]
public function columns(): array
{
$todos = $this->filteredTodoQuery()
->with('folder.parent')
->priority()
->get();
$columns = collect([
TodoStatus::Open,
TodoStatus::InProgress,
TodoStatus::OnHold,
TodoStatus::Blocked,
TodoStatus::Cancelled,
TodoStatus::Deferred,
])->map(fn (TodoStatus $status): array => [
'id' => $status->value,
'label' => $status->label(),
'color' => $status->badgeColor(),
'todos' => $todos
->filter(fn (Todo $todo): bool => $todo->status === $status && $todo->completed_at === null)
->values(),
]);
$columns->push([
'id' => 'completed',
'label' => TodoStatus::Completed->label(),
'color' => TodoStatus::Completed->badgeColor(),
'todos' => $todos
->filter(fn (Todo $todo): bool => $todo->completed_at !== null || $todo->status === TodoStatus::Completed)
->values(),
]);
return $columns->all();
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<div>
<flux:heading size="xl">{{ __('Kanban') }}</flux:heading>
<flux:text class="mt-1">{{ __('Drag todos between columns to update their status.') }}</flux:text>
</div>
<div class="flex flex-wrap items-center gap-2">
<flux:button variant="ghost" icon="list-bullet" :href="route('todos')" wire:navigate>
{{ __('List view') }}
</flux:button>
@if ($this->canCreateTodos)
<flux:button
variant="primary"
wire:click="openCreateForm"
data-test="add-todo-button"
>
{{ __('New Todo') }}
</flux:button>
@endif
</div>
</div>
@if (! $this->canCreateTodos)
<flux:callout variant="warning" icon="folder">
<x-slot name="text">
{{ __('Create a folder you can add todos to before using the board.') }}
</x-slot>
<x-slot name="actions">
<flux:button size="sm" :href="route('folders')" wire:navigate variant="primary">
{{ __('Manage folders') }}
</flux:button>
</x-slot>
</flux:callout>
@endif
<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 todos…') }}"
class="w-full sm:w-64"
data-test="search-input"
/>
<flux:select size="sm" wire:model.live="folderId" class="w-full sm:w-56" data-test="folder-filter">
<flux:select.option value="">{{ __('All folders') }}</flux:select.option>
@foreach ($this->folderTree as $node)
<flux:select.option :value="$node['folder']->id">{{ str_repeat('— ', $node['depth']) }}{{ $node['folder']->name }}</flux:select.option>
@endforeach
</flux:select>
@if ($this->hasActiveFilters)
<flux:button size="sm" variant="danger" icon="x-mark" wire:click="resetFilters" class="shrink-0">
{{ __('Clear') }}
</flux:button>
@endif
</div>
<div class="flex gap-4 overflow-x-auto pb-4" data-test="kanban-board">
@foreach ($this->columns as $column)
<section
wire:key="kanban-column-{{ $column['id'] }}"
class="flex w-72 shrink-0 flex-col gap-3 rounded-xl border border-zinc-200 bg-zinc-50/80 p-3 dark:border-zinc-700 dark:bg-zinc-900/60"
data-test="kanban-column-{{ $column['id'] }}"
>
<div class="flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<flux:badge size="sm" :color="$column['color']">{{ $column['label'] }}</flux:badge>
<span class="text-xs font-medium text-zinc-500" data-test="kanban-count-{{ $column['id'] }}">
{{ $column['todos']->count() }}
</span>
</div>
@if ($this->canCreateTodos)
<flux:button
size="sm"
variant="ghost"
icon="plus"
:title="__('Add todo to :status', ['status' => $column['label']])"
wire:click="openCreateForm('{{ $column['id'] }}')"
data-test="kanban-add-{{ $column['id'] }}"
/>
@endif
</div>
<div
wire:sort="moveTodo"
wire:sort:group="kanban"
wire:sort:group-id="{{ $column['id'] }}"
class="flex min-h-24 flex-col gap-2"
data-test="kanban-list-{{ $column['id'] }}"
>
@forelse ($column['todos'] as $todo)
@php
$canUpdateTodo = auth()->user()->can('update', $todo);
$dueColor = $todo->completed_at !== null
? 'zinc'
: ($todo->due_date?->isPast() ? 'red' : ($todo->due_date?->isToday() ? 'amber' : 'zinc'));
@endphp
<div
wire:sort:item="{{ $todo->id }}"
@if (! $canUpdateTodo) wire:sort:ignore @endif
wire:key="kanban-card-{{ $todo->id }}"
data-test="kanban-card-{{ $todo->id }}"
@class([
'group cursor-grab rounded-lg border border-zinc-200 bg-white p-3 shadow-xs transition hover:border-zinc-300 active:cursor-grabbing dark:border-zinc-700 dark:bg-zinc-800 dark:hover:border-zinc-600',
'opacity-80' => $todo->completed_at !== null,
])
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<p @class([
'text-sm font-medium text-zinc-900 dark:text-zinc-100',
'line-through text-zinc-400 dark:text-zinc-500' => $todo->completed_at !== null,
])>
{{ $todo->description }}
</p>
@if ($todo->notes)
<flux:text size="sm" class="mt-1 line-clamp-2 text-zinc-500">{{ $todo->notes }}</flux:text>
@endif
</div>
@if ($canUpdateTodo)
<div wire:sort:ignore class="shrink-0">
<flux:dropdown position="bottom" align="end">
<flux:button
size="sm"
variant="ghost"
icon="ellipsis-horizontal"
:title="__('Todo actions')"
data-test="kanban-actions-{{ $todo->id }}"
/>
<flux:menu>
<flux:menu.item icon="pencil-square" wire:click="openEditForm({{ $todo->id }})">
{{ __('Edit') }}
</flux:menu.item>
<flux:menu.item icon="trash" variant="danger" wire:click="confirmTodoDelete({{ $todo->id }})">
{{ __('Delete') }}
</flux:menu.item>
</flux:menu>
</flux:dropdown>
</div>
@endif
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
@can('markComplete', $todo)
<div wire:sort:ignore>
<flux:checkbox
:checked="$todo->completed_at !== null"
:title="$todo->completed_at ? __('Mark as not done') : __('Mark as done')"
wire:click="toggleComplete({{ $todo->id }})"
data-test="kanban-toggle-complete-{{ $todo->id }}"
/>
</div>
@endcan
<div class="flex min-w-0 items-center gap-1.5 text-xs text-zinc-500">
<x-folder-dot :color="$todo->folder?->color" />
<span class="truncate">{{ $todo->folder?->parent?->name }}@if ($todo->folder?->parent) / @endif{{ $todo->folder?->name }}</span>
</div>
@if ($column['id'] === 'completed' && $todo->status !== TodoStatus::Completed)
<flux:badge size="sm" :color="$todo->status->badgeColor()">
{{ $todo->status->label() }}
</flux:badge>
@endif
@if ($todo->due_date)
<flux:badge size="sm" :color="$dueColor">
{{ $todo->due_date->isToday() ? __('Today') : $todo->due_date->format('M j') }}
</flux:badge>
@endif
</div>
</div>
@empty
<div
wire:sort:ignore
class="flex min-h-24 items-center justify-center rounded-lg border border-dashed border-zinc-300 text-xs text-zinc-400 dark:border-zinc-700"
>
{{ __('No todos') }}
</div>
@endforelse
</div>
</section>
@endforeach
</div>
<flux:modal wire:model.self="showTodoForm" class="md:w-xl">
<form wire:submit="saveTodo" class="space-y-6">
<div>
<flux:heading size="lg">{{ $editingTodoId === null ? __('New todo') : __('Edit todo') }}</flux:heading>
<flux:text class="mt-2">{{ __('Add a task with a description and folder. A due date is optional.') }}</flux:text>
</div>
<flux:field>
<flux:label>{{ __('Description') }}</flux:label>
<flux:input
wire:model="description"
type="text"
autofocus
placeholder="{{ __('What needs to be done?') }}"
data-test="description-input"
/>
<flux:error name="description" />
</flux:field>
<flux:field>
<flux:label>{{ __('Status') }}</flux:label>
<flux:select wire:model="todoStatus" data-test="status-select">
@foreach (TodoStatus::cases() as $status)
<flux:select.option :value="$status->value">{{ $status->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="todoStatus" />
</flux:field>
<flux:field>
<flux:label>{{ __('Due date') }}</flux:label>
<flux:input wire:model="dueDate" type="date" data-test="due-date-input" />
<flux:error name="dueDate" />
</flux:field>
<flux:field>
<flux:label>{{ __('Notes') }}</flux:label>
<flux:textarea
wire:model="notes"
rows="3"
placeholder="{{ __('Add any extra details…') }}"
data-test="notes-input"
/>
<flux:error name="notes" />
</flux:field>
<flux:field>
<flux:label>{{ __('Folder') }}</flux:label>
<flux:select wire:model="formFolderId" data-test="folder-select">
<flux:select.option value="">{{ __('Select a folder…') }}</flux:select.option>
@foreach ($this->folderTree as $node)
<flux:select.option :value="$node['folder']->id">{{ str_repeat('— ', $node['depth']) }}{{ $node['folder']->name }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="formFolderId" />
</flux:field>
<div class="flex justify-end gap-3">
<flux:modal.close>
<flux:button variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button type="submit" variant="primary">{{ __('Save todo') }}</flux:button>
</div>
</form>
</flux:modal>
<flux:modal name="confirm-todo-delete" class="md:w-lg">
<div class="space-y-6">
<div>
<flux:heading size="lg">{{ __('Delete todo?') }}</flux:heading>
<flux:text class="mt-2">{{ __('This todo will be permanently deleted. This action cannot be undone.') }}</flux:text>
</div>
<div class="flex justify-end gap-3">
<flux:modal.close>
<flux:button variant="ghost">{{ __('Cancel') }}</flux:button>
</flux:modal.close>
<flux:button variant="danger" wire:click="deleteTodo">{{ __('Delete') }}</flux:button>
</div>
</div>
</flux:modal>
</div>
+34 -10
View File
@@ -1,5 +1,6 @@
<?php
use App\Concerns\SortsTodos;
use App\Models\Folder;
use App\Models\Todo;
use App\TodoStatus;
@@ -14,6 +15,8 @@ use Livewire\Component;
new #[Title('Todos')] class extends Component
{
use SortsTodos;
private const PER_PAGE = 50;
#[Locked]
@@ -74,6 +77,11 @@ new #[Title('Todos')] class extends Component
$this->limit = self::PER_PAGE;
}
protected function sortChanged(): void
{
$this->limit = self::PER_PAGE;
}
public function openCreateForm(?int $folderId = null): void
{
$this->reset('editingTodoId', 'description', 'todoStatus', 'dueDate', 'notes', 'formFolderId');
@@ -243,15 +251,19 @@ new #[Title('Todos')] class extends Component
#[Computed]
public function todos(): Collection
{
return $this->filteredTodoQuery()
->with('folder.parent')
->priority()
return $this->applyTodoSort(
$this->filteredTodoQuery()->with('folder.parent')
)
->limit($this->limit)
->get();
}
public function moveTodo(int $todoId, string $direction): void
{
if ($this->hasActiveSort()) {
return;
}
$this->todoForAction($todoId, 'update');
$ids = $this->orderedTodoIds;
@@ -272,6 +284,10 @@ new #[Title('Todos')] class extends Component
public function handleSort(int $todoId, int $position): void
{
if ($this->hasActiveSort()) {
return;
}
$this->todoForAction($todoId, 'update');
$this->reorderTodo($todoId, $position);
@@ -380,6 +396,11 @@ new #[Title('Todos')] class extends Component
<flux:text class="mt-1">Browse and reorder every todo.</flux:text>
</div>
<div class="flex flex-wrap items-center gap-2">
<flux:button variant="ghost" icon="view-columns" :href="route('kanban')" wire:navigate>
{{ __('Board view') }}
</flux:button>
<flux:button
variant="primary"
wire:click="openCreateForm"
@@ -388,6 +409,7 @@ new #[Title('Todos')] class extends Component
{{ __('New Todo') }}
</flux:button>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
@foreach ($this->statusFilters as $value => $label)
@@ -432,12 +454,12 @@ new #[Title('Todos')] class extends Component
<flux:table.columns>
<flux:table.column width="3rem"></flux:table.column>
<flux:table.column width="3rem">{{ __('Done') }}</flux:table.column>
<flux:table.column>{{ __('Description') }}</flux:table.column>
<flux:table.column>{{ __('Status') }}</flux:table.column>
<flux:table.column>{{ __('Folder') }}</flux:table.column>
<flux:table.column>{{ __('Due') }}</flux:table.column>
<flux:table.column>{{ __('Created') }}</flux:table.column>
<flux:table.column>{{ __('Completed') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'description'" :direction="$sortDirection" wire:click="sort('description')">{{ __('Description') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'status'" :direction="$sortDirection" wire:click="sort('status')">{{ __('Status') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'folder'" :direction="$sortDirection" wire:click="sort('folder')">{{ __('Folder') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'due_date'" :direction="$sortDirection" wire:click="sort('due_date')">{{ __('Due') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'created_at'" :direction="$sortDirection" wire:click="sort('created_at')">{{ __('Created') }}</flux:table.column>
<flux:table.column sortable :sorted="$sortBy === 'completed_at'" :direction="$sortDirection" wire:click="sort('completed_at')">{{ __('Completed') }}</flux:table.column>
<flux:table.column align="end" width="10rem">{{ __('Actions') }}</flux:table.column>
</flux:table.columns>
@@ -446,7 +468,7 @@ new #[Title('Todos')] class extends Component
<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">
@can('update', $todo)
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<div wire:sort:handle class="{{ $sortBy === null ? 'inline-flex cursor-grab' : 'hidden' }}" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" />
</div>
@endcan
@@ -517,6 +539,7 @@ new #[Title('Todos')] class extends Component
<flux:table.cell class="py-0">
<div class="flex justify-end gap-1">
@can('update', $todo)
@if ($sortBy === null)
@if ($todo->id !== ($this->orderedTodoIds[0] ?? null))
<flux:button
size="sm"
@@ -538,6 +561,7 @@ new #[Title('Todos')] class extends Component
data-test="move-todo-down-{{ $todo->id }}"
/>
@endif
@endif
<flux:button
size="sm"
+2
View File
@@ -19,6 +19,7 @@ Route::middleware(['auth'])->group(function () {
Route::middleware(['auth', 'verified', 'subscribed'])->group(function () {
Route::livewire('dashboard', 'pages::dashboard')->name('dashboard');
Route::livewire('todos', 'pages::todos')->name('todos');
Route::livewire('kanban', 'pages::kanban')->name('kanban');
Route::livewire('folders', 'pages::folders')->name('folders');
Route::livewire('members', 'pages::workspace.members')->name('members');
@@ -27,6 +28,7 @@ Route::middleware(['auth', 'verified', 'subscribed'])->group(function () {
Route::middleware('admin')->group(function () {
Route::livewire('admin/notes-limits', 'pages::admin.notes-limits')->name('admin.notes-limits');
Route::livewire('admin/plan-pricing', 'pages::admin.plan-pricing')->name('admin.plan-pricing');
Route::livewire('admin/lifetime-access', 'pages::admin.lifetime-access')->name('admin.lifetime-access');
});
});
+158
View File
@@ -0,0 +1,158 @@
<?php
use App\Models\User;
use Livewire\Livewire;
test('guests are redirected from the lifetime access page', function () {
$this->get(route('admin.lifetime-access'))
->assertRedirect(route('login'));
});
test('non-admins cannot access the lifetime access page', function () {
$this->actingAs(User::factory()->create());
$this->get(route('admin.lifetime-access'))->assertForbidden();
});
test('workspace admins are not site admins and cannot access the lifetime access page', function () {
$workspaceAdmin = User::factory()->create();
$this->actingAs($workspaceAdmin);
$this->get(route('admin.lifetime-access'))->assertForbidden();
});
test('a non-admin cannot toggle lifetime access through a direct action call', function () {
$admin = User::factory()->asAdmin()->create();
$this->actingAs($admin);
$member = User::factory()->create();
$component = Livewire::test('pages::admin.lifetime-access');
$this->actingAs($member);
$component->call('toggleLifetimeAccess', $member->id)->assertForbidden();
expect($member->fresh()->currentOrganization->lifetime_access)->toBeFalse();
});
test('non-admins do not see the lifetime access navigation item', function () {
$user = User::factory()->create();
$this->actingAs($user);
$this->get(route('dashboard'))
->assertOk()
->assertDontSee('Lifetime access');
});
test('admins see the lifetime access navigation item', function () {
$user = User::factory()->asAdmin()->create();
$this->actingAs($user);
$this->get(route('dashboard'))
->assertOk()
->assertSee('Lifetime access');
});
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();
$this->actingAs($workspaceAdmin);
$this->get(route('dashboard'))
->assertOk()
->assertDontSee('Site admin');
});
test('admins can view the lifetime access page', function () {
$user = User::factory()->asAdmin()->create();
$this->actingAs($user);
$this->get(route('admin.lifetime-access'))->assertOk();
});
test('the lifetime access page lists users with their status', function () {
$admin = User::factory()->asAdmin()->create();
$this->actingAs($admin);
$lifetimeUser = User::factory()->create(['name' => 'Lifetime User']);
$lifetimeUser->currentOrganization->update(['lifetime_access' => true]);
$regularUser = User::factory()->create(['name' => 'Regular User']);
Livewire::test('pages::admin.lifetime-access')
->assertSee('Lifetime User')
->assertSee('Regular User')
->assertSee('Lifetime')
->assertSee('None');
});
test('admins can enable lifetime access for a user', function () {
$admin = User::factory()->asAdmin()->create();
$this->actingAs($admin);
$member = User::factory()->create(['name' => 'Member One']);
expect($member->fresh()->currentOrganization->lifetime_access)->toBeFalse();
Livewire::test('pages::admin.lifetime-access')
->call('toggleLifetimeAccess', $member->id)
->assertSet('showLimitForm', false);
expect($member->fresh()->currentOrganization->lifetime_access)->toBeTrue();
});
test('admins can disable lifetime access for a user', function () {
$admin = User::factory()->asAdmin()->create();
$this->actingAs($admin);
$member = User::factory()->create(['name' => 'Member Two']);
$member->currentOrganization->update(['lifetime_access' => true]);
expect($member->fresh()->currentOrganization->lifetime_access)->toBeTrue();
Livewire::test('pages::admin.lifetime-access')
->call('toggleLifetimeAccess', $member->id);
expect($member->fresh()->currentOrganization->lifetime_access)->toBeFalse();
});
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.lifetime-access')
->set('search', 'lovelace')
->assertSee('Ada Lovelace')
->assertDontSee('Alan Turing')
->set('search', 'searchable.test')
->assertSee('Grace Hopper')
->assertDontSee($match->name)
->assertDontSee($other->name);
});
test('the lifetime access list is paginated', function () {
$admin = User::factory()->asAdmin()->create();
$this->actingAs($admin);
User::factory()->count(12)->create();
$component = Livewire::test('pages::admin.lifetime-access');
expect($component->instance()->users->perPage())->toBe(10)
->and($component->instance()->users->total())->toBe(13);
});
+2 -2
View File
@@ -42,7 +42,7 @@ test('a non-admin cannot save a notes limit through a direct action call', funct
$component->set('notesLimitInput', '2500')->call('saveNotesLimit')->assertForbidden();
expect($member->fresh()->notes_limit)->toBe(1000);
expect($member->fresh()->notesLimit())->toBe(1000);
});
test('non-admins do not see the notes limits navigation item', function () {
@@ -128,7 +128,7 @@ test('a notes limit must be a valid positive number', function () {
->call('saveNotesLimit')
->assertHasErrors('notesLimitInput');
expect($member->fresh()->notes_limit)->toBe(1000);
expect($member->fresh()->notesLimit())->toBe(1000);
});
test('admins can search users by name or email', function () {
+2 -1
View File
@@ -12,7 +12,8 @@ test('base data includes a default admin user', function () {
expect($admin)->not->toBeNull()
->and($admin->name)->toBe('Administrator')
->and($admin->notes_limit)->toBe(1000);
->and($admin->notes_limit)->toBeNull()
->and($admin->notesLimit())->toBe(1000);
$this->assertTrue($admin->isSiteAdmin());
});
+87
View File
@@ -0,0 +1,87 @@
<?php
use App\Models\Organization;
use App\Models\Plan;
use App\Models\User;
use App\WorkspaceType;
use Laravel\Cashier\Subscription;
test('the default plans are seeded', function () {
expect(Plan::query()->orderBy('sort_order')->pluck('key')->all())
->toBe(['free', 'personal', 'family', 'organization', 'unlimited']);
});
test('a plan casts its workspace type and limits', function () {
$free = Plan::query()->where('key', 'free')->firstOrFail();
expect($free->workspace_type)->toBe(WorkspaceType::Personal)
->and($free->is_active)->toBeTrue()
->and($free->seat_limit)->toBe(1)
->and($free->max_folders)->toBe(3)
->and($free->max_folder_depth)->toBe(1)
->and($free->max_notes_per_folder)->toBe(50)
->and($free->note_chars)->toBe(1000);
});
test('the unlimited plan has no limits', function () {
$unlimited = Plan::query()->where('key', 'unlimited')->firstOrFail();
expect($unlimited->max_folders)->toBeNull()
->and($unlimited->max_folder_depth)->toBeNull()
->and($unlimited->max_notes_per_folder)->toBeNull()
->and($unlimited->note_chars)->toBeNull();
});
test('only the personal plan is purchasable by default', function () {
expect(Plan::query()->where('key', 'personal')->firstOrFail()->isPurchasable())->toBeTrue()
->and(Plan::query()->where('key', 'free')->firstOrFail()->isPurchasable())->toBeFalse()
->and(Plan::query()->where('key', 'unlimited')->firstOrFail()->isPurchasable())->toBeFalse();
});
test('a plan created through the factory can be given caps and a price', function () {
$plan = Plan::factory()->limited(2, 1, 10, 200)->purchasable('price_abc')->create();
expect($plan->max_folders)->toBe(2)
->and($plan->note_chars)->toBe(200)
->and($plan->isPurchasable())->toBeTrue()
->and($plan->stripe_price)->toBe('price_abc');
});
test('an organization belongs to a plan', function () {
$organization = Organization::factory()->withPlan('family')->create();
expect($organization->plan)->not->toBeNull()
->and($organization->plan->key)->toBe('family');
});
test('the factory user is given the unlimited plan', function () {
$user = User::factory()->create();
expect($user->currentOrganization()->first()->plan->key)->toBe('unlimited');
});
test('the factory user can be given a specific plan', function () {
$user = User::factory()->unsubscribed()->withFreePlan()->create();
expect($user->currentOrganization()->first()->plan->key)->toBe('free');
});
test('the backfill assigns a plan to every existing workspace', function () {
$legacy = Organization::factory()->personal()->withLifetimeAccess()->create();
$subscriber = Organization::factory()->personal()->create();
$plain = Organization::factory()->personal()->create();
Subscription::factory()->active()
->withPrice(config('plans.plans.pro.price'))
->create(['organization_id' => $subscriber->id]);
// Simulate a database that predates the backfill.
Organization::query()->update(['plan_id' => null]);
$migration = require database_path('migrations/2026_10_16_043630_backfill_organization_plans.php');
$migration->up();
expect($legacy->refresh()->plan->key)->toBe('unlimited')
->and($subscriber->refresh()->plan->key)->toBe('personal')
->and($plain->refresh()->plan->key)->toBe('free');
});
+34
View File
@@ -670,3 +670,37 @@ test('completed todos sort last regardless of their position', function () {
Livewire::test('pages::dashboard')
->assertSeeInOrder(['Pending task', 'Finished task']);
});
test('dashboard todos can be sorted by a column', function () {
$this->travelTo('2026-09-18 09:00:00');
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Later task',
'due_date' => today()->addDays(2),
'position' => 0,
]);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Sooner task',
'due_date' => today()->addDay(),
'position' => 1,
]);
Todo::factory()->recycle($user)->for($folder)->noDueDate()->create([
'description' => 'No due task',
'position' => 2,
]);
Livewire::test('pages::dashboard')
->assertSeeInOrder(['Later task', 'Sooner task', 'No due task'])
->call('sort', 'due_date')
->assertSet('sortBy', 'due_date')
->assertSet('sortDirection', 'asc')
->assertSeeInOrder(['Sooner task', 'Later task', 'No due task'])
->call('sort', 'due_date')
->assertSet('sortDirection', 'desc')
->assertSeeInOrder(['Later task', 'Sooner task', 'No due task']);
});
+309
View File
@@ -0,0 +1,309 @@
<?php
use App\Models\Folder;
use App\Models\Organization;
use App\Models\Todo;
use App\Models\User;
use App\OrganizationRole;
use App\TodoStatus;
use Livewire\Livewire;
test('guests are redirected to the login page', function () {
$response = $this->get(route('kanban'));
$response->assertRedirect(route('login'));
});
test('authenticated users can visit the kanban page', function () {
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->get(route('kanban'));
$response->assertOk();
});
test('the board groups todos into status columns', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Open task',
'status' => TodoStatus::Open,
'position' => 0,
]);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Progress task',
'status' => TodoStatus::InProgress,
'position' => 1,
]);
Todo::factory()->recycle($user)->for($folder)->completed()->create([
'description' => 'Completed on hold',
'status' => TodoStatus::OnHold,
'position' => 2,
]);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Completed status',
'status' => TodoStatus::Completed,
'position' => 3,
]);
Livewire::test('pages::kanban')
->assertSeeHtml('wire:sort="moveTodo"')
->assertSeeHtml('wire:sort:group="kanban"')
->assertSeeHtml('wire:sort:group-id="open"')
->assertSeeHtml('wire:sort:group-id="completed"')
->assertSeeHtmlInOrder([
'data-test="kanban-column-open"',
'Open task',
'data-test="kanban-column-in-progress"',
'Progress task',
'data-test="kanban-column-on-hold"',
'data-test="kanban-column-blocked"',
'data-test="kanban-column-cancelled"',
'data-test="kanban-column-deferred"',
'data-test="kanban-column-completed"',
'Completed status',
'Completed on hold',
]);
});
test('moving a todo to another status column updates its status', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$todo = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Move me',
'status' => TodoStatus::Open,
'position' => 0,
]);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Existing progress',
'status' => TodoStatus::InProgress,
'position' => 1,
]);
Livewire::test('pages::kanban')
->call('moveTodo', $todo->id, 1, 'in-progress')
->assertSeeHtmlInOrder([
'data-test="kanban-column-in-progress"',
'Existing progress',
'Move me',
]);
expect($todo->fresh()->status)->toBe(TodoStatus::InProgress);
expect($todo->fresh()->completed_at)->toBeNull();
expect(Todo::query()->where('status', TodoStatus::InProgress)->priority()->pluck('description')->all())
->toBe(['Existing progress', 'Move me']);
});
test('toggling complete moves a todo into and out of the completed column', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$todo = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Toggle me',
'status' => TodoStatus::Open,
'position' => 0,
]);
Livewire::test('pages::kanban')
->call('toggleComplete', $todo->id)
->assertSeeHtmlInOrder([
'data-test="kanban-column-completed"',
'Toggle me',
]);
expect($todo->fresh()->status)->toBe(TodoStatus::Completed);
expect($todo->fresh()->completed_at)->not->toBeNull();
Livewire::test('pages::kanban')
->call('toggleComplete', $todo->id)
->assertSeeHtmlInOrder([
'data-test="kanban-column-open"',
'Toggle me',
]);
expect($todo->fresh()->status)->toBe(TodoStatus::Open);
expect($todo->fresh()->completed_at)->toBeNull();
});
test('moving a todo to completed marks it complete without losing its workflow status', function () {
$this->travelTo('2026-09-18 09:00:00');
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$todo = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Finish me',
'status' => TodoStatus::Blocked,
'position' => 0,
]);
Livewire::test('pages::kanban')
->call('moveTodo', $todo->id, 0, 'completed')
->assertSeeHtmlInOrder([
'data-test="kanban-column-completed"',
'Finish me',
]);
expect($todo->fresh()->status)->toBe(TodoStatus::Blocked);
expect($todo->fresh()->completed_at)->not->toBeNull();
});
test('moving an open todo to completed also completes its status', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$todo = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Open task',
'status' => TodoStatus::Open,
'position' => 0,
]);
Livewire::test('pages::kanban')
->call('moveTodo', $todo->id, 0, 'completed');
expect($todo->fresh()->status)->toBe(TodoStatus::Completed);
expect($todo->fresh()->completed_at)->not->toBeNull();
});
test('moving a completed todo back to a status column reopens it', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$todo = Todo::factory()->recycle($user)->for($folder)->completed()->create([
'description' => 'Reopen me',
'status' => TodoStatus::OnHold,
'position' => 0,
]);
Livewire::test('pages::kanban')
->call('moveTodo', $todo->id, 0, 'on-hold')
->assertSeeHtmlInOrder([
'data-test="kanban-column-on-hold"',
'Reopen me',
]);
expect($todo->fresh()->status)->toBe(TodoStatus::OnHold);
expect($todo->fresh()->completed_at)->toBeNull();
});
test('reordering within a column keeps the order of other columns', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
$first = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'First open',
'status' => TodoStatus::Open,
'position' => 0,
]);
Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Second open',
'status' => TodoStatus::Open,
'position' => 1,
]);
$blocked = Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Blocked task',
'status' => TodoStatus::Blocked,
'position' => 2,
]);
Livewire::test('pages::kanban')
->call('moveTodo', $first->id, 1, 'open');
expect(Todo::query()->where('status', TodoStatus::Open)->priority()->pluck('description')->all())
->toBe(['Second open', 'First open']);
expect($blocked->fresh()->position)->toBe(2);
});
test('the board filters by search', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Review design']);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Review proposal']);
Livewire::test('pages::kanban')
->set('search', 'proposal')
->assertDontSee('Review design')
->assertSee('Review proposal');
});
test('adding a todo from a column preselects that status', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Livewire::test('pages::kanban')
->call('openCreateForm', 'blocked')
->assertSet('todoStatus', 'blocked')
->set('description', 'Blocked task')
->set('formFolderId', $folder->id)
->call('saveTodo')
->assertSet('showTodoForm', false)
->assertSeeHtmlInOrder([
'data-test="kanban-column-blocked"',
'Blocked task',
]);
$todo = Todo::where('description', 'Blocked task')->firstOrFail();
expect($todo->status)->toBe(TodoStatus::Blocked);
});
test('users do not see another user todos on the board', function () {
$owner = User::factory()->create();
$ownerFolder = Folder::factory()->for($owner)->create(['name' => 'Owner Folder']);
Todo::factory()->recycle($owner)->for($ownerFolder)->create(['description' => 'Owner secret']);
$intruder = User::factory()->create();
$this->actingAs($intruder);
Livewire::test('pages::kanban')
->assertDontSee('Owner secret')
->assertDontSee('Owner Folder');
});
test('viewers cannot move todos on the board', function () {
$owner = User::factory()->create();
$member = User::factory()->create();
$organization = Organization::factory()->family()->withMember($owner)->create();
$owner->forceFill(['current_organization_id' => $organization->id])->save();
$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' => 'Shared List']);
$todo = Todo::factory()->recycle($owner)->for($folder)->create([
'description' => 'Shared task',
'status' => TodoStatus::Open,
]);
$this->actingAs($member);
Livewire::test('pages::kanban')
->assertSee('Shared task')
->call('moveTodo', $todo->id, 0, 'in-progress')
->assertStatus(403);
expect($todo->fresh()->status)->toBe(TodoStatus::Open);
});
+81
View File
@@ -266,6 +266,87 @@ test('users do not see another user todos', function () {
->assertDontSee('Owner secret');
});
test('todos can be sorted by a column and returned to the manual order', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Alpha', 'position' => 0]);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Bravo', 'position' => 1]);
Livewire::test('pages::todos')
->assertSeeInOrder(['Alpha', 'Bravo'])
->assertSeeHtml('wire:sort="handleSort"')
->assertSeeHtml('cursor-grab')
->assertSeeHtml('wire:click="sort(\'description\')"')
->call('sort', 'description')
->assertSet('sortBy', 'description')
->assertSet('sortDirection', 'asc')
->assertSeeInOrder(['Alpha', 'Bravo'])
->assertDontSeeHtml('cursor-grab')
->call('sort', 'description')
->assertSet('sortDirection', 'desc')
->assertSeeInOrder(['Bravo', 'Alpha'])
->call('sort', 'description')
->assertSet('sortBy', null)
->assertSet('sortDirection', 'asc')
->assertSeeInOrder(['Alpha', 'Bravo'])
->assertSeeHtml('cursor-grab');
});
test('todos can be sorted by status workflow order', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Completed task', 'status' => TodoStatus::Completed, 'position' => 0]);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Open task', 'status' => TodoStatus::Open, 'position' => 1]);
Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Blocked task', 'status' => TodoStatus::Blocked, 'position' => 2]);
Livewire::test('pages::todos')
->call('sort', 'status')
->assertSeeInOrder(['Open task', 'Blocked task', 'Completed task']);
});
test('todos can be sorted by folder name', function () {
$user = User::factory()->create();
$this->actingAs($user);
$alpha = Folder::factory()->for($user)->create(['name' => 'Alpha']);
$zulu = Folder::factory()->for($user)->create(['name' => 'Zulu']);
Todo::factory()->recycle($user)->for($zulu)->create(['description' => 'Zulu task', 'position' => 0]);
Todo::factory()->recycle($user)->for($alpha)->create(['description' => 'Alpha task', 'position' => 1]);
Livewire::test('pages::todos')
->assertSeeInOrder(['Zulu task', 'Alpha task'])
->call('sort', 'folder')
->assertSeeInOrder(['Alpha task', 'Zulu task'])
->call('sort', 'folder')
->assertSeeInOrder(['Zulu task', 'Alpha task']);
});
test('sorting resets the loaded batch', function () {
$user = User::factory()->create();
$this->actingAs($user);
$folder = Folder::factory()->for($user)->create(['name' => 'Work']);
collect(range(1, 60))
->each(fn (int $n) => Todo::factory()->recycle($user)->for($folder)->create([
'description' => 'Todo '.$n,
'position' => $n - 1,
]));
Livewire::test('pages::todos')
->call('loadMore')
->assertSet('limit', 60)
->call('sort', 'description')
->assertSet('limit', 50);
});
test('completed todos show their completion date and days to completion', function () {
$this->travelTo('2026-09-10 09:00:00');