TenantAtlas/tests/Feature/Workspaces/WorkspaceBackfillMigrationTest.php
2026-02-01 12:19:57 +01:00

102 lines
3.2 KiB
PHP

<?php
use App\Models\Tenant;
use App\Models\TenantMembership;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\DB;
function workspaceBackfillMigrationPath(): string
{
return database_path('migrations/2026_02_01_085446_backfill_default_workspace_and_memberships.php');
}
it('backfills a default workspace and assigns legacy tenants to it', function () {
Workspace::query()->delete();
$tenantA = Tenant::factory()->create(['workspace_id' => null, 'is_current' => true]);
$tenantB = Tenant::factory()->create(['workspace_id' => null, 'is_current' => false]);
$userOwner = User::factory()->create();
$userReadonly = User::factory()->create();
TenantMembership::query()->create([
'tenant_id' => $tenantA->getKey(),
'user_id' => $userOwner->getKey(),
'role' => 'owner',
'source' => 'manual',
'source_ref' => null,
'created_by_user_id' => null,
]);
TenantMembership::query()->create([
'tenant_id' => $tenantB->getKey(),
'user_id' => $userReadonly->getKey(),
'role' => 'readonly',
'source' => 'manual',
'source_ref' => null,
'created_by_user_id' => null,
]);
$migration = require workspaceBackfillMigrationPath();
$migration->up();
$defaultWorkspace = Workspace::query()->where('slug', 'default')->first();
expect($defaultWorkspace)->not->toBeNull();
$tenantA->refresh();
$tenantB->refresh();
expect($tenantA->workspace_id)->toBe($defaultWorkspace->getKey())
->and($tenantB->workspace_id)->toBe($defaultWorkspace->getKey());
$memberships = DB::table('workspace_memberships')
->where('workspace_id', $defaultWorkspace->getKey())
->get(['user_id', 'role']);
expect($memberships)->toHaveCount(2)
->and($memberships->firstWhere('user_id', $userOwner->getKey())->role)->toBe('owner')
->and($memberships->firstWhere('user_id', $userReadonly->getKey())->role)->toBe('readonly');
$userOwner->refresh();
$userReadonly->refresh();
expect($userOwner->last_workspace_id)->toBe($defaultWorkspace->getKey())
->and($userReadonly->last_workspace_id)->toBe($defaultWorkspace->getKey());
});
it('is idempotent when run multiple times', function () {
Workspace::query()->delete();
$tenant = Tenant::factory()->create(['workspace_id' => null]);
$user = User::factory()->create();
TenantMembership::query()->create([
'tenant_id' => $tenant->getKey(),
'user_id' => $user->getKey(),
'role' => 'manager',
'source' => 'manual',
'source_ref' => null,
'created_by_user_id' => null,
]);
$migration = require workspaceBackfillMigrationPath();
$migration->up();
$migration->up();
$defaultWorkspace = Workspace::query()->where('slug', 'default')->firstOrFail();
expect(Workspace::query()->where('slug', 'default')->count())->toBe(1);
$tenant->refresh();
expect($tenant->workspace_id)->toBe($defaultWorkspace->getKey());
expect(DB::table('workspace_memberships')
->where('workspace_id', $defaultWorkspace->getKey())
->where('user_id', $user->getKey())
->count())->toBe(1);
});