Compare commits

..

2 Commits

Author SHA1 Message Date
Ahmed Darrazi
9b9bdd351d Merge remote-tracking branch 'origin/dev' into 076-permissions-enterprise-ui
# Conflicts:
#	app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
#	resources/views/filament/forms/components/managed-tenant-onboarding-verification-report.blade.php
2026-02-05 23:04:59 +01:00
Ahmed Darrazi
3ff0e00769 feat(076): required permissions remediation + clustered verify UI + onboarding inline connection edit 2026-02-05 22:06:06 +01:00
85 changed files with 676 additions and 4546 deletions

View File

@ -7,12 +7,9 @@ Thumbs.db
.env .env
.env.* .env.*
*.log *.log
*.log*
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
Dockerfile*
.dockerignore
*.tmp *.tmp
*.swp *.swp
public/build/ public/build/

View File

@ -16,8 +16,6 @@ ## Active Technologies
- PostgreSQL (via Laravel Sail) (067-rbac-troubleshooting) - PostgreSQL (via Laravel Sail) (067-rbac-troubleshooting)
- PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x (073-unified-managed-tenant-onboarding-wizard) - PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x (073-unified-managed-tenant-onboarding-wizard)
- PostgreSQL (Sail) + SQLite in tests where applicable (073-unified-managed-tenant-onboarding-wizard) - PostgreSQL (Sail) + SQLite in tests where applicable (073-unified-managed-tenant-onboarding-wizard)
- PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Filament Infolists (schema-based) (078-operations-tenantless-canonical)
- PostgreSQL (no new migrations — read-only model changes) (078-operations-tenantless-canonical)
- PHP 8.4.15 (feat/005-bulk-operations) - PHP 8.4.15 (feat/005-bulk-operations)
@ -37,9 +35,9 @@ ## Code Style
PHP 8.4.15: Follow standard conventions PHP 8.4.15: Follow standard conventions
## Recent Changes ## Recent Changes
- 078-operations-tenantless-canonical: Added PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Filament Infolists (schema-based)
- 078-operations-tenantless-canonical: Added [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
- 073-unified-managed-tenant-onboarding-wizard: Added PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x - 073-unified-managed-tenant-onboarding-wizard: Added PHP 8.4.x (Composer constraint: `^8.2`) + Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x
- 067-rbac-troubleshooting: Added PHP 8.4 (per repo guidelines) + Laravel 12, Filament v5, Livewire v4
- 058-tenant-ui-polish: Added PHP 8.4.15 (Laravel 12.47.0) + Filament v5.0.0, Livewire v4.0.1
<!-- MANUAL ADDITIONS START --> <!-- MANUAL ADDITIONS START -->

2
.gitignore vendored
View File

@ -6,7 +6,6 @@
.env.production .env.production
.phpactor.json .phpactor.json
.phpunit.result.cache .phpunit.result.cache
*.cache
/.fleet /.fleet
/.idea /.idea
/.nova /.nova
@ -25,7 +24,6 @@ coverage/
/storage/pail /storage/pail
/storage/framework /storage/framework
/storage/logs /storage/logs
/storage/debugbar
/vendor /vendor
/bootstrap/cache /bootstrap/cache
Homestead.json Homestead.json

View File

@ -7,7 +7,6 @@
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Models\UserTenantPreference; use App\Models\UserTenantPreference;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Pages\Page; use Filament\Pages\Page;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
@ -70,8 +69,6 @@ public function selectTenant(int $tenantId): void
$this->persistLastTenant($user, $tenant); $this->persistLastTenant($user, $tenant);
app(WorkspaceContext::class)->rememberLastTenantId((int) $tenant->workspace_id, (int) $tenant->getKey(), request());
$this->redirect(TenantDashboard::getUrl(tenant: $tenant)); $this->redirect(TenantDashboard::getUrl(tenant: $tenant));
} }

View File

@ -8,13 +8,11 @@
use App\Models\Workspace; use App\Models\Workspace;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceIntendedUrl;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Forms\Components\TextInput; use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification; use Filament\Notifications\Notification;
use Filament\Pages\Page; use Filament\Pages\Page;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Gate;
class ChooseWorkspace extends Page class ChooseWorkspace extends Page
{ {
@ -39,12 +37,6 @@ protected function getHeaderActions(): array
Action::make('createWorkspace') Action::make('createWorkspace')
->label('Create workspace') ->label('Create workspace')
->modalHeading('Create workspace') ->modalHeading('Create workspace')
->visible(function (): bool {
$user = auth()->user();
return $user instanceof User
&& Gate::forUser($user)->check('create', Workspace::class);
})
->form([ ->form([
TextInput::make('name') TextInput::make('name')
->required() ->required()
@ -108,9 +100,7 @@ public function selectWorkspace(int $workspaceId): void
$context->setCurrentWorkspace($workspace, $user, request()); $context->setCurrentWorkspace($workspace, $user, request());
$intendedUrl = WorkspaceIntendedUrl::consume(request()); $this->redirect($this->redirectAfterWorkspaceSelected($user));
$this->redirect($intendedUrl ?: $this->redirectAfterWorkspaceSelected($user));
} }
/** /**
@ -124,8 +114,6 @@ public function createWorkspace(array $data): void
abort(403); abort(403);
} }
Gate::forUser($user)->authorize('create', Workspace::class);
$workspace = Workspace::query()->create([ $workspace = Workspace::query()->create([
'name' => $data['name'], 'name' => $data['name'],
'slug' => $data['slug'] ?? null, 'slug' => $data['slug'] ?? null,
@ -144,9 +132,7 @@ public function createWorkspace(array $data): void
->success() ->success()
->send(); ->send();
$intendedUrl = WorkspaceIntendedUrl::consume(request()); $this->redirect($this->redirectAfterWorkspaceSelected($user));
$this->redirect($intendedUrl ?: $this->redirectAfterWorkspaceSelected($user));
} }
private function redirectAfterWorkspaceSelected(User $user): string private function redirectAfterWorkspaceSelected(User $user): string

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Pages\Monitoring;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;
class Alerts extends Page
{
protected static bool $shouldRegisterNavigation = false;
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
protected static ?string $navigationLabel = 'Alerts';
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bell-alert';
protected static ?string $slug = 'alerts';
protected static ?string $title = 'Alerts';
protected string $view = 'filament.pages.monitoring.alerts';
}

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Pages\Monitoring;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;
class AuditLog extends Page
{
protected static bool $shouldRegisterNavigation = false;
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
protected static ?string $navigationLabel = 'Audit Log';
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-clipboard-document-list';
protected static ?string $slug = 'audit-log';
protected static ?string $title = 'Audit Log';
protected string $view = 'filament.pages.monitoring.audit-log';
}

View File

@ -1,21 +1,22 @@
<?php <?php
declare(strict_types=1);
namespace App\Filament\Pages\Monitoring; namespace App\Filament\Pages\Monitoring;
use App\Filament\Resources\OperationRunResource;
use App\Filament\Widgets\Operations\OperationsKpiHeader;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Support\OperationRunOutcome; use App\Support\Badges\BadgeDomain;
use App\Support\OperationRunStatus; use App\Support\Badges\BadgeRenderer;
use App\Support\Workspaces\WorkspaceContext; use App\Support\OperationCatalog;
use BackedEnum; use BackedEnum;
use Filament\Facades\Filament;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms; use Filament\Forms\Contracts\HasForms;
use Filament\Pages\Page; use Filament\Pages\Page;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable; use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable; use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use UnitEnum; use UnitEnum;
@ -25,8 +26,6 @@ class Operations extends Page implements HasForms, HasTable
use InteractsWithForms; use InteractsWithForms;
use InteractsWithTable; use InteractsWithTable;
public string $activeTab = 'all';
protected static bool $isDiscovered = false; protected static bool $isDiscovered = false;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-queue-list'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-queue-list';
@ -38,62 +37,89 @@ class Operations extends Page implements HasForms, HasTable
// Must be non-static // Must be non-static
protected string $view = 'filament.pages.monitoring.operations'; protected string $view = 'filament.pages.monitoring.operations';
public function mount(): void
{
$this->mountInteractsWithTable();
}
protected function getHeaderWidgets(): array
{
return [
OperationsKpiHeader::class,
];
}
public function updatedActiveTab(): void
{
$this->resetPage();
}
public function table(Table $table): Table public function table(Table $table): Table
{ {
return OperationRunResource::table($table) return $table
->query(function (): Builder { ->query(
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request()); OperationRun::query()
->where('tenant_id', Filament::getTenant()->id)
->latest('created_at')
)
->columns([
TextColumn::make('type')
->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state))
->searchable()
->sortable(),
$query = OperationRun::query() TextColumn::make('status')
->with('user') ->badge()
->latest('id') ->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
TextColumn::make('outcome')
->badge()
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunOutcome))
->color(BadgeRenderer::color(BadgeDomain::OperationRunOutcome))
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunOutcome))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
TextColumn::make('initiator_name')
->label('Initiator')
->searchable(),
TextColumn::make('created_at')
->dateTime()
->sortable()
->label('Started'),
TextColumn::make('duration')
->getStateUsing(function (OperationRun $record) {
if ($record->started_at && $record->completed_at) {
return $record->completed_at->diffForHumans($record->started_at, true);
}
return '-';
}),
])
->filters([
SelectFilter::make('outcome')
->options([
'succeeded' => 'Succeeded',
'partially_succeeded' => 'Partially Succeeded',
'failed' => 'Failed',
'cancelled' => 'Cancelled',
'pending' => 'Pending',
]),
SelectFilter::make('type')
->options(
fn () => OperationRun::where('tenant_id', Filament::getTenant()->id)
->distinct()
->pluck('type', 'type')
->toArray()
),
Filter::make('created_at')
->form([
DatePicker::make('created_from'),
DatePicker::make('created_until'),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when( ->when(
$workspaceId, $data['created_from'],
fn (Builder $query): Builder => $query->where('workspace_id', (int) $workspaceId), fn (Builder $query, $date) => $query->whereDate('created_at', '>=', $date),
) )
->when( ->when(
! $workspaceId, $data['created_until'],
fn (Builder $query): Builder => $query->whereRaw('1 = 0'), fn (Builder $query, $date) => $query->whereDate('created_at', '<=', $date),
); );
}),
return $this->applyActiveTab($query); ])
}); ->actions([
} // View action handled by opening a modal or side-peek
]);
private function applyActiveTab(Builder $query): Builder
{
return match ($this->activeTab) {
'active' => $query->whereIn('status', [
OperationRunStatus::Queued->value,
OperationRunStatus::Running->value,
]),
'succeeded' => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::Succeeded->value),
'partial' => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::PartiallySucceeded->value),
'failed' => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::Failed->value),
default => $query,
};
} }
} }

View File

@ -4,22 +4,16 @@
namespace App\Filament\Pages\Operations; namespace App\Filament\Pages\Operations;
use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Services\Auth\CapabilityResolver;
use App\Support\OperationRunLinks;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Pages\Page; use Filament\Pages\Page;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class TenantlessOperationRunViewer extends Page class TenantlessOperationRunViewer extends Page
{ {
protected static string $layout = 'filament-panels::components.layout.simple';
protected static bool $shouldRegisterNavigation = false; protected static bool $shouldRegisterNavigation = false;
protected static bool $isDiscovered = false; protected static bool $isDiscovered = false;
@ -30,53 +24,18 @@ class TenantlessOperationRunViewer extends Page
public OperationRun $run; public OperationRun $run;
public bool $opsUxIsTabHidden = false;
/** /**
* @return array<Action|ActionGroup> * @return array<Action>
*/ */
protected function getHeaderActions(): array protected function getHeaderActions(): array
{ {
$actions = [ return [
Action::make('refresh') Action::make('refresh')
->label('Refresh') ->label('Refresh')
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('gray') ->color('gray')
->url(fn (): string => isset($this->run) ->url(fn (): string => url()->current()),
? route('admin.operations.view', ['run' => (int) $this->run->getKey()])
: route('admin.operations.index')),
]; ];
if (! isset($this->run)) {
return $actions;
}
$user = auth()->user();
$tenant = $this->run->tenant;
if ($tenant instanceof Tenant && (! $user instanceof User || ! app(CapabilityResolver::class)->isMember($user, $tenant))) {
$tenant = null;
}
$related = OperationRunLinks::related($this->run, $tenant);
$relatedActions = [];
foreach ($related as $label => $url) {
$relatedActions[] = Action::make(Str::slug((string) $label, '_'))
->label((string) $label)
->url((string) $url)
->openUrlInNewTab();
}
if ($relatedActions !== []) {
$actions[] = ActionGroup::make($relatedActions)
->label('Open')
->icon('heroicon-o-arrow-top-right-on-square')
->color('gray');
}
return $actions;
} }
public function mount(OperationRun $run): void public function mount(OperationRun $run): void
@ -104,23 +63,4 @@ public function mount(OperationRun $run): void
$this->run = $run->loadMissing(['workspace', 'tenant', 'user']); $this->run = $run->loadMissing(['workspace', 'tenant', 'user']);
} }
public function infolist(Schema $schema): Schema
{
return OperationRunResource::infolist($schema);
}
public function defaultInfolist(Schema $schema): Schema
{
return $schema
->record($this->run)
->columns(2);
}
public function content(Schema $schema): Schema
{
return $schema->schema([
EmbeddedSchema::make('infolist'),
]);
}
} }

View File

@ -2,6 +2,7 @@
namespace App\Filament\Resources; namespace App\Filament\Resources;
use App\Filament\Resources\OperationRunResource\Pages;
use App\Filament\Support\VerificationReportChangeIndicator; use App\Filament\Support\VerificationReportChangeIndicator;
use App\Filament\Support\VerificationReportViewer; use App\Filament\Support\VerificationReportViewer;
use App\Models\OperationRun; use App\Models\OperationRun;
@ -16,10 +17,8 @@
use App\Support\OperationRunStatus; use App\Support\OperationRunStatus;
use App\Support\OpsUx\RunDetailPolling; use App\Support\OpsUx\RunDetailPolling;
use App\Support\OpsUx\RunDurationInsights; use App\Support\OpsUx\RunDurationInsights;
use App\Support\Workspaces\WorkspaceContext;
use BackedEnum; use BackedEnum;
use Filament\Actions; use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DatePicker;
use Filament\Infolists\Components\TextEntry; use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry; use Filament\Infolists\Components\ViewEntry;
@ -39,8 +38,6 @@ class OperationRunResource extends Resource
protected static ?string $slug = 'operations'; protected static ?string $slug = 'operations';
protected static bool $shouldRegisterNavigation = false;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-queue-list'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-queue-list';
protected static string|UnitEnum|null $navigationGroup = 'Monitoring'; protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
@ -49,13 +46,12 @@ class OperationRunResource extends Resource
public static function getEloquentQuery(): Builder public static function getEloquentQuery(): Builder
{ {
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(); $tenantId = Tenant::current()?->getKey();
return parent::getEloquentQuery() return parent::getEloquentQuery()
->with('user') ->with('user')
->latest('id') ->latest('id')
->when($workspaceId, fn (Builder $query) => $query->where('workspace_id', (int) $workspaceId)) ->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId));
->when(! $workspaceId, fn (Builder $query) => $query->whereRaw('1 = 0'));
} }
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
@ -90,11 +86,6 @@ public static function infolist(Schema $schema): Schema
->getStateUsing(fn (OperationRun $record): ?string => static::targetScopeDisplay($record)) ->getStateUsing(fn (OperationRun $record): ?string => static::targetScopeDisplay($record))
->visible(fn (OperationRun $record): bool => static::targetScopeDisplay($record) !== null) ->visible(fn (OperationRun $record): bool => static::targetScopeDisplay($record) !== null)
->columnSpanFull(), ->columnSpanFull(),
TextEntry::make('target_scope_empty_state')
->label('Target')
->getStateUsing(static fn (): string => 'No target scope details were recorded for this run.')
->visible(fn (OperationRun $record): bool => static::targetScopeDisplay($record) === null)
->columnSpanFull(),
TextEntry::make('elapsed') TextEntry::make('elapsed')
->label('Elapsed') ->label('Elapsed')
->getStateUsing(fn (OperationRun $record): string => RunDurationInsights::elapsedHuman($record)), ->getStateUsing(fn (OperationRun $record): string => RunDurationInsights::elapsedHuman($record)),
@ -165,7 +156,7 @@ public static function infolist(Schema $schema): Schema
$previousRunUrl = null; $previousRunUrl = null;
if ($changeIndicator !== null) { if ($changeIndicator !== null) {
$tenant = Filament::getTenant(); $tenant = Tenant::current();
$previousRunUrl = $tenant instanceof Tenant $previousRunUrl = $tenant instanceof Tenant
? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant) ? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant)
@ -281,47 +272,16 @@ public static function table(Table $table): Table
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
]) ])
->filters([ ->filters([
Tables\Filters\SelectFilter::make('tenant_id')
->label('Tenant')
->options(function (): array {
$user = auth()->user();
if (! $user instanceof User) {
return [];
}
return collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->mapWithKeys(static fn (Tenant $tenant): array => [
(string) $tenant->getKey() => $tenant->getFilamentName(),
])
->all();
})
->default(function (): ?string {
$tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) {
return null;
}
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
if ($workspaceId === null || (int) $tenant->workspace_id !== (int) $workspaceId) {
return null;
}
return (string) $tenant->getKey();
})
->searchable(),
Tables\Filters\SelectFilter::make('type') Tables\Filters\SelectFilter::make('type')
->options(function (): array { ->options(function (): array {
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(); $tenantId = Tenant::current()?->getKey();
if ($workspaceId === null) { if (! $tenantId) {
return []; return [];
} }
return OperationRun::query() return OperationRun::query()
->where('workspace_id', (int) $workspaceId) ->where('tenant_id', $tenantId)
->select('type') ->select('type')
->distinct() ->distinct()
->orderBy('type') ->orderBy('type')
@ -339,20 +299,14 @@ public static function table(Table $table): Table
Tables\Filters\SelectFilter::make('initiator_name') Tables\Filters\SelectFilter::make('initiator_name')
->label('Initiator') ->label('Initiator')
->options(function (): array { ->options(function (): array {
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(); $tenantId = Tenant::current()?->getKey();
if ($workspaceId === null) { if (! $tenantId) {
return []; return [];
} }
$tenant = Filament::getTenant();
$tenantId = $tenant instanceof Tenant && (int) $tenant->workspace_id === (int) $workspaceId
? (int) $tenant->getKey()
: null;
return OperationRun::query() return OperationRun::query()
->where('workspace_id', (int) $workspaceId) ->where('tenant_id', $tenantId)
->when($tenantId, fn (Builder $query): Builder => $query->where('tenant_id', $tenantId))
->whereNotNull('initiator_name') ->whereNotNull('initiator_name')
->select('initiator_name') ->select('initiator_name')
->distinct() ->distinct()
@ -388,16 +342,17 @@ public static function table(Table $table): Table
}), }),
]) ])
->actions([ ->actions([
Actions\ViewAction::make() Actions\ViewAction::make(),
->label('View run')
->url(fn (OperationRun $record): string => route('admin.operations.view', ['run' => (int) $record->getKey()])),
]) ])
->bulkActions([]); ->bulkActions([]);
} }
public static function getPages(): array public static function getPages(): array
{ {
return []; return [
'index' => Pages\ListOperationRuns::route('/'),
'view' => Pages\ViewOperationRun::route('/{record}'),
];
} }
private static function targetScopeDisplay(OperationRun $record): ?string private static function targetScopeDisplay(OperationRun $record): ?string

View File

@ -0,0 +1,64 @@
<?php
namespace App\Filament\Resources\OperationRunResource\Pages;
use App\Filament\Resources\OperationRunResource;
use App\Filament\Widgets\Operations\OperationsKpiHeader;
use App\Models\Tenant;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\ActiveRuns;
use Filament\Facades\Filament;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;
class ListOperationRuns extends ListRecords
{
protected static string $resource = OperationRunResource::class;
protected function getHeaderWidgets(): array
{
return [
OperationsKpiHeader::class,
];
}
/**
* @return array<string, Tab>
*/
public function getTabs(): array
{
return [
'all' => Tab::make(),
'active' => Tab::make()
->modifyQueryUsing(fn (Builder $query): Builder => $query->whereIn('status', [
OperationRunStatus::Queued->value,
OperationRunStatus::Running->value,
])),
'succeeded' => Tab::make()
->modifyQueryUsing(fn (Builder $query): Builder => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::Succeeded->value)),
'partial' => Tab::make()
->modifyQueryUsing(fn (Builder $query): Builder => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::PartiallySucceeded->value)),
'failed' => Tab::make()
->modifyQueryUsing(fn (Builder $query): Builder => $query
->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::Failed->value)),
];
}
protected function getTablePollingInterval(): ?string
{
$tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) {
return null;
}
return ActiveRuns::existForTenant($tenant) ? '10s' : null;
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Filament\Resources\OperationRunResource\Pages;
use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\OperationRunLinks;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;
use Illuminate\Support\Str;
class ViewOperationRun extends ViewRecord
{
protected static string $resource = OperationRunResource::class;
public bool $opsUxIsTabHidden = false;
protected function getHeaderActions(): array
{
$tenant = Tenant::current();
if (! $tenant instanceof Tenant) {
return [];
}
/** @var OperationRun $run */
$run = $this->getRecord();
$related = OperationRunLinks::related($run, $tenant);
$actions = [];
foreach ($related as $label => $url) {
$actions[] = Actions\Action::make(Str::slug($label, '_'))
->label($label)
->url($url)
->openUrlInNewTab();
}
if (empty($actions)) {
return [];
}
return [
Actions\ActionGroup::make($actions)
->label('Open')
->icon('heroicon-o-arrow-top-right-on-square')
->color('gray'),
];
}
}

View File

@ -3,7 +3,6 @@
namespace App\Filament\Resources\TenantResource\Pages; namespace App\Filament\Resources\TenantResource\Pages;
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Filament\Widgets\Tenant\RecentOperationsSummary;
use App\Filament\Widgets\Tenant\TenantArchivedBanner; use App\Filament\Widgets\Tenant\TenantArchivedBanner;
use App\Models\Tenant; use App\Models\Tenant;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
@ -24,7 +23,6 @@ protected function getHeaderWidgets(): array
{ {
return [ return [
TenantArchivedBanner::class, TenantArchivedBanner::class,
RecentOperationsSummary::class,
]; ];
} }

View File

@ -3,7 +3,6 @@
namespace App\Filament\Resources\Workspaces; namespace App\Filament\Resources\Workspaces;
use App\Filament\Resources\Workspaces\RelationManagers\WorkspaceMembershipsRelationManager; use App\Filament\Resources\Workspaces\RelationManagers\WorkspaceMembershipsRelationManager;
use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use BackedEnum; use BackedEnum;
use Filament\Actions; use Filament\Actions;
@ -12,7 +11,6 @@
use Filament\Schemas\Schema; use Filament\Schemas\Schema;
use Filament\Tables; use Filament\Tables;
use Filament\Tables\Table; use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum; use UnitEnum;
class WorkspaceResource extends Resource class WorkspaceResource extends Resource
@ -27,31 +25,10 @@ class WorkspaceResource extends Resource
protected static bool $shouldRegisterNavigation = false; protected static bool $shouldRegisterNavigation = false;
protected static ?string $breadcrumb = 'Manage workspaces';
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-squares-2x2'; protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-squares-2x2';
protected static string|UnitEnum|null $navigationGroup = 'Settings'; protected static string|UnitEnum|null $navigationGroup = 'Settings';
public static function getEloquentQuery(): Builder
{
$query = parent::getEloquentQuery();
$user = auth()->user();
if (! $user instanceof User) {
return $query->whereRaw('1 = 0');
}
return $query
->whereNull('archived_at')
->whereIn('id', function ($subQuery) use ($user): void {
$subQuery->from('workspace_memberships')
->select('workspace_id')
->where('user_id', $user->getKey());
});
}
public static function form(Schema $schema): Schema public static function form(Schema $schema): Schema
{ {
return $schema return $schema

View File

@ -5,6 +5,7 @@
namespace App\Filament\Widgets\Dashboard; namespace App\Filament\Widgets\Dashboard;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Filament\Resources\OperationRunResource;
use App\Models\Finding; use App\Models\Finding;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
@ -80,10 +81,10 @@ protected function getStats(): array
->url(FindingResource::getUrl('index', tenant: $tenant)), ->url(FindingResource::getUrl('index', tenant: $tenant)),
Stat::make('Active operations', $activeRuns) Stat::make('Active operations', $activeRuns)
->color($activeRuns > 0 ? 'warning' : 'gray') ->color($activeRuns > 0 ? 'warning' : 'gray')
->url(route('admin.operations.index')), ->url(OperationRunResource::getUrl('index', tenant: $tenant)),
Stat::make('Inventory active', $inventoryActiveRuns) Stat::make('Inventory active', $inventoryActiveRuns)
->color($inventoryActiveRuns > 0 ? 'warning' : 'gray') ->color($inventoryActiveRuns > 0 ? 'warning' : 'gray')
->url(route('admin.operations.index')), ->url(OperationRunResource::getUrl('index', tenant: $tenant)),
]; ];
} }
} }

View File

@ -40,7 +40,12 @@ protected function getStats(): array
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof Tenant) {
return []; return [
Stat::make('Total Runs (30 days)', 0),
Stat::make('Active Runs', 0),
Stat::make('Failed/Partial (7 days)', 0),
Stat::make('Avg Duration (7 days)', '—'),
];
} }
$tenantId = (int) $tenant->getKey(); $tenantId = (int) $tenant->getKey();

View File

@ -1,56 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Filament\Widgets\Tenant;
use App\Models\OperationRun;
use App\Models\Tenant;
use Filament\Facades\Filament;
use Filament\Widgets\Widget;
use Illuminate\Database\Eloquent\Collection;
class RecentOperationsSummary extends Widget
{
protected static bool $isLazy = false;
protected string $view = 'filament.widgets.tenant.recent-operations-summary';
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
$tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) {
return [
'tenant' => null,
'runs' => collect(),
'operationsIndexUrl' => route('admin.operations.index'),
];
}
/** @var Collection<int, OperationRun> $runs */
$runs = OperationRun::query()
->where('tenant_id', (int) $tenant->getKey())
->orderByDesc('created_at')
->orderByDesc('id')
->limit(5)
->get([
'id',
'type',
'status',
'outcome',
'created_at',
'started_at',
'completed_at',
]);
return [
'tenant' => $tenant,
'runs' => $runs,
'operationsIndexUrl' => route('admin.operations.index'),
];
}
}

View File

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
final class ClearTenantContextController
{
public function __invoke(Request $request): RedirectResponse
{
Filament::setTenant(null, true);
app(WorkspaceContext::class)->clearLastTenantId($request);
return redirect()->to('/admin/operations');
}
}

View File

@ -49,8 +49,6 @@ public function __invoke(Request $request): RedirectResponse
$this->persistLastTenant($user, $tenant); $this->persistLastTenant($user, $tenant);
app(WorkspaceContext::class)->rememberLastTenantId((int) $workspaceId, (int) $tenant->getKey(), $request);
return redirect()->to(TenantDashboard::getUrl(tenant: $tenant)); return redirect()->to(TenantDashboard::getUrl(tenant: $tenant));
} }

View File

@ -9,7 +9,6 @@
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceIntendedUrl;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@ -45,12 +44,6 @@ public function __invoke(Request $request): RedirectResponse
$context->setCurrentWorkspace($workspace, $user, $request); $context->setCurrentWorkspace($workspace, $user, $request);
$intendedUrl = WorkspaceIntendedUrl::consume($request);
if ($intendedUrl !== null) {
return redirect()->to($intendedUrl);
}
$tenantsQuery = $user->tenants() $tenantsQuery = $user->tenants()
->where('workspace_id', $workspace->getKey()) ->where('workspace_id', $workspace->getKey())
->where('status', 'active'); ->where('status', 'active');

View File

@ -3,14 +3,11 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Models\User; use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceIntendedUrl;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response as HttpResponse; use Illuminate\Http\Response as HttpResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@ -31,11 +28,24 @@ public function handle(Request $request, Closure $next): Response
$path = '/'.ltrim($request->path(), '/'); $path = '/'.ltrim($request->path(), '/');
if ($this->isWorkspaceOptionalPath($request, $path)) { if (str_starts_with($path, '/admin/t/')) {
return $next($request); return $next($request);
} }
if (str_starts_with($path, '/admin/t/')) { if ($path === '/livewire/update') {
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
$refererPath = '/'.ltrim((string) $refererPath, '/');
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
return $next($request);
}
}
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
return $next($request);
}
if (in_array($path, ['/admin/no-access', '/admin/choose-workspace'], true)) {
return $next($request); return $next($request);
} }
@ -63,38 +73,8 @@ public function handle(Request $request, Closure $next): Response
->exists() ->exists()
: $membershipQuery->exists(); : $membershipQuery->exists();
$canCreateWorkspace = Gate::forUser($user)->check('create', Workspace::class); $target = $hasAnyActiveMembership ? '/admin/choose-workspace' : '/admin/no-access';
$target = ($hasAnyActiveMembership || $canCreateWorkspace)
? '/admin/choose-workspace'
: '/admin/no-access';
if ($target === '/admin/choose-workspace') {
WorkspaceIntendedUrl::storeFromRequest($request);
}
return new HttpResponse('', 302, ['Location' => $target]); return new HttpResponse('', 302, ['Location' => $target]);
} }
private function isWorkspaceOptionalPath(Request $request, string $path): bool
{
if (str_starts_with($path, '/admin/workspaces')) {
return true;
}
if (in_array($path, ['/admin/choose-workspace', '/admin/no-access', '/admin/onboarding'], true)) {
return true;
}
if ($path === '/livewire/update') {
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
$refererPath = '/'.ltrim((string) $refererPath, '/');
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
return true;
}
}
return preg_match('#^/admin/operations/[^/]+$#', $path) === 1;
}
} }

View File

@ -0,0 +1,28 @@
<?php
namespace App\Livewire\Monitoring;
use App\Models\OperationRun;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Illuminate\Contracts\View\View;
use Livewire\Component;
class OperationsDetail extends Component implements HasForms
{
use InteractsWithForms;
public OperationRun $run;
public function mount(OperationRun $run): void
{
// Ensure tenant scope
abort_unless($run->tenant_id === filament()->getTenant()->id, 403);
$this->run = $run;
}
public function render(): View
{
return view('livewire.monitoring.operations-detail');
}
}

View File

@ -7,54 +7,45 @@
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use Illuminate\Auth\Access\Response;
class WorkspacePolicy class WorkspacePolicy
{ {
/** /**
* Determine whether the user can view any models. * Determine whether the user can view any models.
*/ */
public function viewAny(User $user): bool|Response public function viewAny(User $user): bool
{ {
return Response::allow(); return true;
} }
/** /**
* Determine whether the user can view the model. * Determine whether the user can view the model.
*/ */
public function view(User $user, Workspace $workspace): bool|Response public function view(User $user, Workspace $workspace): bool
{ {
$isMember = WorkspaceMembership::query() return WorkspaceMembership::query()
->where('user_id', $user->getKey()) ->where('user_id', $user->getKey())
->where('workspace_id', $workspace->getKey()) ->where('workspace_id', $workspace->getKey())
->exists(); ->exists();
return $isMember ? Response::allow() : Response::denyAsNotFound();
} }
/** /**
* Determine whether the user can create models. * Determine whether the user can create models.
*/ */
public function create(User $user): bool|Response public function create(User $user): bool
{ {
return Response::allow(); return true;
} }
/** /**
* Determine whether the user can update the model. * Determine whether the user can update the model.
*/ */
public function update(User $user, Workspace $workspace): bool|Response public function update(User $user, Workspace $workspace): bool
{ {
/** @var WorkspaceCapabilityResolver $resolver */ /** @var WorkspaceCapabilityResolver $resolver */
$resolver = app(WorkspaceCapabilityResolver::class); $resolver = app(WorkspaceCapabilityResolver::class);
if (! $resolver->isMember($user, $workspace)) { return $resolver->can($user, $workspace, Capabilities::WORKSPACE_MANAGE);
return Response::denyAsNotFound();
}
return $resolver->can($user, $workspace, Capabilities::WORKSPACE_MANAGE)
? Response::allow()
: Response::deny();
} }
/** /**

View File

@ -9,10 +9,6 @@
use App\Filament\Pages\TenantDashboard; use App\Filament\Pages\TenantDashboard;
use App\Filament\Resources\Workspaces\WorkspaceResource; use App\Filament\Resources\Workspaces\WorkspaceResource;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;
use App\Support\Middleware\DenyNonMemberTenantAccess; use App\Support\Middleware\DenyNonMemberTenantAccess;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\Authenticate;
@ -57,50 +53,21 @@ public function panel(Panel $panel): Panel
'primary' => Color::Amber, 'primary' => Color::Amber,
]) ])
->navigationItems([ ->navigationItems([
NavigationItem::make('Manage workspaces') NavigationItem::make('Workspaces')
->url(function (): string { ->url(function (): string {
return route('filament.admin.resources.workspaces.index'); return route('filament.admin.resources.workspaces.index');
}) })
->icon('heroicon-o-squares-2x2') ->icon('heroicon-o-squares-2x2')
->group('Settings') ->group('Settings')
->sort(10)
->visible(function (): bool {
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
$roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
return WorkspaceMembership::query()
->where('user_id', (int) $user->getKey())
->whereIn('role', $roles)
->exists();
}),
NavigationItem::make('Operations')
->url(fn (): string => route('admin.operations.index'))
->icon('heroicon-o-queue-list')
->group('Monitoring')
->sort(10), ->sort(10),
NavigationItem::make('Alerts')
->url(fn (): string => route('admin.monitoring.alerts'))
->icon('heroicon-o-bell-alert')
->group('Monitoring')
->sort(20),
NavigationItem::make('Audit Log')
->url(fn (): string => route('admin.monitoring.audit-log'))
->icon('heroicon-o-clipboard-document-list')
->group('Monitoring')
->sort(30),
]) ])
->renderHook( ->renderHook(
PanelsRenderHook::HEAD_END, PanelsRenderHook::HEAD_END,
fn () => view('filament.partials.livewire-intercept-shim')->render() fn () => view('filament.partials.livewire-intercept-shim')->render()
) )
->renderHook( ->renderHook(
PanelsRenderHook::TOPBAR_START, PanelsRenderHook::USER_MENU_PROFILE_AFTER,
fn () => view('filament.partials.context-bar')->render() fn () => view('filament.partials.workspace-switcher')->render()
) )
->renderHook( ->renderHook(
PanelsRenderHook::BODY_END, PanelsRenderHook::BODY_END,

View File

@ -135,28 +135,9 @@ public function compare(
$canPersist = $persist; $canPersist = $persist;
if ($canPersist && $liveCheckMeta['attempted'] === true && $liveCheckMeta['succeeded'] === false) { if ($liveCheckMeta['attempted'] === true && $liveCheckMeta['succeeded'] === false) {
// Enterprise-safe: never overwrite stored inventory when we could not refresh it. // Enterprise-safe: never overwrite stored inventory when we could not refresh it.
// When the failure is a deterministic misconfiguration (e.g. permission denied), persist an "error" snapshot
// only if we have no stored inventory yet, so the UI can explain the failure.
$reasonCode = is_string($liveCheckMeta['reason_code'] ?? null)
? (string) $liveCheckMeta['reason_code']
: null;
$shouldPersistErrorSnapshot = in_array($reasonCode, [
'authentication_failed',
'permission_denied',
], true);
if (! $shouldPersistErrorSnapshot) {
$canPersist = false; $canPersist = false;
} else {
$hasStoredStatuses = TenantPermission::query()
->where('tenant_id', $tenant->id)
->exists();
$canPersist = ! $hasStoredStatuses;
}
} }
foreach ($required as $permission) { foreach ($required as $permission) {

View File

@ -2,12 +2,11 @@
namespace App\Support\Middleware; namespace App\Support\Middleware;
use App\Filament\Pages\ChooseWorkspace;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Models\WorkspaceMembership; use App\Services\Auth\CapabilityResolver;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use Closure; use Closure;
use Filament\Facades\Filament; use Filament\Facades\Filament;
@ -28,14 +27,6 @@ public function handle(Request $request, Closure $next): Response
$path = '/'.ltrim($request->path(), '/'); $path = '/'.ltrim($request->path(), '/');
$workspaceContext = app(WorkspaceContext::class);
$workspaceId = $workspaceContext->currentWorkspaceId($request);
$existingTenant = Filament::getTenant();
if ($existingTenant instanceof Tenant && $workspaceId !== null && (int) $existingTenant->workspace_id !== (int) $workspaceId) {
Filament::setTenant(null, true);
}
if ($path === '/livewire/update') { if ($path === '/livewire/update') {
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? ''; $refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
$refererPath = '/'.ltrim((string) $refererPath, '/'); $refererPath = '/'.ltrim((string) $refererPath, '/');
@ -53,12 +44,6 @@ public function handle(Request $request, Closure $next): Response
return $next($request); return $next($request);
} }
if ($path === '/admin/operations') {
$this->configureNavigationForRequest($panel);
return $next($request);
}
if ($request->route()?->hasParameter('tenant')) { if ($request->route()?->hasParameter('tenant')) {
$user = $request->user(); $user = $request->user();
@ -81,6 +66,9 @@ public function handle(Request $request, Closure $next): Response
abort(404); abort(404);
} }
$workspaceContext = app(WorkspaceContext::class);
$workspaceId = $workspaceContext->currentWorkspaceId($request);
if ($workspaceId === null) { if ($workspaceId === null) {
abort(404); abort(404);
} }
@ -104,9 +92,6 @@ public function handle(Request $request, Closure $next): Response
} }
Filament::setTenant($tenant, true); Filament::setTenant($tenant, true);
app(WorkspaceContext::class)->rememberLastTenantId((int) $workspaceId, (int) $tenant->getKey(), $request);
$this->configureNavigationForRequest($panel); $this->configureNavigationForRequest($panel);
return $next($request); return $next($request);
@ -115,8 +100,7 @@ public function handle(Request $request, Closure $next): Response
if ( if (
str_starts_with($path, '/admin/w/') str_starts_with($path, '/admin/w/')
|| str_starts_with($path, '/admin/workspaces') || str_starts_with($path, '/admin/workspaces')
|| str_starts_with($path, '/admin/operations') || in_array($path, ['/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access'], true)
|| in_array($path, ['/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access', '/admin/alerts', '/admin/audit-log', '/admin/onboarding'], true)
) { ) {
$this->configureNavigationForRequest($panel); $this->configureNavigationForRequest($panel);
@ -137,6 +121,60 @@ public function handle(Request $request, Closure $next): Response
return $next($request); return $next($request);
} }
$tenant = null;
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);
if ($workspaceId !== null) {
$tenant = $user->tenants()
->where('workspace_id', $workspaceId)
->where('status', 'active')
->first();
if (! $tenant) {
$tenant = $user->tenants()
->where('workspace_id', $workspaceId)
->first();
}
if (! $tenant) {
$tenant = $user->tenants()
->withTrashed()
->where('workspace_id', $workspaceId)
->first();
}
}
if (! $tenant) {
try {
$tenant = Tenant::current();
} catch (\RuntimeException) {
$tenant = null;
}
if ($tenant instanceof Tenant && ! app(CapabilityResolver::class)->isMember($user, $tenant)) {
$tenant = null;
}
}
if (! $tenant) {
$tenant = $user->tenants()
->where('status', 'active')
->first();
}
if (! $tenant) {
$tenant = $user->tenants()->first();
}
if (! $tenant) {
$tenant = $user->tenants()->withTrashed()->first();
}
if ($tenant) {
Filament::setTenant($tenant, true);
}
$this->configureNavigationForRequest($panel); $this->configureNavigationForRequest($panel);
return $next($request); return $next($request);
@ -157,46 +195,11 @@ private function configureNavigationForRequest(\Filament\Panel $panel): void
$panel->navigation(function (): NavigationBuilder { $panel->navigation(function (): NavigationBuilder {
return app(NavigationBuilder::class) return app(NavigationBuilder::class)
->item( ->item(
NavigationItem::make('Manage workspaces') NavigationItem::make('Workspaces')
->url(fn (): string => route('filament.admin.resources.workspaces.index')) ->url(fn (): string => ChooseWorkspace::getUrl())
->icon('heroicon-o-squares-2x2') ->icon('heroicon-o-squares-2x2')
->group('Settings') ->group('Settings')
->sort(10)
->visible(function (): bool {
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
$roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
return WorkspaceMembership::query()
->where('user_id', (int) $user->getKey())
->whereIn('role', $roles)
->exists();
}),
)
->item(
NavigationItem::make('Operations')
->url(fn (): string => route('admin.operations.index'))
->icon('heroicon-o-queue-list')
->group('Monitoring')
->sort(10), ->sort(10),
)
->item(
NavigationItem::make('Alerts')
->url(fn (): string => '/admin/alerts')
->icon('heroicon-o-bell-alert')
->group('Monitoring')
->sort(20),
)
->item(
NavigationItem::make('Audit Log')
->url(fn (): string => '/admin/audit-log')
->icon('heroicon-o-clipboard-document-list')
->group('Monitoring')
->sort(30),
); );
}); });
} }

View File

@ -7,6 +7,7 @@
use App\Filament\Resources\BackupScheduleResource; use App\Filament\Resources\BackupScheduleResource;
use App\Filament\Resources\BackupSetResource; use App\Filament\Resources\BackupSetResource;
use App\Filament\Resources\EntraGroupResource; use App\Filament\Resources\EntraGroupResource;
use App\Filament\Resources\OperationRunResource;
use App\Filament\Resources\PolicyResource; use App\Filament\Resources\PolicyResource;
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\RestoreRunResource; use App\Filament\Resources\RestoreRunResource;
@ -15,9 +16,9 @@
final class OperationRunLinks final class OperationRunLinks
{ {
public static function index(?Tenant $tenant = null): string public static function index(Tenant $tenant): string
{ {
return route('admin.operations.index'); return OperationRunResource::getUrl('index', tenant: $tenant);
} }
public static function tenantlessView(OperationRun|int $run): string public static function tenantlessView(OperationRun|int $run): string
@ -29,13 +30,13 @@ public static function tenantlessView(OperationRun|int $run): string
public static function view(OperationRun|int $run, Tenant $tenant): string public static function view(OperationRun|int $run, Tenant $tenant): string
{ {
return self::tenantlessView($run); return OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant);
} }
/** /**
* @return array<string, string> * @return array<string, string>
*/ */
public static function related(OperationRun $run, ?Tenant $tenant): array public static function related(OperationRun $run, Tenant $tenant): array
{ {
$context = is_array($run->context) ? $run->context : []; $context = is_array($run->context) ? $run->context : [];
@ -43,10 +44,6 @@ public static function related(OperationRun $run, ?Tenant $tenant): array
$links['Operations'] = self::index($tenant); $links['Operations'] = self::index($tenant);
if (! $tenant instanceof Tenant) {
return $links;
}
$providerConnectionId = $context['provider_connection_id'] ?? null; $providerConnectionId = $context['provider_connection_id'] ?? null;
if (is_numeric($providerConnectionId) && class_exists(ProviderConnectionResource::class)) { if (is_numeric($providerConnectionId) && class_exists(ProviderConnectionResource::class)) {

View File

@ -11,10 +11,6 @@ final class WorkspaceContext
{ {
public const SESSION_KEY = 'current_workspace_id'; public const SESSION_KEY = 'current_workspace_id';
public const INTENDED_URL_SESSION_KEY = 'workspace_intended_url';
public const LAST_TENANT_IDS_SESSION_KEY = 'workspace_last_tenant_ids';
public function __construct(private WorkspaceResolver $resolver) {} public function __construct(private WorkspaceResolver $resolver) {}
public function currentWorkspaceId(?Request $request = null): ?int public function currentWorkspaceId(?Request $request = null): ?int
@ -57,54 +53,6 @@ public function setCurrentWorkspace(Workspace $workspace, ?User $user = null, ?R
} }
} }
public function rememberLastTenantId(int $workspaceId, int $tenantId, ?Request $request = null): void
{
$session = ($request && $request->hasSession()) ? $request->session() : session();
$map = $session->get(self::LAST_TENANT_IDS_SESSION_KEY, []);
$map = is_array($map) ? $map : [];
$map[(string) $workspaceId] = $tenantId;
$session->put(self::LAST_TENANT_IDS_SESSION_KEY, $map);
}
public function lastTenantId(?Request $request = null): ?int
{
$workspaceId = $this->currentWorkspaceId($request);
if ($workspaceId === null) {
return null;
}
$session = ($request && $request->hasSession()) ? $request->session() : session();
$map = $session->get(self::LAST_TENANT_IDS_SESSION_KEY, []);
$map = is_array($map) ? $map : [];
$id = $map[(string) $workspaceId] ?? null;
return is_int($id) ? $id : (is_numeric($id) ? (int) $id : null);
}
public function clearLastTenantId(?Request $request = null): void
{
$workspaceId = $this->currentWorkspaceId($request);
if ($workspaceId === null) {
return;
}
$session = ($request && $request->hasSession()) ? $request->session() : session();
$map = $session->get(self::LAST_TENANT_IDS_SESSION_KEY, []);
$map = is_array($map) ? $map : [];
unset($map[(string) $workspaceId]);
$session->put(self::LAST_TENANT_IDS_SESSION_KEY, $map);
}
public function clearCurrentWorkspace(?User $user = null, ?Request $request = null): void public function clearCurrentWorkspace(?User $user = null, ?Request $request = null): void
{ {
$session = ($request && $request->hasSession()) ? $request->session() : session(); $session = ($request && $request->hasSession()) ? $request->session() : session();

View File

@ -1,126 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Support\Workspaces;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
final class WorkspaceIntendedUrl
{
/**
* Store a safe intended URL (path + query) for returning after workspace selection.
*/
public static function store(string $pathWithQuery, ?Request $request = null): void
{
$pathWithQuery = trim($pathWithQuery);
if ($pathWithQuery === '') {
return;
}
if (! self::isAllowed($pathWithQuery)) {
return;
}
$session = self::session($request);
if (! $session instanceof Store) {
return;
}
$session->put(WorkspaceContext::INTENDED_URL_SESSION_KEY, $pathWithQuery);
}
/**
* Store the intended URL derived from the current request.
*/
public static function storeFromRequest(Request $request): void
{
if (! $request->isMethod('GET')) {
return;
}
$path = '/'.ltrim($request->path(), '/');
$queryString = $request->getQueryString();
$pathWithQuery = $queryString ? "{$path}?{$queryString}" : $path;
self::store($pathWithQuery, $request);
}
/**
* Consume (read + forget) the intended URL. Returns null if missing or unsafe.
*/
public static function consume(?Request $request = null): ?string
{
$session = self::session($request);
if (! $session instanceof Store) {
return null;
}
$value = $session->pull(WorkspaceContext::INTENDED_URL_SESSION_KEY);
if (! is_string($value)) {
return null;
}
$value = trim($value);
if ($value === '' || ! self::isAllowed($value)) {
return null;
}
return $value;
}
public static function clear(?Request $request = null): void
{
$session = self::session($request);
if (! $session instanceof Store) {
return;
}
$session->forget(WorkspaceContext::INTENDED_URL_SESSION_KEY);
}
private static function session(?Request $request = null): ?Store
{
$session = ($request && $request->hasSession())
? $request->session()
: session()->driver();
return $session instanceof Store ? $session : null;
}
private static function isAllowed(string $pathWithQuery): bool
{
if (str_contains($pathWithQuery, "\n") || str_contains($pathWithQuery, "\r")) {
return false;
}
if (preg_match('#^https?://#i', $pathWithQuery) === 1) {
return false;
}
if (str_starts_with($pathWithQuery, '//')) {
return false;
}
if (! str_starts_with($pathWithQuery, '/admin')) {
return false;
}
$path = parse_url($pathWithQuery, PHP_URL_PATH);
$path = '/'.ltrim((string) ($path ?? ''), '/');
if (in_array($path, ['/admin/choose-workspace', '/admin/no-access'], true)) {
return false;
}
return true;
}
}

View File

@ -1,47 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$driver = DB::getDriverName();
if ($driver !== 'pgsql') {
// SQLite doesn't enforce UUID types; other drivers are not supported in this app.
return;
}
DB::statement('ALTER TABLE inventory_links ALTER COLUMN source_id TYPE text USING source_id::text');
DB::statement('ALTER TABLE inventory_links ALTER COLUMN target_id TYPE text USING target_id::text');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$driver = DB::getDriverName();
if ($driver !== 'pgsql') {
return;
}
// Best-effort rollback: non-UUID identifiers are coerced.
$uuidRegex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$';
$sentinel = '00000000-0000-0000-0000-000000000000';
DB::statement(
"ALTER TABLE inventory_links ALTER COLUMN source_id TYPE uuid USING (CASE WHEN source_id ~* '{$uuidRegex}' THEN source_id::uuid ELSE '{$sentinel}'::uuid END)"
);
DB::statement(
"ALTER TABLE inventory_links ALTER COLUMN target_id TYPE uuid USING (CASE WHEN target_id IS NULL THEN NULL WHEN target_id ~* '{$uuidRegex}' THEN target_id::uuid ELSE NULL END)"
);
}
};

View File

@ -1,6 +0,0 @@
<div class="space-y-2">
<div class="text-sm text-gray-600 dark:text-gray-300">
Alerts is reserved for future work.
</div>
</div>

View File

@ -1,6 +0,0 @@
<div class="space-y-2">
<div class="text-sm text-gray-600 dark:text-gray-300">
Audit Log is reserved for future work.
</div>
</div>

View File

@ -1,36 +1,3 @@
<x-filament-panels::page> <x-filament-panels::page>
<x-filament::tabs label="Operations tabs">
<x-filament::tabs.item
:active="$this->activeTab === 'all'"
wire:click="$set('activeTab', 'all')"
>
All
</x-filament::tabs.item>
<x-filament::tabs.item
:active="$this->activeTab === 'active'"
wire:click="$set('activeTab', 'active')"
>
Active
</x-filament::tabs.item>
<x-filament::tabs.item
:active="$this->activeTab === 'succeeded'"
wire:click="$set('activeTab', 'succeeded')"
>
Succeeded
</x-filament::tabs.item>
<x-filament::tabs.item
:active="$this->activeTab === 'partial'"
wire:click="$set('activeTab', 'partial')"
>
Partial
</x-filament::tabs.item>
<x-filament::tabs.item
:active="$this->activeTab === 'failed'"
wire:click="$set('activeTab', 'failed')"
>
Failed
</x-filament::tabs.item>
</x-filament::tabs>
{{ $this->table }} {{ $this->table }}
</x-filament-panels::page> </x-filament-panels::page>

View File

@ -1,3 +1,137 @@
<x-filament-panels::page> <x-filament-panels::page>
{{ $this->infolist }} @php
$context = is_array($this->run->context ?? null) ? $this->run->context : [];
$targetScope = $context['target_scope'] ?? [];
$targetScope = is_array($targetScope) ? $targetScope : [];
$failures = is_array($this->run->failure_summary ?? null) ? $this->run->failure_summary : [];
@endphp
<div class="space-y-6">
<x-filament::section heading="Summary">
<div class="grid grid-cols-1 gap-3 text-sm text-gray-700 dark:text-gray-200 md:grid-cols-2">
<div>
<span class="text-gray-500 dark:text-gray-400">Run ID:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (int) $this->run->getKey() }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Workspace:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) ($this->run->workspace?->name ?? '—') }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Operation:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->type }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Initiator:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->initiator_name }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Status:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->status }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Outcome:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->outcome }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Started:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $this->run->started_at?->format('Y-m-d H:i') ?? '—' }}</span>
</div>
<div>
<span class="text-gray-500 dark:text-gray-400">Completed:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $this->run->completed_at?->format('Y-m-d H:i') ?? '—' }}</span>
</div>
</div>
</x-filament::section>
<x-filament::section heading="Target scope" :collapsed="false">
@php
$entraTenantId = $targetScope['entra_tenant_id'] ?? null;
$entraTenantName = $targetScope['entra_tenant_name'] ?? null;
$entraTenantId = is_string($entraTenantId) && $entraTenantId !== '' ? $entraTenantId : null;
$entraTenantName = is_string($entraTenantName) && $entraTenantName !== '' ? $entraTenantName : null;
@endphp
@if ($entraTenantId === null && $entraTenantName === null)
<div class="text-sm text-gray-600 dark:text-gray-300">
No target scope details were recorded for this run.
</div>
@else
<div class="flex flex-col gap-2 text-sm text-gray-700 dark:text-gray-200">
@if ($entraTenantName !== null)
<div>
<span class="text-gray-500 dark:text-gray-400">Entra tenant:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantName }}</span>
</div>
@endif
@if ($entraTenantId !== null)
<div>
<span class="text-gray-500 dark:text-gray-400">Entra tenant ID:</span>
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantId }}</span>
</div>
@endif
</div>
@endif
</x-filament::section>
<x-filament::section heading="Report">
@if ((string) $this->run->status !== 'completed')
<div class="text-sm text-gray-600 dark:text-gray-300">
Report unavailable while the run is in progress. Use “Refresh” to re-check stored status.
</div>
@elseif ((string) $this->run->outcome === 'succeeded')
<div class="text-sm text-gray-700 dark:text-gray-200">
No failures were reported.
</div>
@elseif ($failures === [])
<div class="text-sm text-gray-600 dark:text-gray-300">
Report unavailable. The run completed, but no failure details were recorded.
</div>
@else
<div class="space-y-3">
<div class="text-sm font-medium text-gray-900 dark:text-white">
Findings
</div>
<ul class="space-y-2 text-sm text-gray-700 dark:text-gray-200">
@foreach ($failures as $failure)
@php
$reasonCode = is_array($failure) ? ($failure['reason_code'] ?? null) : null;
$message = is_array($failure) ? ($failure['message'] ?? null) : null;
$reasonCode = is_string($reasonCode) && $reasonCode !== '' ? $reasonCode : null;
$message = is_string($message) && $message !== '' ? $message : null;
@endphp
@if ($reasonCode !== null || $message !== null)
<li class="rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
@if ($reasonCode !== null)
<div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
{{ $reasonCode }}
</div>
@endif
@if ($message !== null)
<div class="mt-1 text-sm text-gray-700 dark:text-gray-200">
{{ $message }}
</div>
@endif
</li>
@endif
@endforeach
</ul>
</div>
@endif
</x-filament::section>
</div>
</x-filament-panels::page> </x-filament-panels::page>

View File

@ -1,174 +0,0 @@
@php
use App\Filament\Pages\ChooseWorkspace;
use App\Models\Tenant;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
/** @var WorkspaceContext $workspaceContext */
$workspaceContext = app(WorkspaceContext::class);
$workspace = $workspaceContext->currentWorkspace(request());
$user = auth()->user();
$canSeeAllWorkspaceTenants = false;
if ($user instanceof User && $workspace) {
$roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
$canSeeAllWorkspaceTenants = WorkspaceMembership::query()
->where('workspace_id', (int) $workspace->getKey())
->where('user_id', (int) $user->getKey())
->whereIn('role', $roles)
->exists();
}
$tenants = collect();
if ($user instanceof User && $workspace) {
if ($canSeeAllWorkspaceTenants) {
$tenants = Tenant::query()
->where('workspace_id', (int) $workspace->getKey())
->orderBy('name')
->get();
} else {
$tenants = collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->filter(fn ($tenant): bool => $tenant instanceof Tenant && (int) $tenant->workspace_id === (int) $workspace->getKey())
->values();
}
}
$currentTenant = Filament::getTenant();
$currentTenantName = $currentTenant instanceof Tenant ? $currentTenant->getFilamentName() : null;
$path = '/'.ltrim(request()->path(), '/');
$isTenantScopedRoute = request()->route()?->hasParameter('tenant') || str_starts_with($path, '/admin/t/');
$lastTenantId = $workspaceContext->lastTenantId(request());
$canClearTenantContext = $currentTenantName !== null || $lastTenantId !== null;
@endphp
<div class="flex items-center gap-3">
<x-filament::dropdown placement="bottom-start" teleport>
<x-slot name="trigger">
<x-filament::button
color="gray"
outlined
size="sm"
icon="heroicon-o-squares-2x2"
>
{{ $workspace?->name ?? 'Select workspace' }}
</x-filament::button>
</x-slot>
<x-filament::dropdown.list>
<a
href="{{ ChooseWorkspace::getUrl() }}"
class="block px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-gray-800"
>
Switch workspace
</a>
</x-filament::dropdown.list>
</x-filament::dropdown>
<div class="h-4 w-px bg-gray-200 dark:bg-gray-700"></div>
@if (! $workspace)
<div class="flex items-center gap-2">
<x-filament::button
color="gray"
outlined
size="sm"
icon="heroicon-o-building-office-2"
disabled
>
Select tenant
</x-filament::button>
<div class="text-xs text-gray-500 dark:text-gray-400">Choose a workspace first.</div>
</div>
@elseif ($isTenantScopedRoute)
<x-filament::button
color="gray"
outlined
size="sm"
icon="heroicon-o-building-office-2"
disabled
>
{{ $currentTenantName ?? 'Tenant' }}
</x-filament::button>
@else
<x-filament::dropdown placement="bottom-start" teleport>
<x-slot name="trigger">
<x-filament::button
color="gray"
outlined
size="sm"
icon="heroicon-o-building-office-2"
>
{{ $currentTenantName ?? 'Select tenant' }}
</x-filament::button>
</x-slot>
<x-filament::dropdown.list>
<div class="px-3 py-2 space-y-2" x-data="{ query: '' }">
<div class="text-xs font-medium text-gray-500 dark:text-gray-400">
Tenant context
@if ($canSeeAllWorkspaceTenants)
<span class="text-gray-400">· all workspace tenants</span>
@endif
</div>
@if ($tenants->isEmpty())
<div class="text-xs text-gray-500 dark:text-gray-400">
{{ $canSeeAllWorkspaceTenants ? 'No tenants exist in this workspace.' : 'No tenants you can access in this workspace.' }}
</div>
@else
<div class="space-y-2">
<input
type="text"
class="fi-input fi-text-input w-full"
placeholder="Search tenants…"
x-model="query"
/>
<div class="max-h-64 overflow-auto rounded-lg border border-gray-200 dark:border-gray-700">
@foreach ($tenants as $tenant)
<form method="POST" action="{{ route('admin.select-tenant') }}">
@csrf
<input type="hidden" name="tenant_id" value="{{ (int) $tenant->getKey() }}" />
<button
type="submit"
class="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 dark:hover:bg-gray-800"
data-search="{{ (string) str($tenant->getFilamentName())->lower() }}"
x-show="query === '' || ($el.dataset.search ?? '').includes(query.toLowerCase())"
>
{{ $tenant->getFilamentName() }}
</button>
</form>
@endforeach
</div>
@if ($canClearTenantContext)
<form method="POST" action="{{ route('admin.clear-tenant-context') }}">
@csrf
<x-filament::button color="gray" size="sm" outlined>
Clear tenant context
</x-filament::button>
</form>
@endif
<div class="text-xs text-gray-500 dark:text-gray-400">
Switching tenants is explicit. Canonical monitoring URLs do not change tenant context.
</div>
</div>
@endif
</div>
</x-filament::dropdown.list>
</x-filament::dropdown>
@endif
</div>

View File

@ -25,7 +25,7 @@
<form method="POST" action="{{ route('admin.switch-workspace') }}" class="space-y-2"> <form method="POST" action="{{ route('admin.switch-workspace') }}" class="space-y-2">
@csrf @csrf
<div class="text-xs font-medium text-gray-500 dark:text-gray-400">Switch workspace</div> <div class="text-xs font-medium text-gray-500 dark:text-gray-400">Workspace</div>
<select <select
name="workspace_id" name="workspace_id"
@ -40,7 +40,7 @@ class="fi-input fi-select w-full"
@endforeach @endforeach
</select> </select>
<div class="text-xs text-gray-500 dark:text-gray-400">Select a workspace to switch context.</div> <div class="text-xs text-gray-500 dark:text-gray-400">Switch workspace</div>
</form> </form>
</div> </div>
</x-filament::dropdown.list> </x-filament::dropdown.list>

View File

@ -1,55 +0,0 @@
@php
/** @var ?\App\Models\Tenant $tenant */
/** @var \Illuminate\Support\Collection<int, \App\Models\OperationRun> $runs */
/** @var string $operationsIndexUrl */
@endphp
<div class="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-800 dark:bg-gray-900">
<div class="flex items-center justify-between gap-3">
<div class="text-sm font-semibold">Recent operations</div>
<a
href="{{ $operationsIndexUrl }}"
class="text-sm font-medium text-primary-600 hover:text-primary-500 dark:text-primary-400 dark:hover:text-primary-300"
>
View all operations
</a>
</div>
@if ($runs->isEmpty())
<div class="mt-3 text-sm text-gray-500 dark:text-gray-400">
No operations yet.
</div>
@else
<ul class="mt-3 divide-y divide-gray-100 dark:divide-gray-800">
@foreach ($runs as $run)
<li class="flex items-center justify-between gap-3 py-2">
<div class="min-w-0">
<div class="truncate text-sm font-medium">
{{ \App\Support\OperationCatalog::label((string) $run->type) }}
</div>
<div class="text-xs text-gray-500 dark:text-gray-400">
{{ $run->created_at?->diffForHumans() ?? '—' }}
</div>
</div>
<div class="flex shrink-0 items-center gap-3">
<div class="text-right text-xs text-gray-600 dark:text-gray-300">
<div>{{ (string) $run->status }}</div>
<div>{{ (string) $run->outcome }}</div>
</div>
<a
href="{{ \App\Support\OperationRunLinks::tenantlessView($run) }}"
class="text-sm font-medium text-primary-600 hover:text-primary-500 dark:text-primary-400 dark:hover:text-primary-300"
>
View
</a>
</div>
</li>
@endforeach
</ul>
@endif
</div>

View File

@ -0,0 +1,60 @@
<div class="space-y-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="bg-white p-4 rounded shadow">
<h3 class="font-bold text-lg mb-2">Summary</h3>
<dl class="grid grid-cols-2 gap-x-4 gap-y-2">
<dt class="text-gray-600">Type:</dt>
<dd>{{ $run->type }}</dd>
<dt class="text-gray-600">Status:</dt>
<dd>{{ $run->status }}</dd>
<dt class="text-gray-600">Outcome:</dt>
<dd>{{ $run->outcome }}</dd>
<dt class="text-gray-600">Initiator:</dt>
<dd>{{ $run->initiator_name }}</dd>
</dl>
</div>
<div class="bg-white p-4 rounded shadow">
<h3 class="font-bold text-lg mb-2">Timing</h3>
<dl class="grid grid-cols-2 gap-x-4 gap-y-2">
<dt class="text-gray-600">Created:</dt>
<dd>{{ $run->created_at }}</dd>
<dt class="text-gray-600">Started:</dt>
<dd>{{ $run->started_at ?? '-' }}</dd>
<dt class="text-gray-600">Completed:</dt>
<dd>{{ $run->completed_at ?? '-' }}</dd>
</dl>
</div>
</div>
@if(!empty($run->summary_counts))
<div class="bg-white p-4 rounded shadow">
<h3 class="font-bold text-lg mb-2">Counts</h3>
<pre class="bg-gray-100 p-2 rounded text-sm overflow-auto">{{ json_encode($run->summary_counts, JSON_PRETTY_PRINT) }}</pre>
</div>
@endif
@if(!empty($run->failure_summary))
<div class="bg-white p-4 rounded shadow border-l-4 border-red-500">
<h3 class="font-bold text-lg mb-2 text-red-700">Failures</h3>
<div class="space-y-2">
@foreach($run->failure_summary as $failure)
<div class="bg-red-50 p-2 rounded">
<div class="font-mono text-xs text-red-800">{{ $failure['code'] ?? 'UNKNOWN' }}</div>
<div class="text-sm text-red-900">{{ $failure['message'] ?? 'Unknown error' }}</div>
</div>
@endforeach
</div>
</div>
@endif
<div class="bg-white p-4 rounded shadow">
<h3 class="font-bold text-lg mb-2">Context</h3>
<pre class="bg-gray-100 p-2 rounded text-sm overflow-auto">{{ json_encode($run->context, JSON_PRETTY_PRINT) }}</pre>
</div>
</div>

View File

@ -3,7 +3,6 @@
use App\Filament\Pages\TenantDashboard; use App\Filament\Pages\TenantDashboard;
use App\Http\Controllers\AdminConsentCallbackController; use App\Http\Controllers\AdminConsentCallbackController;
use App\Http\Controllers\Auth\EntraController; use App\Http\Controllers\Auth\EntraController;
use App\Http\Controllers\ClearTenantContextController;
use App\Http\Controllers\RbacDelegatedAuthController; use App\Http\Controllers\RbacDelegatedAuthController;
use App\Http\Controllers\SelectTenantController; use App\Http\Controllers\SelectTenantController;
use App\Http\Controllers\SwitchWorkspaceController; use App\Http\Controllers\SwitchWorkspaceController;
@ -102,10 +101,6 @@
Route::middleware(['web', 'auth', 'ensure-correct-guard:web', 'ensure-workspace-selected']) Route::middleware(['web', 'auth', 'ensure-correct-guard:web', 'ensure-workspace-selected'])
->post('/admin/select-tenant', SelectTenantController::class) ->post('/admin/select-tenant', SelectTenantController::class)
->name('admin.select-tenant'); ->name('admin.select-tenant');
Route::middleware(['web', 'auth', 'ensure-correct-guard:web', 'ensure-workspace-selected'])
->post('/admin/clear-tenant-context', ClearTenantContextController::class)
->name('admin.clear-tenant-context');
Route::bind('workspace', function (string $value): Workspace { Route::bind('workspace', function (string $value): Workspace {
/** @var WorkspaceResolver $resolver */ /** @var WorkspaceResolver $resolver */
$resolver = app(WorkspaceResolver::class); $resolver = app(WorkspaceResolver::class);
@ -145,63 +140,6 @@
DisableBladeIconComponents::class, DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class, DispatchServingFilamentEvent::class,
FilamentAuthenticate::class, FilamentAuthenticate::class,
'ensure-workspace-selected',
'ensure-filament-tenant-selected',
])
->get('/admin/t/{tenant}/operations', fn () => redirect()->route('admin.operations.index'))
->name('admin.operations.legacy-index');
Route::middleware([
'web',
'panel:admin',
'ensure-correct-guard:web',
DenyNonMemberTenantAccess::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
FilamentAuthenticate::class,
'ensure-workspace-selected',
'ensure-filament-tenant-selected',
])
->get('/admin/operations', \App\Filament\Pages\Monitoring\Operations::class)
->name('admin.operations.index');
Route::middleware([
'web',
'panel:admin',
'ensure-correct-guard:web',
DenyNonMemberTenantAccess::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
FilamentAuthenticate::class,
'ensure-workspace-selected',
'ensure-filament-tenant-selected',
])
->get('/admin/alerts', \App\Filament\Pages\Monitoring\Alerts::class)
->name('admin.monitoring.alerts');
Route::middleware([
'web',
'panel:admin',
'ensure-correct-guard:web',
DenyNonMemberTenantAccess::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
FilamentAuthenticate::class,
'ensure-workspace-selected',
'ensure-filament-tenant-selected',
])
->get('/admin/audit-log', \App\Filament\Pages\Monitoring\AuditLog::class)
->name('admin.monitoring.audit-log');
Route::middleware([
'web',
'panel:admin',
'ensure-correct-guard:web',
DenyNonMemberTenantAccess::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
FilamentAuthenticate::class,
'ensure-filament-tenant-selected',
]) ])
->get('/admin/operations/{run}', \App\Filament\Pages\Operations\TenantlessOperationRunViewer::class) ->get('/admin/operations/{run}', \App\Filament\Pages\Operations\TenantlessOperationRunViewer::class)
->name('admin.operations.view'); ->name('admin.operations.view');

View File

@ -1,35 +0,0 @@
# Specification Quality Checklist: Workspace-first Navigation & Monitoring Hub
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-02-06
**Feature**: [specs/077-workspace-nav-monitoring-hub/spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
- Validation pass on first iteration.
- URLs are treated as product behavior (not implementation details).

View File

@ -1,69 +0,0 @@
# Contracts — Routes & Semantics (077)
**Spec**: [specs/077-workspace-nav-monitoring-hub/spec.md](../spec.md)
This feature is an admin UI/navigation refactor. Contracts are expressed as web route semantics + access rules.
## Canonical routes
### Workspace context
- `GET /admin/choose-workspace`
- Purpose: select active workspace context
- Access: authenticated user
- Visibility: shows only workspaces where the user is a member
- `POST /admin/switch-workspace`
- Purpose: update workspace context
- Access: authenticated user
- Security:
- If user is not a member of the selected workspace → 404 (deny-as-not-found)
### Workspace management (CRUD)
- `GET /admin/workspaces`
- `GET /admin/workspaces/{workspace}`
- `GET /admin/workspaces/{workspace}/edit`
- `GET /admin/workspaces/create`
Contract semantics:
- Workspace context is optional on `/admin/workspaces` (Global Mode).
- Index lists only workspaces the user is a member of.
- If user attempts to access a workspace record they are not a member of → 404 (deny-as-not-found)
- Workspace creation is self-serve for authenticated users (policy-driven).
- If user is a member but lacks the required capability for a protected action/screen (edit/membership management) → 403
- If user is authorized → normal Filament behavior
### Monitoring hub — Operations
- `GET /admin/operations`
- Canonical operations index (tenantless URL)
- Behavior:
- If tenant context is active: default filter state = current tenant (removable)
- If tenant context is not active: workspace-wide list
- `GET /admin/operations/{run}`
- Canonical run deep link
- Security:
- If run belongs to a workspace the user is not a member of → 404
### Monitoring hub — Reserved surfaces (placeholders)
- `GET /admin/alerts`
- Reserved placeholder page
- Access: workspace members (workspace context required)
- `GET /admin/audit-log`
- Reserved placeholder page
- Access: workspace members (workspace context required)
## Status code rules (summary)
- Non-member / not entitled to the workspace scope → 404
- Member but missing capability (workspace-scoped protected actions) → 403
## Non-leakage requirements
- Global search must not list inaccessible workspaces/tenants/runs.
- Navigation labels and groups must not imply the existence of admin-only surfaces.

View File

@ -1,66 +0,0 @@
# Data Model — Workspace-first Navigation & Monitoring Hub (077)
**Date**: 2026-02-06
**Spec**: [specs/077-workspace-nav-monitoring-hub/spec.md](spec.md)
This feature is primarily information architecture + context enforcement. No new tables are required; the design depends on existing entities and their relationships.
## Entities
### Workspace
Represents a portfolio / customer container (primary context).
- Key fields (existing, relevant):
- `id`
- `name`
- `slug` (optional)
- `archived_at` (nullable)
### WorkspaceMembership
Entitlement relationship between a user and a workspace.
- Key fields (existing, relevant):
- `workspace_id`
- `user_id`
- `role` (e.g. owner/operator/etc; actual role semantics are managed by the capability resolver)
### Tenant (Managed Tenant)
Represents a Microsoft/Intune tenant belonging to a workspace (secondary context via Filament tenancy).
- Key fields (existing, relevant):
- `id`
- `workspace_id` (foreign key to Workspace)
- `external_id` (used in Filament tenancy route `/admin/t/{tenant}`)
- `status` (e.g., active)
### OperationRun
Canonical monitoring record (workspace-level entity; may optionally be linked to a tenant).
- Key fields (existing, relevant):
- `id`
- `workspace_id` (required for access control)
- `tenant_id` (nullable; used for default filtering and “recent operations”)
- `type`, `status`, `outcome`
- timestamps (created/started/completed)
- `context` (JSON)
## Relationships
- Workspace has many WorkspaceMemberships.
- Workspace has many Tenants.
- Workspace has many OperationRuns.
- Tenant belongs to Workspace.
- OperationRun belongs to Workspace.
- OperationRun optionally belongs to Tenant.
## Invariants / Rules enforced by this feature
- Workspace context (`current_workspace_id`) is required for workspace-scoped navigation and access control.
- Tenant context must be consistent with workspace context:
- If tenant is not in current workspace, tenant context is cleared (continue tenantless).
- OperationRun access is controlled by membership in the runs `workspace_id`.

View File

@ -1,215 +0,0 @@
# Implementation Plan: Workspace-first Navigation & Monitoring Hub
**Branch**: `077-workspace-nav-monitoring-hub` | **Date**: 2026-02-06 | **Spec**: [specs/077-workspace-nav-monitoring-hub/spec.md](spec.md)
**Input**: Feature specification from [specs/077-workspace-nav-monitoring-hub/spec.md](spec.md)
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/scripts/` for helper scripts.
## Summary
Resolve workspace navigation ambiguity and formalize a workspace-first context model:
- Unambiguous labels: **Switch workspace** (`/admin/choose-workspace`) vs **Manage workspaces** (`/admin/workspaces`).
- Monitoring → **Operations** remains canonical and tenantless (`/admin/operations`, `/admin/operations/{run}`).
- Tenant context influences Operations only via **server-side default filter state** (removable), never via routing.
- Strict non-leaking security semantics:
- Non-member workspace scope → 404 (deny-as-not-found)
- Workspace member missing capability (protected actions/screens) → 403
- Accessing a workspace record outside membership → 404 (deny-as-not-found)
Supporting artifacts:
- [research.md](research.md)
- [data-model.md](data-model.md)
- [contracts/routes.md](contracts/routes.md)
- [quickstart.md](quickstart.md)
## Technical Context
**Language/Version**: PHP 8.4.x
**Primary Dependencies**: Laravel 12, Filament v5, Livewire v4
**Storage**: PostgreSQL (Sail)
**Testing**: Pest v4
**Target Platform**: Web (Filament admin panels)
**Project Type**: Laravel monolith
**Performance Goals**: Operations pages remain DB-only at render; list/detail stay fast on large run tables (pagination + indexed filters)
**Constraints**: Filament-native patterns only; canonical URLs must not depend on tenant context; strict 404/403 non-leakage semantics
**Scale/Scope**: Multi-workspace MSP use; many tenants and many operation runs
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
- Inventory-first: N/A (no inventory semantics changes)
- Read/write separation: PASS (no write operations introduced)
- Graph contract path: N/A (no Graph calls)
- Deterministic capabilities: PASS (capability gating uses existing resolver/registry patterns)
- RBAC-UX: PASS (explicit 404 vs 403 rules)
- RBAC-UX destructive confirmation: N/A (no destructive actions introduced)
- RBAC-UX global search: N/A (no new searchable resources; no changes to global search)
- Tenant isolation: PASS (workspace membership is isolation boundary; tenant context auto-cleared when invalid)
- Run observability: N/A (no new operations/jobs)
- Automation: N/A
- Data minimization: N/A
- Badge semantics (BADGE-001): N/A
## Project Structure
### Documentation (this feature)
```text
specs/077-workspace-nav-monitoring-hub/
├── spec.md
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── contracts/
│ └── routes.md
└── checklists/
└── requirements.md
```
### Source Code (repository root)
```text
app/
├── Filament/
│ ├── Pages/
│ │ └── ChooseWorkspace.php
│ └── Resources/
│ ├── OperationRunResource.php
│ └── OperationRunResource/
│ └── Pages/
│ └── ListOperationRuns.php
├── Http/
│ └── Middleware/
│ └── EnsureWorkspaceSelected.php
├── Providers/
│ └── Filament/
│ └── AdminPanelProvider.php
└── Support/
└── Middleware/
└── EnsureFilamentTenantSelected.php
resources/
└── views/
└── filament/
└── partials/
└── workspace-switcher.blade.php
routes/
└── web.php
tests/
└── Feature/
└── (new tests for navigation labels + 404/403 + operations default filter)
```
**Structure Decision**: Laravel monolith using Filament resources/pages and Laravel middleware.
## Complexity Tracking
No constitution violations.
## Phase 0 — Outline & Research (complete)
All unknowns/decisions have been resolved and recorded:
- Repo reality + ambiguity sources + decisions D1D4: [research.md](research.md)
- No remaining NEEDS CLARIFICATION items in the spec.
## Phase 1 — Design & Contracts (complete)
- Data model: no new tables/columns required; behavior is implemented via middleware + Filament config: [data-model.md](data-model.md)
- Route/security contracts: [contracts/routes.md](contracts/routes.md)
- Manual validation steps + suggested test filters: [quickstart.md](quickstart.md)
## Phase 2 — Implementation Plan (ready for tasks)
### Step 1 — Navigation labels: “one label, one meaning”
- Update admin navigation to include:
- **Switch workspace** (topbar context switcher) → `/admin/choose-workspace`
- **Manage workspaces** (sidebar Settings) → `/admin/workspaces`
- Remove/replace any navigation items labeled only “Workspaces”.
Implementation targets:
- Update [app/Support/Middleware/EnsureFilamentTenantSelected.php](../../app/Support/Middleware/EnsureFilamentTenantSelected.php) navigation builder:
- Change the label from `Workspaces` to `Switch workspace` for the choose-workspace link.
- Ensure this fallback navigation does not accidentally imply CRUD management.
- Update [app/Providers/Filament/AdminPanelProvider.php](../../app/Providers/Filament/AdminPanelProvider.php) nav item label for workspace CRUD to `Manage workspaces`.
- Update [resources/views/filament/partials/workspace-switcher.blade.php](../../resources/views/filament/partials/workspace-switcher.blade.php) text/links to consistently say “Switch workspace”.
- Add reserved Monitoring navigation surfaces for **Alerts** and **Audit Log** as placeholder pages (non-functional “coming soon”) to satisfy FR-011.
### Step 2 — Enforce workspace-scoped RBAC semantics for `/admin/workspaces`
- `/admin/workspaces` stays tenantless and is **Global Mode** (workspace-optional).
- Enforce strict non-leakage semantics:
- Non-member attempting to access a workspace record → **404** (deny-as-not-found)
- Member missing required capability for protected actions/screens → **403**
Implementation targets:
- Scope the Workspaces query (index) to only workspaces the user is a member of.
- Ensure `WorkspacePolicy` returns 404 semantics for non-members (record access).
- Workspace creation is self-serve (policy-driven). Gate edit/membership-management behind canonical workspace capabilities (no raw strings).
- Hide “Manage workspaces” navigation unless the user can manage something workspace-admin related (capability-based).
### Step 3 — Workspace selection redirect + return-to-intended
Requirement: visiting any workspace-scoped page without a selected workspace MUST redirect to `/admin/choose-workspace` and then return to the originally requested URL.
Implementation targets:
- Update [app/Http/Middleware/EnsureWorkspaceSelected.php](../../app/Http/Middleware/EnsureWorkspaceSelected.php):
- When redirecting to `/admin/choose-workspace`, store the intended URL (path + query) in session.
- Preserve the existing exemptions for auth routes and for `/admin/operations/{run}` and Livewire update referers.
- Update both workspace-selection entrypoints to honor intended URLs:
- [app/Filament/Pages/ChooseWorkspace.php](../../app/Filament/Pages/ChooseWorkspace.php)
- [app/Http/Controllers/SwitchWorkspaceController.php](../../app/Http/Controllers/SwitchWorkspaceController.php)
- After setting the workspace, redirect to the stored intended URL (if present and safe), otherwise keep the existing behavior (onboarding / choose-tenant / tenant dashboard).
### Step 4 — Auto-clear invalid tenant context on workspace change
Requirement: if tenant context is active but does not belong to the current workspace, auto-clear tenant context and continue on tenantless workspace pages.
Implementation targets:
- In [app/Support/Middleware/EnsureFilamentTenantSelected.php](../../app/Support/Middleware/EnsureFilamentTenantSelected.php) (or a dedicated middleware used for tenantless pages):
- Detect a persisted Filament tenant that does not match `WorkspaceContext::currentWorkspaceId()`.
- Clear the persisted Filament tenant context (confirm the correct Filament v5 mechanism during implementation).
### Step 5 — Operations: move tenant scoping from query to removable default filter
Requirement: `/admin/operations` stays canonical; if tenant context is active, default to that tenant using server-side default filter state with a visible removable chip.
Implementation targets:
- Update [app/Filament/Resources/OperationRunResource.php](../../app/Filament/Resources/OperationRunResource.php):
- Remove tenant-context filtering from `getEloquentQuery()`.
- Update [app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php](../../app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php):
- Add a tenant filter (select) over available tenants in the current workspace.
- Default the filter state from the current tenant context when valid.
- Ensure the filter chip is visible and can be cleared to view workspace-wide operations.
### Step 6 — Tests (Pest) + formatting
Add/adjust tests to cover the strict semantics:
- Navigation labels: “Switch workspace” vs “Manage workspaces” (no ambiguous “Workspaces”).
- `/admin/workspaces`:
- non-member record access → 404
- member missing capability for a protected action/screen → 403
- EnsureWorkspaceSelected:
- visiting `/admin/operations` without workspace → redirects to choose-workspace
- after selecting workspace → returns to intended URL
- Operations default filter:
- with tenant context active → tenant filter default set
- clearing filter → shows workspace-wide results
Tooling:
- Run `./vendor/bin/sail bin pint --dirty`.
- Run focused tests via `./vendor/bin/sail artisan test --compact --filter=...`.

View File

@ -1,50 +0,0 @@
# Quickstart — Workspace-first Navigation & Monitoring Hub (077)
**Audience**: Devs and reviewers validating the feature on staging/local
**Spec**: [specs/077-workspace-nav-monitoring-hub/spec.md](spec.md)
## Local setup
- Start containers: `./vendor/bin/sail up -d`
- Install dependencies if needed: `./vendor/bin/sail composer install` and `./vendor/bin/sail npm install`
- Run migrations: `./vendor/bin/sail artisan migrate`
## Manual validation checklist
### Navigation separation
1. Open `/admin` and sign in.
2. In the user menu, confirm there is an explicit entry labeled **"Switch workspace"** that navigates to `/admin/choose-workspace`.
3. In the sidebar, confirm **"Manage workspaces"** exists only when authorized.
4. Confirm there is no navigation item labeled simply **"Workspaces"** that ambiguously points to both concepts.
### Operations canonical + default tenant filter
1. Visit `/admin/operations` with no tenant context selected.
- Expect: page loads and shows workspace-wide runs.
2. Activate tenant context (`/admin/t/{tenant}`), then navigate to `/admin/operations`.
- Expect: default tenant filter applied, visible filter chip, chip can be cleared.
3. Visit a run deep link `/admin/operations/{run}` from both tenantless and tenant context.
- Expect: same canonical page, no tenant-route dependency.
### Security semantics
- Non-member accessing operations for another workspace: expect **404**.
- Workspace member but missing capability for a protected action/screen: expect **403**.
- Accessing `/admin/workspaces` for a workspace you are not a member of: expect **404**.
## Test execution
Run focused tests:
- US1 (nav separation): `./vendor/bin/sail artisan test --compact --filter=WorkspaceNavigationHub`
- US2 (canonical ops URLs): `./vendor/bin/sail artisan test --compact --filter=OperationsCanonicalUrls`
- US3 (non-leakage): `./vendor/bin/sail artisan test --compact --filter=NonLeakageWorkspaceOperations`
Run a targeted suite for the feature area:
- `./vendor/bin/sail artisan test --compact tests/Feature/Workspaces tests/Feature/Monitoring tests/Feature/OpsUx`
Run formatting before finalizing:
- `./vendor/bin/sail pint --dirty`

View File

@ -1,58 +0,0 @@
# Research — Workspace-first Navigation & Monitoring Hub (077)
**Date**: 2026-02-06
**Branch**: 077-workspace-nav-monitoring-hub
**Spec**: [specs/077-workspace-nav-monitoring-hub/spec.md](spec.md)
## Repo Reality Check (what exists today)
- Admin panel exists at `/admin` via [app/Providers/Filament/AdminPanelProvider.php](../../app/Providers/Filament/AdminPanelProvider.php).
- System panel exists at `/system` with a separate auth guard (`platform`) via [app/Providers/Filament/SystemPanelProvider.php](../../app/Providers/Filament/SystemPanelProvider.php).
- Workspace context selection exists:
- Page `/admin/choose-workspace` via [app/Filament/Pages/ChooseWorkspace.php](../../app/Filament/Pages/ChooseWorkspace.php)
- POST switch endpoint `/admin/switch-workspace` via [routes/web.php](../../routes/web.php)
- Workspace switcher UI in the user menu via [resources/views/filament/partials/workspace-switcher.blade.php](../../resources/views/filament/partials/workspace-switcher.blade.php)
- Navigation ambiguity is currently real:
- When no tenant is selected, navigation is replaced with a single item labeled **"Workspaces"** linking to the choose-workspace page via [app/Support/Middleware/EnsureFilamentTenantSelected.php](../../app/Support/Middleware/EnsureFilamentTenantSelected.php).
- Separately, the sidebar includes another **"Workspaces"** item linking to `/admin/workspaces` (workspace CRUD) via [app/Providers/Filament/AdminPanelProvider.php](../../app/Providers/Filament/AdminPanelProvider.php).
- Operations is already canonical and tenantless:
- Resource slug is `/admin/operations` via [app/Filament/Resources/OperationRunResource.php](../../app/Filament/Resources/OperationRunResource.php).
- Detail page is `/admin/operations/{record}`.
## Decisions (resolved)
### D1 — Manage workspaces stays on `/admin/workspaces` and follows workspace RBAC semantics (404 for non-members, 403 for missing capability)
- Decision: Treat `/admin/workspaces` as a **workspace-scoped** management surface in the tenant plane (`/admin`, Entra users):
- Non-members (or out-of-scope workspace records) → **404** (deny-as-not-found)
- Members missing required capabilities for protected actions/screens → **403**
- Rationale: Aligns with the constitution RBAC-UX model (membership is the isolation boundary; capability denial is 403 after membership is established) while still preventing cross-workspace leakage.
- Alternatives considered:
- Move management into `/system` panel: rejected because this feature targets the tenant plane IA. (If workspace CRUD becomes platform-admin only later, that should be handled as a separate migration spec.)
### D2 — Tenant context influences Operations via server-side default filter state, not querystring
- Decision: Apply the tenant default filter server-side while keeping the canonical URL `/admin/operations` unchanged.
- Rationale: Matches Spec 077 clarification (Q2=A). Prevents link-sharing surprises and keeps canonical monitoring routes stable.
- Alternatives considered:
- Querystring-based default filtering (e.g. `?tenant_id=`): rejected as it makes filtered URLs the de-facto navigation target.
### D3 — Missing workspace context redirects to `/admin/choose-workspace` and returns to the requested URL
- Decision: When a workspace-scoped page is visited without an active workspace selection, redirect to `/admin/choose-workspace` and then return.
- Rationale: Matches Spec 077 clarification (Q3=A) and aligns with existing `/admin` root override behavior in [routes/web.php](../../routes/web.php).
### D4 — Invalid tenant context (tenant not in current workspace) is auto-cleared
- Decision: If tenant context is active but does not belong to the current workspace, clear tenant context and continue on workspace-level pages.
- Rationale: Matches Spec 077 clarification (Q4=A). Reduces “ghost tenant” behavior after a workspace switch.
- Alternatives considered:
- Hard 404: rejected as too confusing during normal context switching.
## Key Implementation Implications (for planning)
- **Rename navigation labels** to satisfy “one label, one meaning”:
- The “Workspaces” navigation item that points to the choose-workspace page must become **"Switch workspace"**.
- The “Workspaces” navigation item that points to CRUD must become **"Manage workspaces"** and be capability-gated with workspace RBAC semantics (404 for non-members; 403 for missing capability).
- **Operations filter chip/removal**: current behavior filters by `Tenant::current()` inside `OperationRunResource::getEloquentQuery()`, which is not user-removable. The plan should move this behavior into a table filter with default state.
- **No render-time external calls**: monitoring pages must remain DB-only at render (already consistent with constitution).

View File

@ -1,164 +0,0 @@
# Feature Specification: Workspace-first Navigation & Monitoring Hub
**Feature Branch**: `077-workspace-nav-monitoring-hub`
**Created**: 2026-02-06
**Status**: Implemented
**Input**: User description: "Workspace-first navigation and monitoring hub for an enterprise admin suite: remove workspace navigation ambiguity, lock canonical operations deep links, apply tenant context only as default filters, and enforce strict 404/403 access semantics without information leakage."
## Clarifications
### Session 2026-02-06
- Q: What is the authorization plane + status-code rule for `/admin/workspaces` ("Manage workspaces")? → A: Tenant plane (`/admin`, Entra users). `/admin/workspaces` is **Global Mode** (workspace-optional). Index lists only the users workspaces; per-record access for non-members is 404 (deny-as-not-found); protected actions/screens return 403 when unauthorized.
- Q: Should `/admin/workspaces` require an active `current_workspace_id`? → A: No. `/admin/workspaces` is **Global Mode** (workspace-optional). The index lists only workspaces the user is a member of; per-record access for non-members remains 404.
- Q: How should the tenant-context default filter on `/admin/operations` be implemented? → A: Server-side default state with a removable filter chip; URL remains `/admin/operations`.
- Q: What happens when a user visits a workspace-scoped page (e.g. `/admin/operations`) with no `current_workspace_id` selected? → A: Redirect to `/admin/choose-workspace` and return to the originally requested URL after selection.
- Q: If tenant context is active but the tenant is not in the current workspace (e.g., user switches workspaces), what should happen? → A: Auto-clear tenant context and continue on tenantless workspace pages.
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Switch workspace without ambiguity (Priority: P1)
As an operator/admin, I need to switch my active workspace (portfolio) using a clear, single-purpose entry point, so that I never confuse "switch workspace" with "manage workspaces".
**Why this priority**: Workspace context is foundational. If its confusing, every other module becomes harder to use and support.
**Independent Test**: A user can find "Switch workspace", select a workspace they are a member of, and the application context updates while workspace management remains separate.
**Acceptance Scenarios**:
1. **Given** I am signed in and belong to multiple workspaces, **When** I choose "Switch workspace", **Then** I see only workspaces I am a member of and can select one.
2. **Given** I can manage workspaces, **When** I open "Manage workspaces", **Then** I can access workspace CRUD screens and breadcrumbs stay within the management area.
3. **Given** I cannot manage workspaces, **When** I look at navigation, **Then** I do not see "Manage workspaces".
---
### User Story 2 - Use Monitoring hub from canonical links (Priority: P2)
As an operator, I need monitoring pages (starting with Operations) to be reachable via stable, shareable links that never depend on tenant context, so that support, alerts, and notifications can deep-link reliably.
**Why this priority**: Monitoring must be dependable across contexts; deep links are critical for incident response and support.
**Independent Test**: Visiting the canonical operations URLs works with and without tenant context, and the system enforces membership checks.
**Acceptance Scenarios**:
1. **Given** I am a member of a workspace, **When** I visit `/admin/operations`, **Then** I can view a workspace-wide list of operations.
2. **Given** I have an active tenant context, **When** I visit `/admin/operations`, **Then** operations are pre-filtered to that tenant but the URL remains `/admin/operations`.
3. **Given** I have a run link `/admin/operations/{run}`, **When** I open it, **Then** I see the run detail regardless of tenant context.
---
### User Story 3 - Navigate and search without leaking inaccessible data (Priority: P3)
As a user, I should never learn about workspaces/tenants/runs I cannot access through navigation labels, breadcrumbs, counts, or global search results.
**Why this priority**: Preventing information leakage is a core enterprise requirement and reduces risk in multi-tenant MSP environments.
**Independent Test**: An unauthorized user receives not-found responses for out-of-scope resources and does not see them in search.
**Acceptance Scenarios**:
1. **Given** I am not a member of a workspace, **When** I attempt to access that workspaces monitoring data or runs, **Then** I receive a not-found response.
2. **Given** I am a workspace member but lack a capability for a protected workspace-scoped screen or action, **When** I attempt to access it directly, **Then** I receive a forbidden response.
3. **Given** I use global search, **When** I search for entities outside my scope, **Then** they do not appear in results (no partial hints).
### Edge Cases
- User is a member of zero workspaces.
- User loses workspace membership while having an active session.
- Tenant context is active but the tenant does not belong to the current workspace.
- A run is referenced by an external deep link after it was deleted or moved.
- User can view monitoring but cannot perform mutations (e.g., cancel/retry) if those actions exist.
## Requirements *(mandatory)*
**Constitution alignment (required):** This feature changes navigation and authorization behavior but does not introduce new external API calls or background jobs. Any mutation actions added later (e.g., cancel/retry) must follow the platforms safety gates (confirmation/audit) and be covered by authorization tests.
**Constitution alignment (RBAC-UX):**
- **Authorization plane(s) involved**:
- **Tenant plane (Entra users)** only.
- **Platform plane (`/system`) is out of scope** for this feature.
- **Authorization planes**:
- Workspace-level pages (e.g., monitoring hub, workspace management) are governed by workspace membership and workspace capabilities.
- Tenant context is secondary and must not change canonical routing for monitoring pages.
- **Isolation model note (workspace scope)**:
- “Workspace-scoped” monitoring is an explicit, access-checked aggregation scope over the managed tenants that belong to the selected workspace.
- All reads remain bounded to the current workspace; there is no cross-workspace monitoring view in this feature.
- **404 vs 403 semantics (strict)**:
- Non-member / not entitled to the workspace scope → **404** (deny-as-not-found)
- Workspace member but missing the required capability for a protected screen/action → **403**
- **Server-side enforcement**: Navigation visibility must not be treated as authorization; all access control is enforced on the server for every protected page and every mutation.
- **Global search non-leakage**: Global search must not show titles, counts, or partial matches for inaccessible workspaces/tenants/runs. Inaccessible entities behave as not-found.
### Functional Requirements
- **FR-001 (One label, one meaning)**: The application MUST provide two distinct, clearly-labeled entry points:
- "Switch workspace" for selecting the active workspace context.
- "Manage workspaces" for workspace CRUD/administration.
- **FR-002 (Canonical workspace switch route)**: "Switch workspace" MUST navigate to `/admin/choose-workspace`.
- **UX note**: "Switch workspace" is a global context control and MUST NOT be registered as a sidebar navigation item.
- **FR-003 (Canonical workspace management route)**: "Manage workspaces" MUST navigate to `/admin/workspaces` and MUST NOT be labeled simply "Workspaces".
- **FR-004 (Breadcrumb correctness)**: Breadcrumbs in workspace management MUST point back to `/admin/workspaces` and must not send users to the workspace switcher.
- **FR-005 (Monitoring is workspace-level)**: Monitoring pages MUST be workspace-scoped and reachable without tenant context.
- **FR-006 (Canonical Operations URLs)**: Operations MUST remain canonical and tenantless:
- index: `/admin/operations`
- detail: `/admin/operations/{run}`
- **FR-007 (Tenant context affects defaults, not routing)**: If tenant context is active, the operations index MUST default to showing runs for that tenant using **server-side default filter state**, and users MUST be able to clear that default to view workspace-wide operations. The canonical URL MUST remain `/admin/operations` and the default MUST present a visible, removable filter chip (no required querystring parameters).
- **FR-008 (Tenant shortcut to operations)**: Tenant detail screens MUST offer a "Recent operations" summary and a "View all operations" call-to-action that leads to the canonical operations index.
- **FR-009 (Membership gating)**: Users MUST be a member of a workspace to access workspace-scoped pages. Non-members MUST receive a not-found response.
- **FR-010 (Capability gating for management)**: Workspace-scoped management/mutations MUST be restricted to users with the appropriate capability/capabilities (from the canonical registry). Unauthorized workspace members MUST receive a forbidden response.
- Canonical capabilities used by this feature:
- `workspace.manage` (Capabilities::WORKSPACE_MANAGE): create/edit workspace fields.
- `workspace_membership.manage` (Capabilities::WORKSPACE_MEMBERSHIP_MANAGE): add/remove members and change roles.
- **FR-011 (Monitoring hub IA)**: The sidebar MUST provide a "Monitoring" area that is the canonical home for Operations now, with reserved surfaces for future Alerts and Audit Log.
- **FR-012 (Deep-link stability)**: Any monitoring entity intended for support workflows MUST have a stable deep link that does not depend on tenant context.
- **FR-013 (No workspace selected)**: If a user visits a workspace-scoped page without a selected workspace context, the system MUST redirect to `/admin/choose-workspace` and then return the user to their originally requested URL after a successful selection.
- **FR-014 (Invalid tenant context)**: If tenant context is active but the tenant does not belong to the current workspace, the system MUST auto-clear tenant context and continue on workspace-level pages without tenant scoping.
- **FR-077-016 (Header context bar)**: The header MUST provide an always-available context bar for Suite navigation:
- **FR-077-016-A (Workspace visible)**: If a workspace is selected, show `Workspace: <name>` and allow the user to open the existing workspace switcher (`/admin/choose-workspace`).
- **FR-077-016-B (Tenant accessible on tenantless pages)**: The header MUST surface tenant context even on tenantless pages (e.g., `/admin/operations`). If there is an active tenant context, show `Tenant: <tenant name>` (fallback to a safe identifier). If there is no active tenant but there is a last-selected tenant in the current workspace session, show it.
- **FR-077-016-C (No implicit switching)**: Canonical pages MUST NOT silently switch tenant or workspace. The context bar is an explicit control only.
- **FR-077-016-D (No leakage)**: Tenant picker contents MUST include only tenants the user is entitled to view within the current workspace. Unauthorized tenant selection via direct URL MUST remain deny-as-not-found (404).
- **FR-077-016-E (Filament-native)**: Implementation MUST use Filament v5 mechanisms (topbar/user-menu render hooks + Filament tenancy) and Livewire v4 where needed.
### Key Entities *(include if feature involves data)*
- **Workspace**: Primary context container for a customer/portfolio.
- **Workspace Membership**: The relationship that entitles a user to a workspace.
- **Managed Tenant**: Secondary context within a workspace; used for scoping defaults and tenant workflows.
- **Operation Run**: A record representing an operational execution that belongs to a workspace and may be associated with a tenant.
- **Capability**: A named permission that gates management/mutation behavior.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001 (Reduced confusion)**: In a moderated test with new users, at least 90% correctly choose the right destination (switch vs manage) on first attempt.
- **SC-002 (Faster workspace switching)**: Users can switch to a known workspace in under 15 seconds without using search.
- **SC-003 (Reliable deep links)**: Support can open `/admin/operations/{run}` successfully regardless of tenant context in 100% of tested cases.
- **SC-004 (No leakage regressions)**: Security regression tests confirm 0 instances of inaccessible workspaces/tenants/runs appearing in navigation or global search.
## Acceptance details (pinned)
### Recent operations summary (FR-008)
- Show the most recent **5** operation runs for the current tenant, ordered by `created_at` descending (fallback: `id` descending).
- Display, at minimum: `type` (label), `status`, `outcome`, `created_at` (or since), and a link to the run detail.
- Provide a "View all operations" CTA that navigates to canonical `/admin/operations` (no tenant prefix / no required query params).
### Header context bar (FR-077-016)
- The header shows a stable, compact context bar:
- `Workspace: <name>` (clickable)
- `Tenant: <name>` (picker)
- Tenant picker is available on tenantless pages.
- No automatic tenant selection occurs when opening canonical URLs.
## Mandatory Tests (pinned)
- **T-077-016-1 (Tenant dropdown on tenantless pages)**: With a selected workspace and an active tenant context, visiting `/admin/operations` shows the tenant picker and selecting a tenant navigates to tenant home.
- **T-077-016-2 (Security filtering)**: Only entitled tenants within the current workspace appear in the picker; posting /navigating to an unauthorized tenant results in 404.
- **T-077-016-3 (No implicit switching)**: Visiting `/admin/operations/{run}` from a deep link MUST NOT auto-switch tenant.

View File

@ -1,220 +0,0 @@
---
description: "Task list for Spec 077 implementation"
---
# Tasks: Workspace-first Navigation & Monitoring Hub (077)
**Input**: Design documents from `/specs/077-workspace-nav-monitoring-hub/`
**Prerequisites**:
- Required: [spec.md](spec.md), [plan.md](plan.md)
- Optional (used): [research.md](research.md), [data-model.md](data-model.md), [contracts/routes.md](contracts/routes.md), [quickstart.md](quickstart.md)
**Tests**: REQUIRED (Pest) — this feature changes runtime behavior (navigation + authorization + filtering).
**Livewire/Filament compatibility**: Filament v5 + Livewire v4 only.
---
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: Prepare the minimal scaffolding for safe, test-first delivery.
- [X] T001 Create new Pest test file for workspace navigation in tests/Feature/Workspaces/WorkspaceNavigationHubTest.php
- [X] T002 Create new Pest test file for operations canonical routing in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
- [X] T003 [P] Create new Pest test file for non-leakage semantics in tests/Feature/OpsUx/NonLeakageWorkspaceOperationsTest.php
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Shared plumbing needed by multiple stories.
- [X] T004 Add intended-URL session key constant in app/Support/Workspaces/WorkspaceContext.php
- [X] T005 Implement “store intended URL” helper in app/Support/Workspaces/WorkspaceIntendedUrl.php
- [X] T006 [P] Add tests for intended-URL helper in tests/Feature/Workspaces/WorkspaceIntendedUrlTest.php
- [X] T007 Update middleware to use intended-URL helper in app/Http/Middleware/EnsureWorkspaceSelected.php
- [X] T008 [P] Add safe-redirect allowlist for intended URLs in app/Support/Workspaces/WorkspaceIntendedUrl.php
**Checkpoint**: Intended redirect plumbing exists and is covered by tests.
---
## Phase 3: User Story 1 — Switch workspace without ambiguity (Priority: P1) 🎯 MVP
**Goal**: Clear separation between “Switch workspace” and “Manage workspaces”, with correct 404/403 behavior.
**Independent Test**: A signed-in user can switch workspaces via “Switch workspace”, and “Manage workspaces” is only visible/accessible when authorized.
### Tests for User Story 1 (write first)
- [X] T009 [P] [US1] Assert nav label “Switch workspace” appears when tenant is not selected in tests/Feature/Workspaces/WorkspaceNavigationHubTest.php
- [X] T010 [P] [US1] Assert no ambiguous “Workspaces” nav item exists in tests/Feature/Workspaces/WorkspaceNavigationHubTest.php
- [X] T011 [P] [US1] Assert `/admin/workspaces` is tenantless and reachable for a workspace owner in tests/Feature/Workspaces/WorkspacesResourceIsTenantlessTest.php
- [X] T012 [P] [US1] Assert `/admin/workspaces/{record}` is deny-as-not-found for non-members (404) in tests/Feature/Workspaces/WorkspacesResourceIsTenantlessTest.php
### Implementation for User Story 1
- [X] T013 [US1] Rename fallback nav item to “Switch workspace” in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T014 [US1] Update user-menu copy/CTA to “Switch workspace” in resources/views/filament/partials/workspace-switcher.blade.php
- [X] T015 [US1] Rename admin sidebar item to “Manage workspaces” in app/Providers/Filament/AdminPanelProvider.php
- [X] T016 [US1] Gate “Manage workspaces” navigation visibility via capability in app/Providers/Filament/AdminPanelProvider.php
- [X] T017 [US1] Enforce workspace-scoped RBAC semantics for workspace management (404 non-member, 403 missing capability) in app/Policies/WorkspacePolicy.php
- [X] T018 [US1] Ensure workspace management breadcrumbs point to `/admin/workspaces` in app/Filament/Resources/Workspaces/WorkspaceResource.php
- [X] T019 [US1] Ensure `/admin/workspaces` routes do not require tenant context in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T020 [US1] Run focused tests for US1 via `./vendor/bin/sail artisan test --compact --filter=WorkspaceNavigationHub` (document in specs/077-workspace-nav-monitoring-hub/quickstart.md)
**Checkpoint**: UI uses unambiguous labels; `/admin/workspaces` follows workspace RBAC semantics (no leakage).
---
## Phase 4: User Story 2 — Use Monitoring hub from canonical links (Priority: P2)
**Goal**: `/admin/operations` and `/admin/operations/{run}` work regardless of tenant context; tenant context only sets removable default filters.
**Independent Test**: Visiting `/admin/operations` works tenantless (workspace-selected), and in tenant context it defaults to that tenant via a removable filter chip.
### Tests for User Story 2 (write first)
- [X] T021 [P] [US2] Assert `/admin/operations` is reachable without tenant context in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
- [X] T022 [P] [US2] Assert `/admin/operations/{run}` works with and without tenant context in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
- [X] T023 [P] [US2] Assert operations list defaults to current tenant (filter state) when tenant context active in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
- [X] T024 [P] [US2] Assert clearing tenant filter shows workspace-wide runs in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
### Implementation for User Story 2
- [X] T025 [US2] Allow `/admin/operations` (index) through tenancy-enforcing middleware without auto-setting tenant in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T026 [US2] Ensure workspace selection is required for `/admin/operations` and stores intended URL for return flow in app/Http/Middleware/EnsureWorkspaceSelected.php
- [X] T027 [US2] Redirect back to intended URL after workspace selection in both app/Filament/Pages/ChooseWorkspace.php and app/Http/Controllers/SwitchWorkspaceController.php
- [X] T028 [US2] Remove hard tenant scoping from query in app/Filament/Resources/OperationRunResource.php
- [X] T029 [US2] Add tenant SelectFilter with removable chip and server-side default state in app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php
- [X] T030 [US2] Scope selectable tenants in the filter to current workspace in app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php
- [X] T031 [US2] Add “Recent operations” summary (last 5 by created_at) + “View all operations” CTA on tenant view page in app/Filament/Resources/TenantResource/Pages/ViewTenant.php
- [X] T032 [US2] Ensure “View all operations” CTA routes to canonical `/admin/operations` in app/Filament/Resources/TenantResource/Pages/ViewTenant.php
- [X] T033 [US2] Ensure operations pages remain DB-only (no Graph calls) by extending existing checks in tests/Feature/MonitoringOperationsTest.php
- [X] T034 [US2] Run focused tests for US2 via `./vendor/bin/sail artisan test --compact --filter=OperationsCanonicalUrls` and update specs/077-workspace-nav-monitoring-hub/quickstart.md
**Checkpoint**: Canonical operations URLs work; tenant context only affects default filter state.
---
## Phase 5: User Story 3 — Navigate and search without leaking inaccessible data (Priority: P3)
**Goal**: Enforce strict 404 vs 403 semantics without leaking admin surfaces or cross-workspace/tenant data.
**Independent Test**: Non-members get 404; members missing capability get 403, and no navigation labels hint at inaccessible features.
### Tests for User Story 3 (write first)
- [X] T035 [P] [US3] Assert non-member access to another workspaces operations is 404 in tests/Feature/OpsUx/NonLeakageWorkspaceOperationsTest.php
- [X] T036 [P] [US3] Assert member missing `workspace.manage` gets 403 on `/admin/workspaces/{record}/edit` in tests/Feature/OpsUx/NonLeakageWorkspaceOperationsTest.php
- [X] T037 [P] [US3] Assert invalid tenant context is auto-cleared when switching workspace in tests/Feature/Workspaces/ManagedTenantsWorkspaceRoutingTest.php
- [X] T038 [P] [US3] Assert reserved Monitoring placeholder pages exist (`/admin/alerts`, `/admin/audit-log`) in tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php
### Implementation for User Story 3
- [X] T039 [US3] Implement “auto-clear invalid tenant context” check in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T040 [US3] Confirm and implement correct Filament v5 mechanism for clearing persisted tenant state in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T041 [US3] Implement reserved Monitoring placeholder pages (Alerts, Audit Log) as Filament pages under app/Filament/Pages/Monitoring/**
- [X] T042 [US3] Ensure navigation does not expose admin-only surfaces to unauthorized users in app/Providers/Filament/AdminPanelProvider.php
- [X] T043 [US3] Verify global search does not introduce new leakage for operations/workspaces and, if needed, disable global search for resources without view/edit pages in app/Filament/**
- [X] T044 [US3] Run focused tests for US3 via `./vendor/bin/sail artisan test --compact --filter=NonLeakageWorkspaceOperations`
**Checkpoint**: 404/403 behavior matches spec; no cross-scope leaks.
---
## Phase 6: Polish & Cross-Cutting Concerns
**Purpose**: Stabilize, format, and validate end-to-end.
- [X] T045 Run formatter on touched files via `./vendor/bin/sail bin pint --dirty`
- [X] T046 Run targeted full suite for touched areas via `./vendor/bin/sail artisan test --compact tests/Feature/Workspaces tests/Feature/Monitoring tests/Feature/OpsUx`
- [X] T047 [P] Confirm manual quickstart steps still match UI labels and routes in specs/077-workspace-nav-monitoring-hub/quickstart.md
- [X] T048 [P] Confirm route semantics still match contracts in specs/077-workspace-nav-monitoring-hub/contracts/routes.md
- [X] T049 Ensure Filament v5 + Livewire v4 APIs are used (no v3/v4 Filament APIs) in app/Filament/**
- [X] T050 Run full suite (optional) via `./vendor/bin/sail artisan test --compact`
### Post-implementation bugfixes
- [X] T058 Fix route conflict so Operations “View” consistently hits canonical `/admin/operations/{run}` by moving Filament resource view route to `/admin/operations/r/{record}` in app/Filament/Resources/OperationRunResource.php
- [X] T059 Remove “Switch workspace” from sidebar navigation (workspace switching is topbar-only) in app/Providers/Filament/AdminPanelProvider.php and app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T060 Define Global Mode: make `/admin/workspaces` workspace-optional + add explicit allowlist in app/Http/Middleware/EnsureWorkspaceSelected.php
- [X] T061 Disable tenant picker when no workspace is active (Global Mode) in resources/views/filament/partials/context-bar.blade.php
- [X] T062 Remove “Manage workspaces” link from the topbar context switcher to avoid redundant entry points in resources/views/filament/partials/context-bar.blade.php
- [X] T063 Unify workspace creation authorization: ChooseWorkspace create action must use WorkspacePolicy (Gate) in app/Filament/Pages/ChooseWorkspace.php and app/Policies/WorkspacePolicy.php
---
## Phase 7: Addendum — Header Context Bar (FR-077-016)
**Goal**: Always-visible context bar for Workspace + Tenant, usable on tenantless pages without implicit switching.
### Tests (write first)
- [X] T051 [P] [FR-077-016] Assert tenant picker renders on `/admin/operations` in tests/Feature/Monitoring/HeaderContextBarTest.php
- [X] T052 [P] [FR-077-016] Assert tenant picker lists only entitled tenants in tests/Feature/Monitoring/HeaderContextBarTest.php
- [X] T053 [P] [FR-077-016] Assert deep link `/admin/operations/{run}` does not auto-switch tenant in tests/Feature/Monitoring/HeaderContextBarTest.php
### Implementation
- [X] T054 [FR-077-016] Render context bar in topbar via render hook in app/Providers/Filament/AdminPanelProvider.php
- [X] T055 [FR-077-016] Add context bar partial view in resources/views/filament/partials/context-bar.blade.php
- [X] T056 [FR-077-016] Remove implicit tenant auto-selection behavior while preserving deny-as-not-found semantics in app/Support/Middleware/EnsureFilamentTenantSelected.php
- [X] T057 [FR-077-016] Persist last-selected tenant per workspace session in app/Support/Workspaces/WorkspaceContext.php and controllers/pages that select tenants
**Checkpoint**: Tenant picker usable on tenantless pages; no silent tenant switching.
---
## Dependencies & Execution Order
### Phase Dependencies
- Phase 1 (Setup) → Phase 2 (Foundational)
- Phase 2 (Foundational) → Phase 3+ (User stories)
- Phase 3 (US1) is the MVP and should be delivered first.
- Phase 4 (US2) depends on the clarified navigation + intended-URL plumbing (Phases 12).
- Phase 5 (US3) depends on the implemented behavior from US1/US2 so it can assert non-leakage.
### User Story Dependencies
- US1 → US2: soft dependency (naming + intended redirect improves US2 flows)
- US2 → US3: recommended dependency (US3 asserts final 404/403 and filter semantics)
---
## Parallel Execution Examples
### US1 parallelizable work
- T009, T010, T011, T012 can be written in parallel (different assertions/files)
- T013, T014, T015 can be implemented in parallel (different files)
### US2 parallelizable work
- T021T024 can be written in parallel
- T028 (resource query) and T029 (table filters) can be implemented in parallel
- T031T032 can be implemented in parallel with operations filter work (different file)
### US3 parallelizable work
- T035T038 can be written in parallel
- T039T042 can be implemented in parallel (different files)
---
## Implementation Strategy
### MVP scope (recommended)
- Deliver Phase 13 (US1) only.
- Validate with `./vendor/bin/sail artisan test --compact --filter=WorkspaceNavigationHub`.
- Demo “Switch workspace” vs “Manage workspaces” clarity + correct 404/403 behavior.
### Incremental delivery
- Add US2 (canonical operations URLs + removable tenant default filter)
- Add US3 (non-leakage regression guards)
- Finish with Phase 6 polish and a full suite run

View File

@ -1,36 +0,0 @@
# Specification Quality Checklist: Operations Tenantless Canonical Migration
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-02-06
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs) — Implementation Notes section is clearly marked non-normative; FR-078-002 mentions trait names as implementation guidance only
- [x] Focused on user value and business needs — all user stories describe user outcomes, not system internals
- [x] Written for non-technical stakeholders — principles and requirements use domain language
- [x] All mandatory sections completed — User Scenarios, Requirements, Success Criteria all present
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain — all decisions resolved (302 vs 301, KPI deferral, infolist approach)
- [x] Requirements are testable and unambiguous — each FR has specific verifiable behavior
- [x] Success criteria are measurable — SC-001 through SC-006 all have concrete pass/fail conditions
- [x] Success criteria are technology-agnostic (no implementation details) — criteria reference URLs and user outcomes, not code
- [x] All acceptance scenarios are defined — 4 user stories with given/when/then scenarios
- [x] Edge cases are identified — 5 edge cases documented including null workspace, non-numeric record, null tenant
- [x] Scope is clearly bounded — Non-Goals section explicitly excludes KPI workspace-scoping, alerts engine, capability-gating
- [x] Dependencies and assumptions identified — baseline routes, existing link helpers, constitution alignment documented
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria — FR-078-001 through FR-078-012 each specify observable behavior
- [x] User scenarios cover primary flows — canonical view, legacy redirects, contextual nav, list regression
- [x] Feature meets measurable outcomes defined in Success Criteria — SC-001 (one canonical URL), SC-003 (secure redirects), SC-005 (verification report tenantless)
- [x] No implementation details leak into specification — Implementation Notes section is non-normative; core spec is behavior-focused
## Notes
- FR-078-002 includes implementation guidance (trait names) as a non-normative hint for planners; the normative requirement is "reuse infolist schema" regardless of approach.
- Open decision on 301 vs 302 documented; 302 chosen as Phase 1 default with clear promotion path.
- KPI workspace-scoping explicitly deferred (Non-Goals + FR-078-008) — keeps migration scope focused.

View File

@ -1,109 +0,0 @@
# Route Contracts: Operations Tenantless Canonical Migration
**Feature**: 078-operations-tenantless-canonical
**Date**: 2026-02-06
---
## Canonical Routes (Retained — No Changes)
### GET /admin/operations
| Property | Value |
|----------|-------|
| **Route name** | `admin.operations.index` |
| **Handler** | `App\Filament\Pages\Monitoring\Operations` |
| **Middleware** | `web`, `panel:admin`, `ensure-correct-guard:web`, `DenyNonMemberTenantAccess`, Filament middleware, `ensure-workspace-selected`, `ensure-filament-tenant-selected` |
| **Auth** | Requires authentication + workspace membership |
| **Scope** | Workspace-level (shows all runs in workspace) |
| **Response** | 200 HTML (Livewire page) |
### GET /admin/operations/{run}
| Property | Value |
|----------|-------|
| **Route name** | `admin.operations.view` |
| **Handler** | `App\Filament\Pages\Operations\TenantlessOperationRunViewer` |
| **Middleware** | `web`, `panel:admin`, `ensure-correct-guard:web`, `DenyNonMemberTenantAccess`, Filament middleware |
| **Auth** | Requires authentication + workspace membership for `$run->workspace_id` |
| **Model binding** | `{run}` resolves to `OperationRun` by ID |
| **Non-member** | 404 (deny-as-not-found) |
| **Not found** | 404 (Laravel model binding) |
| **Response** | 200 HTML (Livewire page with infolist) |
---
## Decommissioned Routes (Resource-Generated Routes Removed After Migration)
### GET /admin/t/{tenant}/operations/r/{record}
| Property | Value |
|----------|-------|
| **Route name** | `filament.admin.resources.operations.view` |
| **Status** | ❌ **REMOVED** — route no longer registered |
| **After migration** | Natural 404 |
| **Previously** | `ViewOperationRun` (Filament ViewRecord page) |
### GET /admin/t/{tenant}/operations
| Property | Value |
|----------|-------|
| **Route name** | `filament.admin.resources.operations.index` |
| **Status** | ❌ **REMOVED** — route no longer registered |
| **After migration** | Replaced by explicit convenience route `admin.operations.legacy-index` that redirects 302 → `/admin/operations` |
| **Previously** | `ListOperationRuns` (Filament ListRecords page) |
---
## Link Generation Contracts
### OperationRunLinks::view($run, $tenant)
| Property | Value |
|----------|-------|
| **Returns** | `route('admin.operations.view', ['run' => $run])` |
| **Delegates to** | `OperationRunLinks::tenantlessView($run)` |
| **Tenant parameter** | Ignored (no-op) |
| **Change** | None — already canonical |
### OperationRunLinks::tenantlessView($run)
| Property | Value |
|----------|-------|
| **Returns** | `route('admin.operations.view', ['run' => $run])` |
| **Change** | None |
### OperationRunLinks::index()
| Property | Value |
|----------|-------|
| **Returns** | `route('admin.operations.index')` |
| **Change** | None |
### OperationRunLinks::related($run, $tenant)
| Property | Value |
|----------|-------|
| **Returns** | Array of up to 11 contextual link arrays |
| **Change** | None — consumed by `TenantlessOperationRunViewer` header actions |
---
## Test Route Assertions
### Positive (must work)
| Test | Route | Expected |
|------|-------|----------|
| T-078-001 | `GET /admin/operations/{run}` | 200 (member) |
| T-078-001 | `GET /admin/operations/{run}` | 200 (run with `tenant_id = null`) |
| T-078-009 | `GET /admin/t/{tenant}/operations` | 302 redirect to `/admin/operations` |
### Negative (must 404)
| Test | Route | Expected |
|------|-------|----------|
| T-078-001 | `GET /admin/operations/{run}` | 404 (non-member) |
| T-078-002 | `GET /admin/t/{tenant}/operations/r/{record}` | 404 (any user) |
| T-078-004 | Route name `filament.admin.resources.operations.view` | Not registered |
| T-078-004 | Route name `filament.admin.resources.operations.index` | Not registered |

View File

@ -1,94 +0,0 @@
# Data Model: Operations Tenantless Canonical Migration
**Feature**: 078-operations-tenantless-canonical
**Date**: 2026-02-06
---
## Overview
This feature does **not** introduce new models or migrations. It reorganizes how existing models are rendered and routed.
## Entities (Existing — No Changes)
### OperationRun
| Field | Type | Notes |
|-------|------|-------|
| `id` | `bigint` (PK) | Auto-increment |
| `workspace_id` | `bigint` (FK) | Required. Authorization boundary. |
| `tenant_id` | `bigint` (FK, nullable) | Null for workspace-level runs (e.g., onboarding). |
| `type` | `string` | Operation type slug (e.g., `policy.sync`, `restore.execute`). |
| `status` | `enum` | `OperationRunStatus`: Queued, Running, Completed, Cancelled. |
| `outcome` | `enum` (nullable) | `OperationRunOutcome`: Succeeded, PartiallySucceeded, Failed. |
| `context` | `jsonb` | Contains `target_scope`, `verification_report`, etc. |
| `summary_counts` | `jsonb` | `{total, processed, succeeded, failed, skipped}` |
| `failure_summary` | `jsonb` (nullable) | Sanitized failure details. |
| `initiated_by` | `bigint` (FK, nullable) | User who started the run. |
| `started_at` | `timestamp` (nullable) | |
| `completed_at` | `timestamp` (nullable) | |
| `created_at` | `timestamp` | |
| `updated_at` | `timestamp` | |
**Relationships**: `belongsTo Workspace`, `belongsTo Tenant` (nullable), `belongsTo User` (initiated_by)
### WorkspaceMembership (Authorization Boundary)
The `OperationRunPolicy::view()` checks:
1. User must be a member of `$run->workspace_id`
2. Returns `Response::denyAsNotFound()` if not a member
No changes to this model or policy logic.
## Routing Changes (No Model Impact)
### Routes Removed
| Route Name | Pattern | Handler |
|------------|---------|---------|
| `filament.admin.resources.operations.index` | `GET /admin/t/{tenant}/operations` | `ListOperationRuns` (resource-generated) |
| `filament.admin.resources.operations.view` | `GET /admin/t/{tenant}/operations/r/{record}` | `ViewOperationRun` |
### Route Added
| Route Name | Pattern | Handler |
|------------|---------|---------|
| `admin.operations.legacy-index` | `GET /admin/t/{tenant}/operations` | Redirect 302 to `/admin/operations` |
### Routes Retained (Unchanged)
| Route Name | Pattern | Handler |
|------------|---------|---------|
| `admin.operations.index` | `GET /admin/operations` | `Operations.php` |
| `admin.operations.view` | `GET /admin/operations/{run}` | `TenantlessOperationRunViewer` |
### Files Deleted
| File | Reason |
|------|--------|
| `app/Filament/Resources/OperationRunResource/Pages/ViewOperationRun.php` | Replaced by TenantlessOperationRunViewer |
| `app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php` | Replaced by Operations.php |
| `app/Livewire/Monitoring/OperationsDetail.php` | Dead code |
| `resources/views/livewire/monitoring/operations-detail.blade.php` | Dead code (blade for OperationsDetail) |
### Files Modified
| File | Change |
|------|--------|
| `app/Filament/Resources/OperationRunResource.php` | `getPages()` returns `[]` |
| `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` | Reuse infolist via schema, add related links |
| `resources/views/filament/pages/operations/tenantless-operation-run-viewer.blade.php` | Replace hand-coded HTML with `{{ $this->infolist }}` |
| `app/Filament/Widgets/Operations/OperationsKpiHeader.php` | Hide stats when no tenant context |
### Test Files Requiring Updates
| File | Change Required |
|------|----------------|
| `tests/Feature/Verification/VerificationAuthorizationTest.php` | Replace `OperationRunResource::getUrl('view')` with `route('admin.operations.view')` |
| `tests/Feature/OpsUx/FailureSanitizationTest.php` | Replace `OperationRunResource::getUrl('view')` with canonical route; replace `ViewOperationRun` mount |
| `tests/Feature/OpsUx/CanonicalViewRunLinksTest.php` | Update guard regex to account for headless resource |
| `tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php` | Replace `ViewOperationRun` mount with `TenantlessOperationRunViewer` |
| `tests/Feature/Verification/VerificationReportRedactionTest.php` | Replace `ViewOperationRun` mount with `TenantlessOperationRunViewer` |
| `tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php` | Replace `ViewOperationRun` mount with `TenantlessOperationRunViewer` |
| `tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php` | Remove `ListOperationRuns` test; add route-not-registered assertion |
| `tests/Feature/Monitoring/OperationsTenantScopeTest.php` | Remove `ListOperationRuns` test |

View File

@ -1,288 +0,0 @@
# Implementation Plan: Operations Tenantless Canonical Migration
**Branch**: `078-operations-tenantless-canonical` | **Date**: 2025-07-13 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `/specs/078-operations-tenantless-canonical/spec.md`
## Summary
Make Operations detail **fully canonical** at `/admin/operations/{run}` by converting `TenantlessOperationRunViewer` to reuse `OperationRunResource::infolist()` via Filament v5's unified schema system, decommissioning auto-generated tenant-scoped resource pages (they naturally 404 after route removal), cleaning up dead code, and updating all affected tests.
Key approach: Filament v5 deprecated `InteractsWithInfolists` — every `Page` already has `InteractsWithSchemas`. The existing `OperationRunResource::infolist()` is `public static` with no `$this` references and already handles `Filament::getTenant()` returning null. This means `TenantlessOperationRunViewer` can define `infolist(Schema $schema)` to delegate directly, achieving full visual parity with zero code duplication.
## Technical Context
**Language/Version**: PHP 8.4 (Laravel 12)
**Primary Dependencies**: Filament v5, Livewire v4, Filament Infolists (schema-based)
**Storage**: PostgreSQL (no new migrations — read-only model changes)
**Testing**: Pest v4 (Feature tests)
**Target Platform**: Web (Laravel Sail / Docker)
**Project Type**: Web application (monolith)
**Performance Goals**: DB-only rendering (no external calls on page load)
**Constraints**: Tenantless pages must render without `Filament::getTenant()`; no new dependencies
**Scale/Scope**: ~15 files modified/deleted, ~8 test files updated, 0 new migrations
## Constitution Check
*GATE: All pass. No violations.*
| Principle | Status | Notes |
|-----------|--------|-------|
| Inventory-first | N/A | No inventory changes |
| Read/write separation | Pass | Feature is read-only (rendering changes only) |
| Graph contract path | N/A | No Graph calls |
| Deterministic capabilities | N/A | No capability changes |
| RBAC-UX planes | Pass | Workspace-level auth only; non-member = 404 (RBAC-UX-002) |
| RBAC-UX destructive | N/A | No destructive actions |
| RBAC-UX global search | Pass | Resource has `$shouldRegisterNavigation = false`, no `$recordTitleAttribute` |
| Tenant isolation | Pass | Reads workspace-scoped; no cross-tenant access |
| Run observability | N/A | No new operations; monitoring pages remain DB-only |
| Automation | N/A | No queued/scheduled work |
| Data minimization | Pass | No new data stored |
| Badge semantics | Pass | Existing `BadgeRenderer` reused via infolist — no new badge mappings |
**Post-design re-check**: Same results — no constitution violations.
## Project Structure
### Documentation (this feature)
```text
specs/078-operations-tenantless-canonical/
+-- spec.md # Feature specification
+-- plan.md # This file
+-- research.md # Phase 0: Filament v5 schema research
+-- data-model.md # Phase 1: Entity & routing changes
+-- quickstart.md # Phase 1: Verification steps
+-- contracts/
| +-- routes.md # Route contract (before/after)
+-- checklists/
| +-- requirements.md # Spec quality checklist
+-- tasks.md # Phase 2 output (created by /speckit.tasks)
```
### Source Code (files touched)
```text
app/
+-- Filament/
| +-- Resources/
| | +-- OperationRunResource.php # getPages() returns []
| | +-- OperationRunResource/Pages/
| | +-- ViewOperationRun.php # DELETE
| | +-- ListOperationRuns.php # DELETE
| +-- Pages/
| | +-- Operations/
| | +-- TenantlessOperationRunViewer.php # Infolist reuse + related links
| +-- Widgets/
| +-- Operations/
| +-- OperationsKpiHeader.php # Hide stats when no tenant
+-- Livewire/
+-- Monitoring/
+-- OperationsDetail.php # DELETE (dead code)
resources/views/
+-- filament/pages/operations/
| +-- tenantless-operation-run-viewer.blade.php # Replace HTML with infolist render
+-- livewire/monitoring/
+-- operations-detail.blade.php # DELETE (dead code)
tests/Feature/
+-- Operations/
| +-- TenantlessOperationRunViewerTest.php # Update infolist assertions
+-- Monitoring/
| +-- OperationsCanonicalUrlsTest.php # Remove ListOperationRuns, add route-gone
| +-- OperationsTenantScopeTest.php # Remove ListOperationRuns reference
+-- Verification/
| +-- VerificationAuthorizationTest.php # Canonical route instead of getUrl
| +-- VerificationReportViewerDbOnlyTest.php # TenantlessViewer replaces ViewOperationRun
| +-- VerificationReportRedactionTest.php # TenantlessViewer replaces ViewOperationRun
| +-- VerificationReportMissingOrMalformedTest.php # TenantlessViewer replaces ViewOperationRun
+-- OpsUx/
| +-- FailureSanitizationTest.php # Canonical route + TenantlessViewer
| +-- CanonicalViewRunLinksTest.php # Update guard regex
+-- 078/ # NEW spec-specific tests
+-- CanonicalDetailRenderTest.php
+-- LegacyRoutesReturnNotFoundTest.php
+-- KpiHeaderTenantlessTest.php
+-- VerificationReportTenantlessTest.php
+-- TenantListRedirectTest.php
+-- RelatedLinksOnDetailTest.php
```
**Structure Decision**: Standard Laravel monolith. No new directories except `tests/Feature/078/` for spec tests.
## Complexity Tracking
> No constitution violations to justify.
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| None | N/A | N/A |
---
## Implementation Phases
### Phase A — Headless Resource + Dead Code Cleanup
**Goal**: Remove auto-generated routes; delete dead code.
**Risk**: Low — removing unused pages and dead code.
**Tests first**: T-078-004 (routes not registered), T-078-002 (legacy URLs 404).
| Step | File | Change |
|------|------|--------|
| A.1 | `OperationRunResource.php` | `getPages()` returns `[]` |
| A.2 | `ViewOperationRun.php` | Delete file |
| A.3 | `ListOperationRuns.php` | Delete file |
| A.4 | `OperationsDetail.php` | Delete file (dead code) |
| A.5 | `operations-detail.blade.php` | Delete file (dead code) |
| A.6 | `tests/Feature/078/LegacyRoutesReturnNotFoundTest.php` | New: T-078-002 + T-078-004 |
| A.7 | 7 existing test files | Replace `ViewOperationRun` / `ListOperationRuns` / `getUrl('view')` references |
**Exit criteria**: All existing tests pass; legacy URLs return 404; no routes registered for resource.
### Phase B — Infolist Reuse on TenantlessOperationRunViewer
**Goal**: Replace hand-coded Blade with Filament schema-based infolist for full visual parity.
**Risk**: Medium — schema auto-discovery on standalone Page needs verification.
**Tests first**: T-078-001 (canonical detail renders), T-078-008 (verification report tenantless).
| Step | File | Change |
|------|------|--------|
| B.1 | `TenantlessOperationRunViewer.php` | Add `infolist(Schema $schema)` — delegates to `OperationRunResource::infolist($schema)` |
| B.2 | `TenantlessOperationRunViewer.php` | Add `defaultInfolist(Schema $schema)``->record($this->run)->columns(2)` |
| B.3 | `TenantlessOperationRunViewer.php` | Add `content(Schema $schema)` — returns `EmbeddedSchema::make('infolist')` |
| B.4 | `TenantlessOperationRunViewer.php` | Add `public bool $opsUxIsTabHidden = false` property (polling callback) |
| B.5 | `tenantless-operation-run-viewer.blade.php` | Replace hand-coded HTML with infolist render tag |
| B.6 | `tests/Feature/078/CanonicalDetailRenderTest.php` | New: T-078-001 (+ T-078-007 guard) |
| B.7 | `tests/Feature/078/VerificationReportTenantlessTest.php` | New: T-078-008 |
**Exit criteria**: Canonical detail shows identical layout to old tenant-scoped view; verification report section renders.
### Phase C — Contextual Navigation (Related Links)
**Goal**: Replace "Admin details" button with `OperationRunLinks::related()` action group.
**Risk**: Low — mechanism already exists, just wiring.
**Tests first**: T-078-010 (related links appear), T-078-005 (no "Admin details" link).
| Step | File | Change |
|------|------|--------|
| C.1 | `TenantlessOperationRunViewer.php` | Add `getHeaderActions()` using `OperationRunLinks::related()` |
| C.2 | `TenantlessOperationRunViewer.php` | Remove "Admin details" button code (~line 61) |
| C.3 | `tests/Feature/078/RelatedLinksOnDetailTest.php` | New: T-078-010 + T-078-005 + T-078-012 |
**Exit criteria**: Related links render for different run types; "Admin details" link absent.
### Phase D — KPI Header Tenantless Handling
**Goal**: Hide KPI stats when no tenant context (not workspace-scoped — deferred).
**Risk**: Low — conditional early return.
**Tests first**: T-078-006 (KPI hidden in tenantless mode), T-078-011 (tenantless list query safety).
| Step | File | Change |
|------|------|--------|
| D.1 | `OperationsKpiHeader.php` | `getStats()`: if `Filament::getTenant()` is null then return `[]` |
| D.2 | `tests/Feature/078/KpiHeaderTenantlessTest.php` | New: T-078-006 |
| D.3 | `tests/Feature/078/OperationsListTenantlessSafetyTest.php` | New: T-078-011 |
**Exit criteria**: Operations page without tenant context renders without errors; KPI section hidden.
### Phase E — List Redirect (FR-078-012)
**Goal**: Convenience redirect for decommissioned list URL.
**Risk**: Low — single route addition.
**Tests first**: T-078-009 (302 redirect).
| Step | File | Change |
|------|------|--------|
| E.1 | `routes/web.php` | Add redirect: `/admin/t/{tenant}/operations` 302 to `/admin/operations` |
| E.2 | `tests/Feature/078/TenantListRedirectTest.php` | New: T-078-009 |
**Exit criteria**: Tenant-scoped list URL redirects; no other URLs affected.
---
## Key Design Decisions
### D-001 — Schema-based infolist (not InteractsWithInfolists)
Filament v5 unified forms/infolists/tables into the schema system. `InteractsWithInfolists` is deprecated. Every `Page` already has `InteractsWithSchemas` via `BasePage`. Define `infolist(Schema $schema)` on the page and it auto-discovers via reflection.
**See**: [research.md](research.md) R-001
### D-002 — Empty getPages() (not resource exclusion)
Returning `[]` from `getPages()` cleanly prevents all route registration while keeping the class available for `::table()` and `::infolist()` reuse. Simpler than excluding from panel discovery.
**See**: [research.md](research.md) R-003
### D-003 — Natural 404 (not redirect handlers)
After route decommission, legacy detail URLs naturally 404. No redirect handlers needed — simplest approach, zero information leakage, zero maintenance.
**See**: spec.md clarifications (FR-078-005/006 removed)
### D-004 — KPI hidden (not workspace-scoped queries)
Phase 1 hides KPI when no tenant. Full workspace-scoped KPI requires refactoring 6 queries + `ActiveRuns::existForWorkspace()` — deferred to separate spec.
**See**: [research.md](research.md) R-004, R-005
---
## Risk Assessment
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| Schema auto-discovery fails on standalone Page | Medium | Low | Research confirms it works (R-001); fallback: static builder extraction |
| Test updates miss a reference to deleted pages | Low | Medium | `grep -r` sweep for ViewOperationRun and ListOperationRuns before PR |
| Infolist polling breaks without opsUxIsTabHidden | Low | Medium | Add property explicitly; existing poll logic has null-safe fallback |
| KPI widget error when tenant is null | Low | Low | Already returns [] on null; this change makes it explicit |
---
## Test Strategy
### New Tests (spec-specific in tests/Feature/078/)
| Test ID | File | Coverage |
|---------|------|----------|
| T-078-001 | CanonicalDetailRenderTest.php | Detail renders with/without tenant_id |
| T-078-002 | LegacyRoutesReturnNotFoundTest.php | Legacy detail URLs return 404 |
| T-078-004 | LegacyRoutesReturnNotFoundTest.php | Route names not registered |
| T-078-005 | RelatedLinksOnDetailTest.php | No "Admin details" link |
| T-078-006 | KpiHeaderTenantlessTest.php | KPI hidden without tenant |
| T-078-008 | VerificationReportTenantlessTest.php | Verification report renders tenantless |
| T-078-009 | TenantListRedirectTest.php | List redirect 302 |
| T-078-010 | RelatedLinksOnDetailTest.php | Related links in header actions |
| T-078-011 | OperationsListTenantlessSafetyTest.php | List renders safely with tenant and tenantless context |
| T-078-012 | RelatedLinksOnDetailTest.php | Canonical CTA label is "View run" and legacy CTA removed |
### Updated Tests (existing)
| File | Change |
|------|--------|
| VerificationAuthorizationTest.php | `getUrl('view')` replaced with `route('admin.operations.view')` |
| FailureSanitizationTest.php | `getUrl('view')` replaced with canonical route; ViewOperationRun replaced with TenantlessOperationRunViewer |
| CanonicalViewRunLinksTest.php | Update guard regex for headless resource |
| VerificationReportViewerDbOnlyTest.php | ViewOperationRun replaced with TenantlessOperationRunViewer |
| VerificationReportRedactionTest.php | ViewOperationRun replaced with TenantlessOperationRunViewer |
| VerificationReportMissingOrMalformedTest.php | ViewOperationRun replaced with TenantlessOperationRunViewer |
| OperationsCanonicalUrlsTest.php | Remove ListOperationRuns test, add route-gone assertion |
| OperationsTenantScopeTest.php | Remove ListOperationRuns reference |
### Focused Test Command
```bash
vendor/bin/sail artisan test --compact \
tests/Feature/078/ \
tests/Feature/Operations/TenantlessOperationRunViewerTest.php \
tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php \
tests/Feature/Monitoring/OperationsTenantScopeTest.php \
tests/Feature/Verification/VerificationAuthorizationTest.php \
tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php \
tests/Feature/Verification/VerificationReportRedactionTest.php \
tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php \
tests/Feature/OpsUx/FailureSanitizationTest.php \
tests/Feature/OpsUx/CanonicalViewRunLinksTest.php
```

View File

@ -1,80 +0,0 @@
# Quickstart: Operations Tenantless Canonical Migration
**Feature**: 078-operations-tenantless-canonical
**Branch**: `078-operations-tenantless-canonical`
---
## Prerequisites
- Laravel Sail running (`vendor/bin/sail up -d`)
- Database migrated (`vendor/bin/sail artisan migrate`)
- At least one workspace with a user member
- At least one `OperationRun` record (with and without `tenant_id`)
## Verification Steps
### 1. Canonical detail renders
```bash
# Visit as authenticated workspace member
# URL: /admin/operations/{run_id}
# Expected: Full infolist renders (summary, target scope, verification report, counts, context JSON)
```
### 2. Auto-generated tenant routes are gone
```bash
vendor/bin/sail artisan route:list --name=filament.admin.resources.operations
# Expected: No routes listed (empty output)
```
### 3. Canonical list still works
```bash
# Visit: /admin/operations
# Expected: Workspace-scoped table with status tabs, filters
```
### 4. Run tests
```bash
# Run the focused test pack for this spec:
vendor/bin/sail artisan test --compact \
tests/Feature/078/ \
tests/Feature/Operations/TenantlessOperationRunViewerTest.php \
tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php \
tests/Feature/Monitoring/OperationsTenantScopeTest.php \
tests/Feature/Verification/VerificationAuthorizationTest.php \
tests/Feature/OpsUx/FailureSanitizationTest.php \
tests/Feature/OpsUx/CanonicalViewRunLinksTest.php \
tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php \
tests/Feature/Verification/VerificationReportRedactionTest.php \
tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php
# Expected: All pass
```
### 5. Pint formatting
```bash
vendor/bin/sail bin pint --dirty
```
## Key Files to Inspect
| File | What to check |
|------|---------------|
| `app/Filament/Resources/OperationRunResource.php` | `getPages()` returns `[]` |
| `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` | Uses schema-based infolist, has related links header |
| `app/Filament/Widgets/Operations/OperationsKpiHeader.php` | Returns empty stats when no tenant context |
| `app/Filament/Pages/Monitoring/Operations.php` | Unchanged — still reuses `OperationRunResource::table()` |
## What Was Deleted
| File | Why |
|------|-----|
| `app/Filament/Resources/OperationRunResource/Pages/ViewOperationRun.php` | Replaced by TenantlessOperationRunViewer |
| `app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php` | Replaced by Operations.php |
| `app/Livewire/Monitoring/OperationsDetail.php` | Dead code |
| `resources/views/livewire/monitoring/operations-detail.blade.php` | Dead code |

View File

@ -1,93 +0,0 @@
# Research: Operations Tenantless Canonical Migration
**Feature**: 078-operations-tenantless-canonical
**Date**: 2026-02-06
---
## R-001 — Filament v5 Infolist Reuse on Standalone Pages
**Decision**: Use the native `InteractsWithSchemas` mechanism (already on every `Page`). No need for `InteractsWithInfolists` or `HasInfolists`.
**Rationale**: In Filament v5, the schema system is unified — forms, infolists, and tables all go through `InteractsWithSchemas`. The `InteractsWithInfolists` trait is fully deprecated (every method proxies to schema equivalents). `HasInfolists` is an empty marker interface. Every `Filament\Pages\Page` already extends `BasePage` which uses `InteractsWithSchemas` and implements `HasSchemas`.
**How it works**:
1. Define `public function infolist(Schema $schema): Schema` on the Page
2. `InteractsWithSchemas` auto-discovers it via reflection
3. Render via `{{ $this->infolist }}` (magic property) or `EmbeddedSchema::make('infolist')`
**Alternatives considered**:
- Adding `InteractsWithInfolists` trait → Rejected: deprecated shim, adds no functionality
- Extracting a static builder from `OperationRunResource` → Not needed: `infolist()` is already `static`
**Source files verified**:
- `vendor/filament/infolists/src/Concerns/InteractsWithInfolists.php` — all methods `@deprecated`
- `vendor/filament/infolists/src/Contracts/HasInfolists.php` — empty interface
- `vendor/filament/support/src/Pages/BasePage.php``implements HasSchemas`, uses `InteractsWithSchemas`
- `vendor/filament/support/src/Concerns/InteractsWithSchemas.php` — auto-discovers methods by name
---
## R-002 — OperationRunResource::infolist() Compatibility
**Decision**: Call `OperationRunResource::infolist($schema)` directly from the standalone Page.
**Rationale**: The method is `public static`, uses no `$this` references, and already handles tenantless context gracefully (`Filament::getTenant()` returns null → falls back to `OperationRunLinks::tenantlessView()`).
**Requirements for the standalone Page**:
1. `public function infolist(Schema $schema): Schema` → delegates to `OperationRunResource::infolist($schema)`
2. `public function defaultInfolist(Schema $schema): Schema` → sets `->record($this->run)->columns(2)`
3. `public bool $opsUxIsTabHidden = false` property → needed for polling callback in infolist
4. Override `content()` or render via Blade `{{ $this->infolist }}`
**Alternatives considered**:
- Extracting infolist into a shared trait → Overengineered for one consumer
- Keeping hand-coded Blade → Defeats the single-source goal
---
## R-003 — Headless Resource Pattern (Empty getPages)
**Decision**: Return `[]` from `OperationRunResource::getPages()` to eliminate all auto-generated routes.
**Rationale**: `Resource::routes()` iterates `getPages()` in a `foreach` — empty array means zero route registrations. The resource class is retained as a static utility providing `::table()` and `::infolist()` schema builders.
**Impact**: The following route names will no longer exist:
- `filament.admin.resources.operations.index`
- `filament.admin.resources.operations.view`
**Files that reference these routes** (need updating):
- `tests/Feature/Verification/VerificationAuthorizationTest.php` (L38, L74) — `OperationRunResource::getUrl('view', ...)`
- `tests/Feature/OpsUx/FailureSanitizationTest.php` (L58) — `OperationRunResource::getUrl('view', ...)`
- `tests/Feature/OpsUx/CanonicalViewRunLinksTest.php` (L25) — guard test scanning for stale references (update regex)
- `tests/Feature/Verification/VerificationDbOnlyTest.php``ViewOperationRun` Livewire test
- `tests/Feature/OpsUx/FailureSanitizationTest.php``ViewOperationRun` Livewire test
- `tests/Feature/Verification/VerificationReportRenderingTest.php``ViewOperationRun` Livewire test
- `tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php` (L121) — `ListOperationRuns` Livewire test
- `tests/Feature/Monitoring/OperationsTenantScopeTest.php` (L119) — `ListOperationRuns` Livewire test
**Alternatives considered**:
- Keeping a dummy page that redirects → Adds complexity, spec says natural 404
- Excluding resource from discovery → More fragile than empty `getPages()`
---
## R-004 — KPI Header Tenantless Behavior
**Decision**: Hide `OperationsKpiHeader` when no tenant context is available (Phase 1).
**Rationale**: The widget runs 6 queries all scoped by `tenant_id`. Without tenant context, all queries return 0. Showing zeros is misleading. Workspace-scoped queries are a larger refactor deferred to a separate spec.
**Implementation**: Check `Filament::getTenant()` in the widget's `getStats()` — return empty array if null. Or conditionally register the widget on the page based on tenant presence.
**Source**: `app/Filament/Widgets/Operations/OperationsKpiHeader.php` — 131 lines, 4 stat cards, `$isLazy = false`
---
## R-005 — Legacy List Redirect (FR-078-012)
**Decision**: Add a 302 redirect from `/admin/t/{tenant}/operations` to `/admin/operations`.
**Rationale**: Unlike detail URLs which naturally 404 after page decommission, the list URL pattern may still be reached through Filament's navigation system during the transition period. A simple redirect avoids confusion.
**Note**: This is the only redirect in the spec. All detail-level legacy URLs naturally 404.

View File

@ -1,343 +0,0 @@
# Feature Specification: Operations Tenantless Canonical Migration
**Feature Branch**: `078-operations-tenantless-canonical`
**Created**: 2026-02-06
**Status**: Draft
**Stack**: Filament v5 + Livewire v4 (native only)
**Input**: Eliminate dual "run detail" surfaces (tenant-scoped Filament view vs tenantless canonical viewer) and make Operations truly canonical, supportable, and secure.
---
## 0. Executive Summary
Operations is already **canonical at the index and tenantless detail** (`/admin/operations`, `/admin/operations/{run}`), but **auto-generated tenant-scoped Filament resource routes** still exist as side-effects of panel discovery:
- Tenant-scoped detail: `/admin/t/{tenant}/operations/r/{record}`
- Tenant-scoped list: `/admin/t/{tenant}/operations`
This spec makes the tenantless detail page **the only run detail view**, removes the auto-generated tenant-scoped pages (legacy detail URLs naturally 404), and ensures **deny-as-not-found** security—without introducing non-native UI frameworks.
---
## Clarifications
### Session 2026-02-06
- Q: Should a tenant-scoped legacy URL (`/admin/t/{tenant}/operations/r/{record}`) for a run with `tenant_id = null` be allowed (redirect) or blocked (404)? → A: ~~Allow redirect~~ Superseded — FR-078-005/006 removed; legacy detail URLs naturally 404 after route decommission.
---
## 1. Goals
1. **Single canonical run detail view**`/admin/operations/{run}`
2. **Remove auto-generated tenant-scoped pages** — decommission both `/admin/t/{tenant}/operations/r/{record}` and `/admin/t/{tenant}/operations`
3. **Clean decommission** — legacy tenant-scoped detail URLs naturally 404 after route removal (no redirect handlers needed)
4. **No duplication of UI logic** — reuse `OperationRunResource::infolist()` in the tenantless viewer
5. **Enterprise security semantics** — non-member → 404, no existence leakage
---
## 2. Non-Goals
- Building a new operations dashboard
- Introducing an alerts engine
- Changing operation execution semantics
- Implementing fine-grained `operations.view` capabilities (access remains workspace-membership)
- Workspace-scoped KPI header (tracked separately; header hidden in tenantless mode for Phase 1)
---
## 3. Current State (Baseline)
**Registered routes (today):**
| Route | Pattern | Name | Handler | Scope |
|-------|---------|------|---------|-------|
| Canonical list | `GET /admin/operations` | `admin.operations.index` | `Operations.php` (custom page) | Workspace (session) |
| Canonical detail | `GET /admin/operations/{run}` | `admin.operations.view` | `TenantlessOperationRunViewer.php` | Workspace membership |
| Auto-generated list | `GET /admin/t/{tenant}/operations` | `filament.admin.resources.operations.index` | `ListOperationRuns.php` | Tenant-scoped |
| Auto-generated view | `GET /admin/t/{tenant}/operations/r/{record}` | `filament.admin.resources.operations.view` | `ViewOperationRun.php` | Tenant-scoped |
**Key constraints:**
- Tenant-scoped routes exist because `OperationRunResource` is auto-discovered in a tenant panel (`AdminPanelProvider::discoverResources`).
- All production "View run" links already point to canonical tenantless detail via `OperationRunLinks::view()``OperationRunLinks::tenantlessView()`.
- The resource already declares `$isScopedToTenant = false` and `$shouldRegisterNavigation = false`.
**Link helper state:**
- `OperationRunLinks::view($run, $tenant)` delegates to `tenantlessView($run)` — the `$tenant` parameter is a no-op.
- `OperationRunLinks::related($run, $tenant)` returns up to 11 contextual links (Policies, Inventory, Drift, Backup Sets, Provider Connections, etc.).
- `OperationRunUrl::view()` and `OperationRunUrl::index()` are thin wrappers around `OperationRunLinks`.
---
## 4. Enterprise Principles (Normative)
### P-078-001 — Canonical deep links
There MUST be exactly one canonical URL to open a run: `/admin/operations/{run}`.
### P-078-002 — No tenant context dependency
Canonical run detail MUST render without tenant context and MUST NOT require `/admin/t/{tenant}`.
### P-078-003 — Deny-as-not-found
Any user not entitled to view a run MUST receive **404**, not 403. (Constitution: RBAC-UX-002)
### P-078-004 — No leakage via legacy URLs
Decommissioned tenant-scoped routes MUST NOT exist after migration. Removed routes naturally return 404 — no redirect handlers, no existence leakage.
### P-078-005 — Filament-native
Use Filament pages/resources/infolists/actions and Livewire v4 only. No custom SPA routing.
---
## User Scenarios & Testing
### User Story 1 — View operation run via canonical URL (Priority: P1)
A workspace member clicks a "View run" link (from notification, widget, or operations list) and sees the full run detail at `/admin/operations/{run}` — regardless of whether the run has a tenant or not.
**Why this priority**: This is the core feature — the single canonical detail surface that replaces the dual-surface.
**Independent Test**: Create runs with and without `tenant_id`, navigate to `/admin/operations/{run}`, assert all sections render (summary, target scope, verification report, context JSON).
**Acceptance Scenarios**:
1. **Given** a run with `tenant_id` set and user is workspace member, **When** user visits `/admin/operations/{run}`, **Then** full detail renders including target scope, verification report (if present), summary counts, and context JSON.
2. **Given** a run with `tenant_id = null` (e.g., onboarding run), **When** user visits `/admin/operations/{run}`, **Then** detail renders without crash; target scope shows "No target scope details recorded."
3. **Given** a run with a verification report in context, **When** user visits canonical detail, **Then** verification report section renders correctly with badge rendering and acknowledgements — even though `Filament::getTenant()` returns null.
4. **Given** user is NOT a workspace member, **When** user visits `/admin/operations/{run}`, **Then** 404 (deny-as-not-found).
---
### User Story 2 — Legacy tenant-scoped detail URLs return 404 (Priority: P2)
A user has a bookmarked or old notification link pointing to `/admin/t/{tenant}/operations/r/{record}`. After route decommission, the system returns 404 — no redirect, no existence leakage.
**Why this priority**: Ensures decommissioned routes don't silently serve stale pages or leak information.
**Independent Test**: Hit legacy detail URLs; assert 404 for all users regardless of membership.
**Acceptance Scenarios**:
1. **Given** any user (member or non-member), **When** user visits `/admin/t/{tenant}/operations/r/{record}`, **Then** 404.
2. **Given** any user, **When** user visits `/admin/operations/r/{record}`, **Then** 404 (the `/r/` slug variant also does not exist).
---
### User Story 3 — Contextual navigation from run detail (Priority: P2)
On the canonical detail page, a workspace member sees contextual "Open" actions (e.g., "Open tenant", "Policies", "Backup Set", "Provider Connection") based on the run's context — using the existing `OperationRunLinks::related()` mechanism.
**Why this priority**: Replaces the "Admin details" back-link with richer, already-implemented navigation.
**Independent Test**: Create runs of different types, verify that the related links appear in the header actions group.
**Acceptance Scenarios**:
1. **Given** a run of type `policy.sync` with `policy_id` in context, **When** viewing canonical detail, **Then** header shows "Open" group with links to Operations index, Policy, and Policies list.
2. **Given** a run with `tenant_id` and user is tenant member, **When** viewing canonical detail, **Then** related links include tenant-scoped resources (via `OperationRunLinks::related()`).
3. **Given** a run with `tenant_id = null`, **When** viewing canonical detail, **Then** no tenant-specific related links appear; only generic links (Operations index).
---
### User Story 4 — Operations list remains workspace-scoped (Priority: P3)
The `/admin/operations` page continues to show all runs for the current workspace, with an optional tenant default filter when tenant context is active.
**Why this priority**: Existing behavior; this story ensures no regression during migration.
**Independent Test**: Visit `/admin/operations` with and without tenant context; verify workspace scoping and default filter behavior.
**Acceptance Scenarios**:
1. **Given** workspace context set but no tenant context, **When** visiting `/admin/operations`, **Then** all workspace runs shown.
2. **Given** tenant context active, **When** visiting `/admin/operations`, **Then** tenant filter defaults to active tenant but can be cleared to show all.
---
### Edge Cases
- Run with `workspace_id = 0` or null → 404 (existing behavior in `OperationRunPolicy::view`)
- Run exists but requesting user has no workspace membership → 404 (deny-as-not-found)
- Verification report section with `Filament::getTenant()` returning null → falls back to `OperationRunLinks::tenantlessView()` for previous-run URLs (already handled in infolist)
- Legacy tenant-scoped URLs (`/admin/t/{tenant}/operations/r/{record}`) → 404 (routes no longer registered after decommission)
---
## Requirements
**Constitution alignment (RBAC-UX):**
- Authorization plane: Workspace-level (not tenant-level). Operations detail requires workspace membership only.
- 404 vs 403: Non-member → 404 (RBAC-UX-002). No capability-gating for view-only operations access in this spec.
- Server-side enforcement: `OperationRunPolicy::view()` + `WorkspaceMembership` check in `TenantlessOperationRunViewer::mount()`.
- Legacy tenant-scoped routes are decommissioned (naturally 404); no redirect handlers needed (P-078-004).
- Global search: `OperationRunResource` has `$shouldRegisterNavigation = false` and no `$recordTitleAttribute` — not globally searchable.
**Constitution alignment (OPS-EX-AUTH-001):** Not applicable — no auth handshakes involved.
**Constitution alignment (BADGE-001):** No badge changes. Existing badge mappings (`OperationRunStatus`, `OperationRunOutcome`) are reused via shared `BadgeRenderer` in the reused infolist.
### Functional Requirements
#### 5.1 Canonical Run Detail — Feature-Complete Tenantless Page
- **FR-078-001**: `GET /admin/operations/{run}` MUST display: run summary (status/outcome/timestamps/initiator), target scope, verification report (DB-only), summary counts, failure summary, and context JSON (redacted).
- **FR-078-002**: Tenantless detail page MUST reuse `OperationRunResource::infolist()` via Filament v5's native schema system. `TenantlessOperationRunViewer` MUST define `public function infolist(Schema $schema): Schema` delegating to `OperationRunResource::infolist($schema)`, provide `defaultInfolist(Schema $schema)` to bind `->record($this->run)->columns(2)`, and render the schema via `{{ $this->infolist }}` (or `EmbeddedSchema::make('infolist')` in `content()`).
- **FR-078-003**: Tenantless detail MUST reuse `OperationRunLinks::related($run, $tenant)` for contextual header actions (replacing the removed "Admin details" button). If `$run->tenant` is null, only generic links (Operations index) appear.
#### 5.2 Decommission Auto-Generated Tenant-Scoped Pages
- **FR-078-004**: Remove the `'view'` page entry from `OperationRunResource::getPages()` and delete `ViewOperationRun.php`. This eliminates the auto-generated `/admin/t/{tenant}/operations/r/{record}` route.
- **FR-078-011**: Remove the `'index'` page entry from `OperationRunResource::getPages()` and delete `ListOperationRuns.php`. This eliminates the auto-generated `/admin/t/{tenant}/operations` route. The resource retains only its `table()` and `infolist()` schema builders for reuse by the custom pages.
#### 5.3 Legacy URL Handling
Legacy detail URLs (`/admin/t/{tenant}/operations/r/{record}` and `/admin/operations/r/{record}`) naturally return 404 after route decommission — no redirect handlers are needed. ~~FR-078-005 and FR-078-006 removed.~~
- **FR-078-012**: Add a convenience redirect for `GET /admin/t/{tenant}/operations`:
1. Redirect **302** to `/admin/operations`.
Note: No auth check needed since `/admin/operations` already enforces workspace membership.
#### 5.4 KPI Header Handling (Phase 1 Simplification)
- **FR-078-008**: `OperationsKpiHeader` widget MUST continue to render when tenant context is available. When no tenant context exists (tenantless pages), the KPI header SHOULD be hidden (not rendered) rather than showing zeros. Full workspace-scoped KPI support is deferred to a follow-up spec.
- **FR-078-009**: Polling/active-run queries on the canonical list page (`Operations.php`) MUST handle `tenant_id = null` runs and tenantless rendering safely. This MUST be verified by an explicit regression test covering list rendering with and without tenant context.
#### 5.5 Dead Code Cleanup
- **FR-078-010**: Delete `app/Livewire/Monitoring/OperationsDetail.php` and its Blade view `resources/views/livewire/monitoring/operations-detail.blade.php`. This component is unreferenced dead code that enforces an obsolete tenant-only abort check.
### Key Entities
- **OperationRun**: The central model. Has `workspace_id` (required for authorization), `tenant_id` (nullable — onboarding/provider-check runs may lack it), `context` (JSONB with target_scope, verification_report, etc.), `summary_counts`, `failure_summary`.
- **WorkspaceMembership**: The authorization boundary. View access requires membership in the run's workspace.
- **OperationRunLinks**: Centralized link helper. `view()``tenantlessView()` (already canonical). `related()` provides contextual navigation links.
---
## Success Criteria
### Measurable Outcomes
- **SC-001**: Exactly one canonical run detail URL exists: `/admin/operations/{run}`. The route `filament.admin.resources.operations.view` is no longer registered.
- **SC-002**: All "View run" links across notifications, widgets, tables, and jobs resolve to `/admin/operations/{run}` (no tenant-scoped detail links remain).
- **SC-003**: Legacy tenant-scoped detail URLs return 404 after route decommission (no redirect handlers, no information leakage).
- **SC-004**: Runs with `tenant_id = null` render on canonical detail without errors.
- **SC-005**: Verification report section renders correctly on canonical detail when `Filament::getTenant()` returns null.
- **SC-006**: All existing Pest tests pass after migration (no regressions).
---
## Security & RBAC
### SR-078-001 — View permissions
- Viewing operations list and run detail requires workspace membership (baseline).
- Non-member → 404 (deny-as-not-found, per RBAC-UX-002).
- No fine-grained capabilities for operations view in this spec.
### SR-078-002 — No sensitive leakage in context JSON
- Context JSON shown in UI uses allowlist-based redaction (existing behavior).
- The verification report section already sanitizes sensitive data.
---
## UX Requirements
### UX-078-001 — Consistent CTA label
All run CTAs MUST use the canonical label per ux-contracts.md:
- **"View run"** (exact casing)
### UX-078-002 — Context navigation via related links
Canonical detail header MUST show an "Open" action group populated by `OperationRunLinks::related()`. This provides all relevant contextual links (Operations index, Provider Connection, Policies, Backup Sets, Restore Runs, Drift, Inventory, etc.) based on run type and context.
### UX-078-003 — Empty/missing target scope
If target scope is missing: show the existing non-blocking text "No target scope details were recorded for this run." Do not crash; degrade gracefully.
---
## Tests (Mandatory)
### T-078-001 — Canonical run detail renders without tenant context
- Create run with `tenant_id = null` and with `tenant_id` set
- Assert `/admin/operations/{run}` renders summary sections without crash
### T-078-002 — Legacy tenant-scoped detail URLs return 404
- Any user visiting `/admin/t/{tenant}/operations/r/{record}` → 404 (route not registered)
- Any user visiting `/admin/operations/r/{record}` → 404 (route not registered)
### T-078-004 — No auto-generated tenant-scoped routes exist
- Assert route names `filament.admin.resources.operations.view` and `filament.admin.resources.operations.index` are not registered (or return 404)
### T-078-005 — No "Admin details" link on canonical detail
- Assert canonical detail page does not render `/admin/t/.../operations/r/...` links
### T-078-006 — KPI header hidden in tenantless mode
- On `/admin/operations` without tenant context, KPI header does not render (or renders gracefully)
### T-078-007 — DB-only rendering
- Rendering canonical detail does not dispatch jobs or perform HTTP calls (existing guard tests remain valid)
### T-078-008 — Verification report renders on tenantless detail
- Create run with verification report in context and `tenant_id` set
- Visit `/admin/operations/{run}` without `Filament::getTenant()` set
- Assert verification report section renders (badge, acknowledgements, change indicator with tenantless previous-run URL)
### T-078-009 — Tenant-scoped list redirect
- `/admin/t/{tenant}/operations` redirects (302) to `/admin/operations`
### T-078-010 — Related links appear on canonical detail
- Create run of type `restore.execute` with `restore_run_id` in context
- Assert header actions include "Restore Run" link
### T-078-011 — Operations list tenantless safety
- Visit `/admin/operations` with and without tenant context
- Assert list renders successfully and includes `tenant_id = null` runs without polling/query errors
### T-078-012 — Canonical CTA label consistency
- Assert run entry points use the exact label **"View run"**
- Assert canonical detail no longer shows the legacy "Admin details" CTA
---
## Acceptance Criteria
- ✅ Exactly one canonical run detail URL: `/admin/operations/{run}`
- ✅ Auto-generated tenant-scoped routes (list + view) are removed; legacy detail URLs return 404
- ✅ No "Admin details" / tenant-scoped back-links from canonical pages
- ✅ Operations list works in workspace mode; tenant context only adds default filter
- ✅ Runs with `tenant_id = null` display safely
- ✅ Verification report renders correctly without tenant context
- ✅ Related contextual links (from `OperationRunLinks::related()`) replace the removed "Admin details" button
- ✅ Dead code (`OperationsDetail.php` + Blade view) removed
- ✅ Tests cover 404 semantics, infolist rendering, and canonical link rules
- ✅ Implementation is Filament v5 + Livewire v4 native only
---
## Implementation Notes (Non-Normative)
### Infolist Reuse Strategy
Use Filament v5's native schema flow on the standalone page:
- Define `infolist(Schema $schema)` and delegate to `OperationRunResource::infolist($schema)`
- Define `defaultInfolist(Schema $schema)` with `->record($this->run)->columns(2)`
- Render with `{{ $this->infolist }}` (and use `EmbeddedSchema::make('infolist')` from `content()` when needed)
### Resource After Decommission
After removing both page entries from `getPages()`, `OperationRunResource` becomes a "headless" resource — it provides `table()` and `infolist()` schema builders reused by:
- `Operations.php` (custom list page, via `OperationRunResource::table($table)`)
- `TenantlessOperationRunViewer` (canonical detail, via infolist delegation)
The resource class itself is retained; only its auto-generated routes are eliminated.
### KPI Header Deferral
`OperationsKpiHeader` currently queries 6 times by `tenant_id` and uses `ActiveRuns::existForTenant()`. Full workspace-scoping requires adding `existForWorkspace()` to `ActiveRuns` and refactoring all 6 queries. This is deferred to a separate spec to keep this migration focused. Phase 1 simply hides the KPI header when tenant context is absent.
---
## Open Decisions
- **"Copy JSON" capability-gating**: Recommended for enterprise environments but not in scope for this spec.

View File

@ -1,262 +0,0 @@
# Tasks: Operations Tenantless Canonical Migration
**Input**: Design documents from `/specs/078-operations-tenantless-canonical/`
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
**Tests**: Tests are REQUIRED (Pest). This feature changes runtime routing and rendering behavior.
**Operations**: No new operations introduced. Existing `OperationRun` model is read-only in this feature.
**RBAC**: Authorization unchanged — workspace membership enforced via `OperationRunPolicy::view()`. Non-member gets 404 (deny-as-not-found). No new capabilities, no destructive actions.
**Badges**: No badge changes. Existing `BadgeRenderer` reused via shared infolist schema.
**Organization**: Tasks are grouped by user story. US1 (P1) is the MVP. US2/US3 (P2) can proceed in parallel after foundational phase. US4 (P3) is independent.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (US1, US2, US3, US4)
- Exact file paths included in descriptions
## Path Conventions
- Standard Laravel monolith: `app/`, `resources/`, `routes/`, `tests/`, `config/`
- New spec tests: `tests/Feature/078/`
---
## Phase 1: Setup
**Purpose**: Create test directory and verify branch readiness
- [X] T001 Create spec test directory `tests/Feature/078/`
- [X] T002 Verify branch is clean and on `078-operations-tenantless-canonical`
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Make `OperationRunResource` headless, delete decommissioned pages, delete dead code, and fix all existing tests that reference deleted classes/routes. This phase MUST complete before any user story work.
**Why blocking**: US1 needs ViewOperationRun deleted so infolist lives on standalone page. US2 needs routes removed. US3 needs the viewer to be the sole detail surface. All existing tests must pass after this phase.
- [X] T003 Change `getPages()` to return `[]` in `app/Filament/Resources/OperationRunResource.php`
- [X] T004 [P] Delete `app/Filament/Resources/OperationRunResource/Pages/ViewOperationRun.php`
- [X] T005 [P] Delete `app/Filament/Resources/OperationRunResource/Pages/ListOperationRuns.php`
- [X] T006 [P] Delete `app/Livewire/Monitoring/OperationsDetail.php` (dead code)
- [X] T007 [P] Delete `resources/views/livewire/monitoring/operations-detail.blade.php` (dead code)
- [X] T008 Update `tests/Feature/Verification/VerificationAuthorizationTest.php` — replace `OperationRunResource::getUrl('view', ...)` with `route('admin.operations.view', ...)` and replace `ViewOperationRun` Livewire mount with `TenantlessOperationRunViewer`
- [X] T009 [P] Update `tests/Feature/OpsUx/FailureSanitizationTest.php` — replace `OperationRunResource::getUrl('view', ...)` with canonical route; replace `ViewOperationRun` mount with `TenantlessOperationRunViewer`
- [X] T010 [P] Update `tests/Feature/OpsUx/CanonicalViewRunLinksTest.php` — update guard regex to account for headless resource (no `getUrl` calls exist)
- [X] T011 [P] Update `tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php` — replace `ViewOperationRun` mount with `TenantlessOperationRunViewer`
- [X] T012 [P] Update `tests/Feature/Verification/VerificationReportRedactionTest.php` + `tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php` — replace `ViewOperationRun` mounts with `TenantlessOperationRunViewer`
- [X] T013 [P] Update `tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php` — remove `ListOperationRuns` test block; add route-not-registered assertion for `filament.admin.resources.operations.index`
- [X] T014 [P] Update `tests/Feature/Monitoring/OperationsTenantScopeTest.php` — remove `ListOperationRuns` reference
- [X] T015 Run `grep -r "ViewOperationRun\|ListOperationRuns" app/ tests/ resources/` to verify no stale references remain
- [X] T016 Run existing test suite for affected files: `vendor/bin/sail artisan test --compact tests/Feature/Verification/ tests/Feature/OpsUx/ tests/Feature/Monitoring/ tests/Feature/Operations/`
**Checkpoint**: All existing tests pass. Resource is headless. Dead code removed. No stale references.
---
## Phase 3: User Story 1 — View operation run via canonical URL (Priority: P1) MVP
**Goal**: The canonical detail page at `/admin/operations/{run}` renders with full Filament infolist (summary, target scope, verification report, counts, context JSON) — replacing the current hand-coded Blade with `OperationRunResource::infolist()` reuse via the unified schema system.
**Independent Test**: Create runs with and without `tenant_id`, visit `/admin/operations/{run}`, assert all infolist sections render.
### Tests for User Story 1
- [X] T017 [P] [US1] Write test T-078-001 (canonical detail renders with tenant_id) in `tests/Feature/078/CanonicalDetailRenderTest.php` — create OperationRun with tenant_id, visit canonical URL as workspace member, assert 200 + infolist sections visible (status badge, outcome, timestamps, target scope, summary counts)
- [X] T018 [P] [US1] Write test T-078-001 (canonical detail renders without tenant_id) in `tests/Feature/078/CanonicalDetailRenderTest.php` — create OperationRun with tenant_id=null, visit canonical URL, assert 200 + graceful rendering ("No target scope details")
- [X] T019 [P] [US1] Write test T-078-001 (non-member gets 404) in `tests/Feature/078/CanonicalDetailRenderTest.php` — visit as non-member, assert 404
- [X] T020 [P] [US1] Write test T-078-008 (verification report renders tenantless) in `tests/Feature/078/VerificationReportTenantlessTest.php` — create run with verification_report in context, visit canonical URL, assert verification section renders with badges and acknowledgements
- [X] T021 [P] [US1] Write test T-078-007 (DB-only rendering) in `tests/Feature/078/CanonicalDetailRenderTest.php` — assert canonical detail rendering does not dispatch jobs or HTTP calls
### Implementation for User Story 1
- [X] T022 [US1] Add `public function infolist(Schema $schema): Schema` to `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` — delegates to `OperationRunResource::infolist($schema)`
- [X] T023 [US1] Add `public function defaultInfolist(Schema $schema): Schema` to `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` — sets `->record($this->run)->columns(2)`
- [X] T024 [US1] Add `public bool $opsUxIsTabHidden = false` property to `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` (required for polling callback in infolist)
- [X] T025 [US1] Add `public function content(Schema $schema): Schema` to `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` returning `EmbeddedSchema::make('infolist')`
- [X] T026 [US1] Replace hand-coded HTML in `resources/views/filament/pages/operations/tenantless-operation-run-viewer.blade.php` with infolist render (`{{ $this->infolist }}`)
- [X] T027 [US1] Run tests: `vendor/bin/sail artisan test --compact tests/Feature/078/CanonicalDetailRenderTest.php tests/Feature/078/VerificationReportTenantlessTest.php tests/Feature/Operations/TenantlessOperationRunViewerTest.php`
**Checkpoint**: Canonical detail at `/admin/operations/{run}` renders full Filament infolist. Runs with and without tenant_id render correctly. MVP is functional.
---
## Phase 4: User Story 2 — Legacy tenant-scoped detail URLs return 404 (Priority: P2)
**Goal**: Verify that decommissioned tenant-scoped routes naturally return 404. No redirect handlers, no existence leakage.
**Independent Test**: Hit legacy detail URLs; assert 404 for all users.
**Note**: The actual route removal was done in Phase 2 (Foundational). This phase adds the spec-required tests that validate the behavior.
### Tests for User Story 2
- [X] T028 [P] [US2] Write test T-078-002 (legacy detail URL returns 404) in `tests/Feature/078/LegacyRoutesReturnNotFoundTest.php` — visit `/admin/t/{tenant}/operations/r/{record}` as any user, assert 404
- [X] T029 [P] [US2] Write test T-078-002 (slug variant returns 404) in `tests/Feature/078/LegacyRoutesReturnNotFoundTest.php` — visit `/admin/operations/r/{record}`, assert 404
- [X] T030 [P] [US2] Write test T-078-004 (auto-generated route names not registered) in `tests/Feature/078/LegacyRoutesReturnNotFoundTest.php` — assert `Route::has('filament.admin.resources.operations.view')` is false and `Route::has('filament.admin.resources.operations.index')` is false
### Implementation for User Story 2
> No additional implementation needed — routes were removed in Phase 2.
- [X] T031 [US2] Run tests: `vendor/bin/sail artisan test --compact tests/Feature/078/LegacyRoutesReturnNotFoundTest.php`
**Checkpoint**: All legacy URLs return 404. Route names are not registered. No existence leakage.
---
## Phase 5: User Story 3 — Contextual navigation from run detail (Priority: P2)
**Goal**: Replace the "Admin details" button on canonical detail with `OperationRunLinks::related()` action group in header actions — providing richer contextual navigation (Operations index, Policy, Backup Set, Restore Run, etc.).
**Independent Test**: Create runs of different types, verify related links appear in header actions and "Admin details" link is absent.
### Tests for User Story 3
- [X] T032 [P] [US3] Write test T-078-010 (related links appear) in `tests/Feature/078/RelatedLinksOnDetailTest.php` — create run of type `restore.execute` with `restore_run_id` in context, visit canonical detail, assert header actions include "Restore Run" link
- [X] T033 [P] [US3] Write test T-078-010 (generic links for tenantless run) in `tests/Feature/078/RelatedLinksOnDetailTest.php` — create run with tenant_id=null, assert only generic links (Operations index) appear
- [X] T034 [P] [US3] Write tests T-078-005 + T-078-012 in `tests/Feature/078/RelatedLinksOnDetailTest.php` — assert canonical detail does not render `/admin/t/.../operations/r/...` links and uses exact CTA label "View run" (legacy "Admin details" absent)
### Implementation for User Story 3
- [X] T035 [US3] Add `getHeaderActions()` method to `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php` — return actions from `OperationRunLinks::related($this->run, $this->run->tenant)`
- [X] T036 [US3] Remove "Admin details" button code (~line 61) from `app/Filament/Pages/Operations/TenantlessOperationRunViewer.php`
- [X] T037 [US3] Run tests: `vendor/bin/sail artisan test --compact tests/Feature/078/RelatedLinksOnDetailTest.php`
**Checkpoint**: Header shows contextual "Open" action group. "Admin details" link is gone. Related links vary by run type.
---
## Phase 6: User Story 4 — Operations list remains workspace-scoped (Priority: P3)
**Goal**: Ensure no regression on `/admin/operations` list. KPI header hidden in tenantless mode. 302 redirect for decommissioned list URL.
**Independent Test**: Visit `/admin/operations` with and without tenant context; verify workspace scoping, KPI behavior, and redirect.
### Tests for User Story 4
- [X] T038 [P] [US4] Write test T-078-006 (KPI header hidden without tenant) in `tests/Feature/078/KpiHeaderTenantlessTest.php` — visit `/admin/operations` without tenant context, assert KPI stats are not rendered (empty array from `getStats()`)
- [X] T039 [P] [US4] Write test T-078-009 (tenant-scoped list redirect) in `tests/Feature/078/TenantListRedirectTest.php` — visit `/admin/t/{tenant}/operations`, assert 302 redirect to `/admin/operations`
- [X] T048 [P] [US4] Write test T-078-011 (tenantless list query safety) in `tests/Feature/078/OperationsListTenantlessSafetyTest.php` — visit `/admin/operations` with and without tenant context, assert runs including `tenant_id = null` render without errors
### Implementation for User Story 4
- [X] T040 [US4] Add tenant-null guard in `getStats()` of `app/Filament/Widgets/Operations/OperationsKpiHeader.php` — if `Filament::getTenant()` is null, return `[]`
- [X] T041 [US4] Add 302 redirect route in `routes/web.php``/admin/t/{tenant}/operations` redirects to `/admin/operations` (FR-078-012)
- [X] T042 [US4] Run tests: `vendor/bin/sail artisan test --compact tests/Feature/078/KpiHeaderTenantlessTest.php tests/Feature/078/TenantListRedirectTest.php tests/Feature/078/OperationsListTenantlessSafetyTest.php`
**Checkpoint**: Operations list works in workspace mode. KPI hidden without tenant. List redirect works.
---
## Phase 7: Polish & Cross-Cutting Concerns
**Purpose**: Final validation, formatting, and stale reference sweep
- [X] T043 Run `grep -r "ViewOperationRun\|ListOperationRuns\|OperationsDetail" app/ tests/ resources/` — verify zero stale references across entire codebase
- [X] T044 Run `vendor/bin/sail bin pint --dirty` — fix any formatting issues
- [X] T049 Remove obsolete temporary layout `resources/views/filament/layouts/topbar-only.blade.php`
- [X] T045 Run focused test pack: `vendor/bin/sail artisan test --compact tests/Feature/078/ tests/Feature/Operations/TenantlessOperationRunViewerTest.php tests/Feature/Monitoring/OperationsCanonicalUrlsTest.php tests/Feature/Monitoring/OperationsTenantScopeTest.php tests/Feature/Verification/VerificationAuthorizationTest.php tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php tests/Feature/Verification/VerificationReportRedactionTest.php tests/Feature/Verification/VerificationReportMissingOrMalformedTest.php tests/Feature/OpsUx/FailureSanitizationTest.php tests/Feature/OpsUx/CanonicalViewRunLinksTest.php`
- [X] T046 Run quickstart.md validation: `vendor/bin/sail artisan route:list --name=filament.admin.resources.operations` — assert empty output
- [X] T047 Ask user if they want to run the full test suite: `vendor/bin/sail artisan test --compact`
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies — start immediately
- **Foundational (Phase 2)**: Depends on Phase 1 — BLOCKS all user stories
- **US1 (Phase 3)**: Depends on Phase 2 completion (resource must be headless first)
- **US2 (Phase 4)**: Depends on Phase 2 completion (routes must be removed)
- **US3 (Phase 5)**: Depends on Phase 3 completion (viewer must have infolist before adding header actions)
- **US4 (Phase 6)**: Depends on Phase 2 completion only (independent of US1/US2/US3)
- **Polish (Phase 7)**: Depends on all desired user stories being complete
### User Story Dependencies
- **US1 (P1)**: After Phase 2 — no other story dependencies. **This is the MVP.**
- **US2 (P2)**: After Phase 2 — independent of US1 (tests only, implementation in Phase 2)
- **US3 (P2)**: After US1 (Phase 3) — needs infolist on viewer before adding header actions
- **US4 (P3)**: After Phase 2 — independent of US1/US2/US3
### Within Each User Story
- Tests written FIRST, verified to FAIL before implementation
- Implementation follows test guidance
- Story checkpoint validates independently
### Parallel Opportunities
After Phase 2 completes:
- **US1 and US2 and US4** can proceed in parallel (different files, no dependencies)
- US3 must wait for US1 (same file: TenantlessOperationRunViewer.php)
Within Phase 2:
- T004, T005, T006, T007 (file deletions) can all run in parallel
- T008-T014 (test file updates) can all run in parallel
Within Phase 3 (US1):
- T017-T021 (test writing) can all run in parallel
- T022-T026 (implementation) are sequential (same file)
---
## Parallel Example: After Phase 2
```
# US1 (developer/agent A):
T017-T021: Write US1 tests (parallel)
T022-T026: Implement infolist reuse (sequential, same file)
T027: Run US1 tests
# US2 (developer/agent B — can run simultaneously):
T028-T030: Write US2 tests (parallel)
T031: Run US2 tests
# US4 (developer/agent C — can run simultaneously):
T038-T039: Write US4 tests (parallel)
T040-T041: Implement KPI guard + redirect
T042: Run US4 tests
# US3 (must wait for US1):
T032-T034: Write US3 tests (parallel)
T035-T036: Implement related links
T037: Run US3 tests
```
---
## Implementation Strategy
### MVP First (User Story 1 Only)
1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (headless resource + dead code + test fixes)
3. Complete Phase 3: User Story 1 (infolist reuse on canonical detail)
4. **STOP and VALIDATE**: Canonical detail renders full infolist for all run types
5. This is deployable as MVP — core value delivered
### Incremental Delivery
1. Setup + Foundational -> Foundation ready (all existing tests pass)
2. Add US1 -> Canonical detail has full infolist (MVP!)
3. Add US2 -> Legacy URLs confirmed 404 (validation tests)
4. Add US3 -> Related links replace "Admin details" button
5. Add US4 -> KPI hidden + list redirect
6. Polish -> Full sweep, formatting, final validation
---
## Notes
- All tests use Pest (not PHPUnit class syntax)
- Use existing `OperationRun` factory for test data setup
- `TenantlessOperationRunViewer` is the sole detail surface after migration
- `OperationRunResource` retained as headless utility (provides `::table()` and `::infolist()`)
- No new migrations, no new models, no new dependencies
- Total: 47 tasks across 7 phases

View File

@ -1,19 +0,0 @@
# Plan: Inventory links support non-UUID IDs
**Branch**: `079-inventory-links-non-uuid-ids`
**Date**: 2026-02-07
## Approach
- Add a PostgreSQL migration to change `inventory_links.source_id` and `inventory_links.target_id` from `uuid` to `text`.
- Add a pgsql-specific test that asserts the column types are `text` and that upserting an edge with a non-UUID `target_id` does not error.
## Safety
- Change is limited to `inventory_links` columns only.
- Unique constraint and indexes continue to function on `text` columns.
## Testing
- Pest feature test under `tests/Feature/Inventory/`.
- Run focused test + existing inventory extraction tests.

View File

@ -1,22 +0,0 @@
# Spec 079: Inventory links support non-UUID IDs
**Date**: 2026-02-07
## Problem
Inventory dependency extraction writes edges into `inventory_links`. Some Microsoft Graph / Intune identifiers (notably scope tag IDs) can be non-UUID strings (e.g. `"0"`). The current schema defines `inventory_links.source_id` and `inventory_links.target_id` as UUID columns, causing PostgreSQL failures when non-UUID identifiers are inserted.
## Goal
Allow storing non-UUID identifiers in `inventory_links` without crashing inventory sync/extraction.
## Requirements
- `inventory_links.source_id` and `inventory_links.target_id` must accept arbitrary string identifiers.
- Existing UUID identifiers must continue to work.
- Behavior must be covered by tests.
## Non-goals
- No redesign of the dependency graph model.
- No UI/Filament changes.

View File

@ -1,18 +0,0 @@
# Tasks: Inventory links support non-UUID IDs
## Phase 1: Spec + setup
- [X] T001 Create spec folder and docs
## Phase 2: Tests (TDD)
- [X] T002 Add pgsql schema regression test in `tests/Feature/Inventory/InventoryLinksNonUuidIdsTest.php`
## Phase 3: Implementation
- [X] T003 Add migration to change `inventory_links.source_id` + `target_id` to `text` on PostgreSQL
## Phase 4: Validation
- [X] T004 Run tests: `vendor/bin/sail artisan test --compact tests/Feature/Inventory/InventoryLinksNonUuidIdsTest.php`
- [X] T005 Run Pint: `vendor/bin/sail bin pint --dirty`

View File

@ -1,129 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;
final class CanonicalDetailRenderTest extends TestCase
{
use RefreshDatabase;
public function test_renders_canonical_detail_for_a_workspace_member_when_tenant_context_exists(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
Filament::setTenant(null, true);
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'policy.sync',
'status' => 'completed',
'outcome' => 'succeeded',
'context' => [
'target_scope' => [
'entra_tenant_name' => 'Contoso',
'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
],
],
'summary_counts' => [
'total' => 10,
'processed' => 10,
'succeeded' => 10,
'failed' => 0,
'skipped' => 0,
],
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Operation run')
->assertSee('Policy sync')
->assertSee('Counts')
->assertSee('Context')
->assertSee('Contoso');
}
public function test_renders_canonical_detail_gracefully_when_tenant_id_is_null(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
Filament::setTenant(null, true);
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => null,
'type' => 'provider.connection.check',
'status' => 'completed',
'outcome' => 'failed',
'context' => [],
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('No target scope details were recorded for this run.');
}
public function test_returns_404_on_canonical_detail_for_non_members(): void
{
$tenant = Tenant::factory()->create();
[$otherUser] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'policy.sync',
'status' => 'completed',
'outcome' => 'succeeded',
]);
$this->actingAs($otherUser)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertNotFound();
}
public function test_renders_canonical_detail_db_only_with_no_job_dispatch(): void
{
Bus::fake();
Queue::fake();
[$user, $tenant] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'provider.connection.check',
'status' => 'completed',
'outcome' => 'failed',
'context' => [
'verification_report' => json_decode(
(string) file_get_contents(base_path('specs/074-verification-checklist/contracts/examples/fail.json')),
true,
512,
JSON_THROW_ON_ERROR,
),
],
]);
assertNoOutboundHttp(function () use ($user, $run): void {
$this->actingAs($user)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Verification report');
});
Bus::assertNothingDispatched();
Queue::assertNothingPushed();
}
}

View File

@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class KpiHeaderTenantlessTest extends TestCase
{
use RefreshDatabase;
public function test_hides_operations_kpi_stats_when_tenant_context_is_absent(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
OperationRun::factory()->count(3)->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.index'))
->assertOk()
->assertDontSee('Total Runs (30 days)')
->assertDontSee('Failed/Partial (7 days)')
->assertDontSee('Avg Duration (7 days)');
}
}

View File

@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
final class LegacyRoutesReturnNotFoundTest extends TestCase
{
use RefreshDatabase;
public function test_returns_404_for_legacy_tenant_scoped_operation_detail_urls(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
]);
$this->actingAs($user)
->get('/admin/t/'.$tenant->external_id.'/operations/r/'.$run->getKey())
->assertNotFound();
}
public function test_returns_404_for_the_admin_operations_r_record_legacy_slug_variant(): void
{
[$user] = createUserWithTenant(role: 'owner');
$this->actingAs($user)
->get('/admin/operations/r/123')
->assertNotFound();
}
public function test_does_not_register_legacy_operation_resource_route_names(): void
{
$this->assertFalse(Route::has('filament.admin.resources.operations.view'));
$this->assertFalse(Route::has('filament.admin.resources.operations.index'));
}
}

View File

@ -1,78 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class OperationsListTenantlessSafetyTest extends TestCase
{
use RefreshDatabase;
public function test_renders_workspace_operations_list_with_tenantless_runs_when_no_tenant_context_is_set(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => null,
'type' => 'provider.connection.check',
'initiator_name' => 'Tenantless run',
'status' => 'queued',
'outcome' => 'pending',
]);
OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'policy.sync',
'initiator_name' => 'Tenant run',
'status' => 'queued',
'outcome' => 'pending',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.index'))
->assertOk()
->assertSee('Tenantless run')
->assertSee('Tenant run');
}
public function test_renders_workspace_operations_list_safely_with_tenant_context_and_tenantless_records_present(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => null,
'type' => 'provider.connection.check',
'initiator_name' => 'Tenantless run',
'status' => 'queued',
'outcome' => 'pending',
]);
OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'policy.sync',
'initiator_name' => 'Tenant run',
'status' => 'queued',
'outcome' => 'pending',
]);
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.index'))
->assertOk()
->assertSee('Tenant run')
->assertDontSee('Tenantless run');
}
}

View File

@ -1,94 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Models\RestoreRun;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class RelatedLinksOnDetailTest extends TestCase
{
use RefreshDatabase;
public function test_shows_restore_related_links_on_canonical_detail_for_restore_execute_runs(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
$restoreRun = RestoreRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
]);
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'restore.execute',
'context' => [
'restore_run_id' => (int) $restoreRun->getKey(),
],
]);
$expectedUrl = OperationRunLinks::related($run->loadMissing('tenant'), $tenant)['Restore Run'] ?? null;
$response = $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Open')
->assertSee('Restore Run');
$this->assertIsString($expectedUrl);
$response->assertSee((string) $expectedUrl, false);
}
public function test_shows_only_generic_links_for_tenantless_runs_on_canonical_detail(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => null,
'type' => 'restore.execute',
'context' => [
'restore_run_id' => 999,
],
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Operations')
->assertSee(route('admin.operations.index'), false)
->assertDontSee('Restore Run');
}
public function test_does_not_show_legacy_admin_details_cta_and_keeps_canonical_view_run_label(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'type' => 'policy.sync',
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertDontSee('Admin details')
->assertDontSee('/admin/t/'.$tenant->external_id.'/operations/r/'.$run->getKey(), false);
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.index'))
->assertOk()
->assertSee('View run');
}
}

View File

@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class TenantListRedirectTest extends TestCase
{
use RefreshDatabase;
public function test_redirects_legacy_tenant_scoped_operations_list_url_to_canonical_operations_index(): void
{
[$user, $tenant] = createUserWithTenant(role: 'owner');
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get('/admin/t/'.$tenant->external_id.'/operations')
->assertStatus(302)
->assertRedirect(route('admin.operations.index'));
}
}

View File

@ -1,63 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class VerificationReportTenantlessTest extends TestCase
{
use RefreshDatabase;
public function test_renders_verification_report_on_canonical_detail_without_filament_tenant_context(): void
{
[$user, $tenant] = createUserWithTenant(role: 'operator');
$report = json_decode(
(string) file_get_contents(base_path('specs/074-verification-checklist/contracts/examples/fail.json')),
true,
512,
JSON_THROW_ON_ERROR,
);
$previousRun = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'user_id' => (int) $user->getKey(),
'type' => 'provider.connection.check',
'status' => 'completed',
'outcome' => 'failed',
'context' => [
'verification_report' => $report,
],
]);
$report['previous_report_id'] = (int) $previousRun->getKey();
$run = OperationRun::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(),
'user_id' => (int) $user->getKey(),
'type' => 'provider.connection.check',
'status' => 'completed',
'outcome' => 'failed',
'context' => [
'verification_report' => $report,
],
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Verification report')
->assertSee('Open previous verification')
->assertSee('/admin/operations/'.((int) $previousRun->getKey()), false)
->assertSee('Token acquisition works');
}
}

View File

@ -52,7 +52,7 @@
->assertDontSee($tenantB->name); ->assertDontSee($tenantB->name);
}); });
test('user menu does not render a workspace switcher (topbar context bar is the single entry point)', function () { test('user menu renders a workspace switcher when a workspace is selected', function () {
[$user, $tenant] = createUserWithTenant(); [$user, $tenant] = createUserWithTenant();
$workspace = Workspace::query()->whereKey($tenant->workspace_id)->firstOrFail(); $workspace = Workspace::query()->whereKey($tenant->workspace_id)->firstOrFail();
@ -61,5 +61,6 @@
->get(route('filament.admin.resources.tenants.index', filamentTenantRouteParams($tenant))) ->get(route('filament.admin.resources.tenants.index', filamentTenantRouteParams($tenant)))
->assertOk() ->assertOk()
->assertSee($workspace->name) ->assertSee($workspace->name)
->assertDontSee('name="workspace_id"', escape: false); ->assertSee('Switch workspace')
->assertSee('name="workspace_id"', escape: false);
}); });

View File

@ -1,46 +0,0 @@
<?php
use App\Models\InventoryItem;
use App\Models\InventoryLink;
use App\Models\Tenant;
use App\Services\Inventory\DependencyExtractionService;
use App\Support\Enums\RelationshipType;
use Illuminate\Support\Facades\DB;
it('stores non-UUID identifiers in inventory_links on PostgreSQL', function () {
$driver = DB::getDriverName();
$tenant = Tenant::factory()->create();
$item = InventoryItem::factory()->for($tenant)->create([
'external_id' => '11111111-1111-1111-1111-111111111111',
]);
/** @var DependencyExtractionService $service */
$service = app(DependencyExtractionService::class);
$service->extractForPolicyData($item, [
'id' => $item->external_id,
'roleScopeTagIds' => ['0'],
'assignments' => [],
]);
if ($driver === 'pgsql') {
$columnTypes = collect(DB::select(
"select column_name, data_type from information_schema.columns where table_name = 'inventory_links' and column_name in ('source_id', 'target_id')"
))
->mapWithKeys(fn (object $row) => [(string) $row->column_name => (string) $row->data_type]);
expect($columnTypes->get('source_id'))->toBe('text')
->and($columnTypes->get('target_id'))->toBe('text');
}
expect(
InventoryLink::query()
->where('tenant_id', $tenant->getKey())
->where('source_type', 'inventory_item')
->where('source_id', $item->external_id)
->where('relationship_type', RelationshipType::ScopedBy->value)
->where('target_id', '0')
->exists()
)->toBeTrue();
});

View File

@ -1,173 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
it('renders the tenant context picker on tenantless Monitoring → Operations', function (): void {
$tenant = Tenant::factory()->create(['status' => 'active']);
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
$workspaceName = $tenant->workspace?->name;
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
WorkspaceContext::LAST_TENANT_IDS_SESSION_KEY => [
(string) $tenant->workspace_id => (int) $tenant->getKey(),
],
])
->get('/admin/operations')
->assertOk()
->assertSee($workspaceName ?? 'Select workspace')
->assertSee('Select tenant')
->assertSee('Search tenants…')
->assertSee('Switch workspace')
->assertSee('admin/select-tenant')
->assertSee('Clear tenant context')
->assertSee($tenant->getFilamentName());
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])
->post(route('admin.select-tenant'), ['tenant_id' => (int) $tenant->getKey()])
->assertRedirect();
});
it('disables the tenant picker when no workspace is active (Global Mode)', function (): void {
$user = \App\Models\User::factory()->create();
$workspace = \App\Models\Workspace::factory()->create();
\App\Models\WorkspaceMembership::factory()->create([
'workspace_id' => (int) $workspace->getKey(),
'user_id' => (int) $user->getKey(),
'role' => 'owner',
]);
Filament::setTenant(null, true);
session()->forget(WorkspaceContext::SESSION_KEY);
$this->actingAs($user)
->get('/admin/workspaces')
->assertOk()
->assertSee('Select workspace')
->assertSee('Select tenant')
->assertSee('Choose a workspace first.')
->assertDontSee('Search tenants…');
});
it('renders the tenant indicator read-only on tenant-scoped pages (Filament tenant menu is primary)', function (): void {
$tenant = Tenant::factory()->create(['status' => 'active']);
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id,
])
->get(route('filament.admin.resources.tenants.index', filamentTenantRouteParams($tenant)))
->assertOk()
->assertSee($tenant->getFilamentName())
->assertDontSee('Search tenants…')
->assertDontSee('admin/select-tenant')
->assertDontSee('Clear tenant context');
});
it('filters the header tenant picker to tenants the user can access', function (): void {
$tenantA = Tenant::factory()->create(['status' => 'active']);
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner', workspaceRole: 'readonly');
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
'name' => 'ZZZ-UNAUTHORIZED-TENANT-NAME-12345',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
])
->get('/admin/operations')
->assertOk()
->assertSee($tenantA->getFilamentName())
->assertDontSee($tenantB->getFilamentName());
});
it('shows all workspace tenants in the header tenant picker for workspace owners', function (): void {
$tenantA = Tenant::factory()->create(['status' => 'active']);
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner', workspaceRole: 'owner');
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
'name' => 'ZZZ-UNASSIGNED-TENANT-NAME-12345',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
])
->get('/admin/operations')
->assertOk()
->assertSee($tenantA->getFilamentName())
->assertSee($tenantB->getFilamentName());
});
it('does not implicitly switch tenant when opening canonical operation deep links', function (): void {
$tenantA = Tenant::factory()->create(['status' => 'active']);
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
]);
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$runA = OperationRun::factory()->create([
'tenant_id' => (int) $tenantA->getKey(),
'workspace_id' => (int) $tenantA->workspace_id,
'type' => 'policy.sync',
'initiator_name' => 'TenantA',
]);
OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(),
'workspace_id' => (int) $tenantB->workspace_id,
'type' => 'inventory.sync',
'initiator_name' => 'TenantB',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
])
->get(route('admin.operations.view', ['run' => (int) $runA->getKey()]))
->assertOk();
expect(Filament::getTenant())->toBeNull();
$this->actingAs($user)
->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
])
->get('/admin/operations')
->assertOk()
->assertSee('Policy sync')
->assertSee('Inventory sync')
->assertSee('TenantA')
->assertSee('TenantB');
});

View File

@ -1,8 +1,7 @@
<?php <?php
use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue; use Illuminate\Support\Facades\Queue;
@ -22,11 +21,8 @@
Bus::fake(); Bus::fake();
Queue::fake(); Queue::fake();
Filament::setTenant(null, true);
assertNoOutboundHttp(function () use ($tenant) { assertNoOutboundHttp(function () use ($tenant) {
$this->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) $this->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertOk(); ->assertOk();
}); });

View File

@ -1,149 +0,0 @@
<?php
declare(strict_types=1);
use App\Filament\Pages\Monitoring\Operations;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('serves /admin/operations without tenant context (workspace-wide)', function (): void {
$tenantA = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
]);
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$runA = OperationRun::factory()->create([
'tenant_id' => (int) $tenantA->getKey(),
'workspace_id' => (int) $tenantA->workspace_id,
'type' => 'policy.sync',
'initiator_name' => 'TenantA',
]);
$runB = OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(),
'workspace_id' => (int) $tenantB->workspace_id,
'type' => 'inventory.sync',
'initiator_name' => 'TenantB',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
->get('/admin/operations')
->assertOk()
->assertSee('Policy sync')
->assertSee('Inventory sync')
->assertSee('TenantA')
->assertSee('TenantB');
});
it('serves /admin/operations/{run} with and without tenant context', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
$run = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'policy.sync',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Operation run')
->assertDontSee('/admin/t/'.((int) $tenant->getKey()).'/operations/r/'.((int) $run->getKey()));
Filament::setTenant($tenant, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk()
->assertSee('Operation run');
});
it('defaults the tenant filter from tenant context and can be cleared', function (): void {
$tenantA = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
]);
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$runA = OperationRun::factory()->create([
'tenant_id' => (int) $tenantA->getKey(),
'workspace_id' => (int) $tenantA->workspace_id,
'type' => 'policy.sync',
'initiator_name' => 'TenantA',
]);
$runB = OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(),
'workspace_id' => (int) $tenantB->workspace_id,
'type' => 'inventory.sync',
'initiator_name' => 'TenantB',
]);
Filament::setTenant($tenantA, true);
$this->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
]);
session([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
]);
$component = Livewire::actingAs($user)
->test(Operations::class)
->assertCanSeeTableRecords([$runA])
->assertCanNotSeeTableRecords([$runB]);
$component
->filterTable('tenant_id', null)
->assertCanSeeTableRecords([$runA, $runB]);
});
it('does not register legacy operation resource routes', function (): void {
expect(Route::has('filament.admin.resources.operations.index'))->toBeFalse();
expect(Route::has('filament.admin.resources.operations.view'))->toBeFalse();
});
it('has reserved Monitoring placeholder pages for Alerts and Audit Log', function (): void {
$tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get('/admin/alerts')
->assertOk();
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id])
->get('/admin/audit-log')
->assertOk();
});

View File

@ -1,8 +1,7 @@
<?php <?php
use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Bus;
it('renders Monitoring → Operations index DB-only (no outbound HTTP, no background work)', function () { it('renders Monitoring → Operations index DB-only (no outbound HTTP, no background work)', function () {
@ -20,16 +19,13 @@
Bus::fake(); Bus::fake();
Filament::setTenant(null, true);
assertNoOutboundHttp(function () use ($tenant) { assertNoOutboundHttp(function () use ($tenant) {
$this->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) $this->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertOk() ->assertOk()
->assertDontSee('Total Runs (30 days)') ->assertSee('Total Runs (30 days)')
->assertDontSee('Active Runs') ->assertSee('Active Runs')
->assertDontSee('Failed/Partial (7 days)') ->assertSee('Failed/Partial (7 days)')
->assertDontSee('Avg Duration (7 days)') ->assertSee('Avg Duration (7 days)')
->assertSee('All') ->assertSee('All')
->assertSee('Active') ->assertSee('Active')
->assertSee('Succeeded') ->assertSee('Succeeded')
@ -55,13 +51,10 @@
Bus::fake(); Bus::fake();
Filament::setTenant(null, true);
assertNoOutboundHttp(function () use ($tenant, $run) { assertNoOutboundHttp(function () use ($tenant, $run) {
$this->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) $this->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk() ->assertOk()
->assertSee('Operation run'); ->assertSee('Policy sync');
}); });
Bus::assertNothingDispatched(); Bus::assertNothingDispatched();

View File

@ -1,20 +1,18 @@
<?php <?php
use App\Filament\Pages\Monitoring\Operations; use App\Filament\Resources\OperationRunResource;
use App\Filament\Resources\OperationRunResource\Pages\ListOperationRuns;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Livewire\Livewire; use Livewire\Livewire;
it('defaults Monitoring → Operations list to the active tenant when tenant context is set', function () { it('scopes Monitoring → Operations list to the active tenant', function () {
$tenantA = Tenant::factory()->create(); $tenantA = Tenant::factory()->create();
$tenantB = Tenant::factory()->create(); $tenantB = Tenant::factory()->create();
[$user] = createUserWithTenant($tenantA, role: 'owner'); [$user] = createUserWithTenant($tenantA, role: 'owner');
$tenantB->forceFill(['workspace_id' => (int) $tenantA->workspace_id])->save();
$user->tenants()->syncWithoutDetaching([ $user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'], $tenantB->getKey() => ['role' => 'owner'],
]); ]);
@ -35,11 +33,8 @@
'initiator_name' => 'TenantB', 'initiator_name' => 'TenantB',
]); ]);
Filament::setTenant($tenantA, true);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenantA))
->get('/admin/operations')
->assertOk() ->assertOk()
->assertSee('Policy sync') ->assertSee('Policy sync')
->assertSee('TenantA') ->assertSee('TenantA')
@ -53,8 +48,6 @@
[$user] = createUserWithTenant($tenantA, role: 'owner'); [$user] = createUserWithTenant($tenantA, role: 'owner');
$tenantB->forceFill(['workspace_id' => (int) $tenantA->workspace_id])->save();
$user->tenants()->syncWithoutDetaching([ $user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'], $tenantB->getKey() => ['role' => 'owner'],
]); ]);
@ -110,15 +103,8 @@
$tenantA->makeCurrent(); $tenantA->makeCurrent();
Filament::setTenant($tenantA, true); Filament::setTenant($tenantA, true);
$this->withSession([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
]);
session([
WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id,
]);
Livewire::actingAs($user) Livewire::actingAs($user)
->test(Operations::class) ->test(ListOperationRuns::class)
->assertCanSeeTableRecords([$runActiveA, $runSucceededA, $runPartialA, $runFailedA]) ->assertCanSeeTableRecords([$runActiveA, $runSucceededA, $runPartialA, $runFailedA])
->assertCanNotSeeTableRecords([$runActiveB, $runFailedB]) ->assertCanNotSeeTableRecords([$runActiveB, $runFailedB])
->set('activeTab', 'active') ->set('activeTab', 'active')
@ -135,12 +121,16 @@
->assertCanNotSeeTableRecords([$runActiveA, $runSucceededA, $runPartialA, $runActiveB, $runFailedB]); ->assertCanNotSeeTableRecords([$runActiveA, $runSucceededA, $runPartialA, $runActiveB, $runFailedB]);
}); });
it('prevents cross-workspace access to Monitoring → Operations detail', function () { it('prevents cross-tenant access to Monitoring → Operations detail', function () {
$tenantA = Tenant::factory()->create(); $tenantA = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB = Tenant::factory()->create(); $tenantB = Tenant::factory()->create();
[$user] = createUserWithTenant($tenantA, role: 'owner');
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$runB = OperationRun::factory()->create([ $runB = OperationRun::factory()->create([
'tenant_id' => $tenantB->getKey(), 'tenant_id' => $tenantB->getKey(),
'type' => 'inventory.sync', 'type' => 'inventory.sync',
@ -150,7 +140,6 @@
]); ]);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id]) ->get(OperationRunResource::getUrl('view', ['record' => $runB], tenant: $tenantA))
->get(route('admin.operations.view', ['run' => (int) $runB->getKey()]))
->assertNotFound(); ->assertNotFound();
}); });

View File

@ -1,21 +1,17 @@
<?php <?php
declare(strict_types=1); use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Services\Graph\GraphClientInterface; use App\Services\Graph\GraphClientInterface;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
it('allows access to Monitoring → Operations for workspace members', function (): void { it('allows access to monitoring page for tenant members', function () {
$tenant = Tenant::factory()->create(); $tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner'); [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
OperationRun::factory()->create([ $run = OperationRun::create([
'tenant_id' => (int) $tenant->getKey(), 'tenant_id' => $tenant->id,
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'policy.sync', 'type' => 'policy.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
@ -23,22 +19,18 @@
'run_identity_hash' => 'hash123', 'run_identity_hash' => 'hash123',
]); ]);
Filament::setTenant(null, true);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertSuccessful() ->assertSuccessful()
->assertSee('Policy sync'); ->assertSee('Policy sync');
}); });
it('renders Monitoring → Operations pages DB-only (never calls Graph)', function (): void { it('renders monitoring pages DB-only (never calls Graph)', function () {
$tenant = Tenant::factory()->create(); $tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'owner'); [$user, $tenant] = createUserWithTenant($tenant, role: 'owner');
$run = OperationRun::factory()->create([ $run = OperationRun::create([
'tenant_id' => (int) $tenant->getKey(), 'tenant_id' => $tenant->id,
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'policy.sync', 'type' => 'policy.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
@ -55,62 +47,59 @@
$mock->shouldReceive('request')->never(); $mock->shouldReceive('request')->never();
}); });
Filament::setTenant(null, true);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertSuccessful(); ->assertSuccessful();
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertSuccessful(); ->assertSuccessful();
}); });
it('defaults the operations list to the active tenant when tenant context is set', function (): void { it('shows runs only for current tenant', function () {
$tenantA = Tenant::factory()->create(); $tenantA = Tenant::factory()->create();
$tenantB = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner'); [$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB = Tenant::factory()->create([ // We must simulate being in tenant context
'status' => 'active', $this->actingAs($user);
'workspace_id' => (int) $tenantA->workspace_id, // Filament::setTenant($tenantA); // This is usually handled by middleware on routes, but in Livewire test we might need manual set or route visit.
]);
$user->tenants()->syncWithoutDetaching([ // Easier approach: visit the page for tenantA
$tenantB->getKey() => ['role' => 'owner'],
]);
OperationRun::factory()->create([ OperationRun::create([
'tenant_id' => (int) $tenantA->getKey(), 'tenant_id' => $tenantA->id,
'workspace_id' => (int) $tenantA->workspace_id,
'type' => 'policy.sync', 'type' => 'policy.sync',
'initiator_name' => 'TenantA', 'status' => 'queued',
'outcome' => 'pending',
'initiator_name' => 'System',
'run_identity_hash' => 'hashA',
]); ]);
OperationRun::factory()->create([ OperationRun::create([
'tenant_id' => (int) $tenantB->getKey(), 'tenant_id' => $tenantB->id,
'workspace_id' => (int) $tenantB->workspace_id,
'type' => 'inventory.sync', 'type' => 'inventory.sync',
'initiator_name' => 'TenantB', 'status' => 'queued',
'outcome' => 'pending',
'initiator_name' => 'System',
'run_identity_hash' => 'hashB',
]); ]);
Filament::setTenant($tenantA, true); // Livewire::test needs to know the tenant if the component relies on it.
// However, the component relies on `Filament::getTenant()`.
// The cleanest way is to just GET the page URL, which runs middleware.
$this->actingAs($user) $this->get(OperationRunResource::getUrl('index', tenant: $tenantA))
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id])
->get('/admin/operations')
->assertSee('Policy sync') ->assertSee('Policy sync')
->assertDontSee('Inventory sync'); ->assertDontSee('Inventory sync');
}); });
it('allows readonly users to view operations list and detail', function (): void { it('allows readonly users to view operations list and detail', function () {
$tenant = Tenant::factory()->create(); $tenant = Tenant::factory()->create();
[$user, $tenant] = createUserWithTenant($tenant, role: 'readonly'); [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly');
$run = OperationRun::factory()->create([ $run = OperationRun::create([
'tenant_id' => (int) $tenant->getKey(), 'tenant_id' => $tenant->id,
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'policy.sync', 'type' => 'policy.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
@ -118,27 +107,30 @@
'run_identity_hash' => 'hash123', 'run_identity_hash' => 'hash123',
]); ]);
Filament::setTenant(null, true);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertSuccessful() ->assertSuccessful()
->assertSee('Policy sync'); ->assertSee('Policy sync');
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertSuccessful() ->assertSuccessful()
->assertSee('Operation run'); ->assertSee('Policy sync');
}); });
it('returns 404 when viewing an operation run outside workspace membership', function (): void { it('denies access to unauthorized users', function () {
$run = OperationRun::factory()->create(); $tenant = Tenant::factory()->create();
$user = User::factory()->create(); $user = User::factory()->create();
// Not attached to tenant
$this->actingAs($user) // In a multitenant app, if you try to access a tenant route you are not part of,
->get(route('admin.operations.view', ['run' => (int) $run->getKey()])) // Filament typically returns 404 (Not Found) if it can't find the tenant-user relationship, or 403.
->assertNotFound(); // The previous fail said "Received 404". This confirms Filament couldn't find the tenant for this user scope or just hides it.
// We should accept 404 or 403.
$response = $this->actingAs($user)
->get(OperationRunResource::getUrl('index', tenant: $tenant));
// Allow either 403 or 404 as "Denied"
$this->assertTrue(in_array($response->status(), [403, 404]));
}); });

View File

@ -22,8 +22,7 @@
$contents = File::get($path); $contents = File::get($path);
if (preg_match("/\\bOperationRunResource::getUrl\(\\s*'view'/", $contents) === 1 if (preg_match("/\\bOperationRunResource::getUrl\(\\s*'view'/", $contents) === 1) {
|| preg_match("/route\(\s*'filament\.admin\.resources\.operations\.view'/", $contents) === 1) {
$violations[] = $path; $violations[] = $path;
} }
} }

View File

@ -1,5 +1,6 @@
<?php <?php
use App\Filament\Resources\OperationRunResource;
use App\Models\Tenant; use App\Models\Tenant;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use Illuminate\Notifications\DatabaseNotification; use Illuminate\Notifications\DatabaseNotification;
@ -54,6 +55,6 @@
expect($notificationJson)->not->toContain('test.user@example.com'); expect($notificationJson)->not->toContain('test.user@example.com');
$this->actingAs($user) $this->actingAs($user)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()])) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->assertSuccessful(); ->assertSuccessful();
}); });

View File

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('returns 404 when a non-member tries to view another workspace operation run', function (): void {
$workspaceA = Workspace::factory()->create();
$workspaceB = Workspace::factory()->create();
$user = User::factory()->create();
WorkspaceMembership::factory()->create([
'workspace_id' => $workspaceA->getKey(),
'user_id' => $user->getKey(),
'role' => 'owner',
]);
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $workspaceB->getKey(),
]);
$runB = OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(),
'workspace_id' => (int) $workspaceB->getKey(),
'type' => 'policy.sync',
'initiator_name' => 'WorkspaceB',
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceA->getKey()])
->get(route('admin.operations.view', ['run' => (int) $runB->getKey()]))
->assertNotFound();
});
it('returns 403 when a workspace member without workspace.manage tries to edit a workspace', function (): void {
$user = User::factory()->create();
$workspace = Workspace::factory()->create();
WorkspaceMembership::factory()->create([
'workspace_id' => $workspace->getKey(),
'user_id' => $user->getKey(),
'role' => 'manager',
]);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
->get('/admin/workspaces/'.(int) $workspace->getKey().'/edit')
->assertForbidden();
});

View File

@ -1,93 +1,71 @@
<?php <?php
declare(strict_types=1); use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
uses(\Illuminate\Foundation\Testing\RefreshDatabase::class); uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);
test('operation runs default to the active tenant when tenant context is set', function (): void { test('operation runs are listed for the active tenant', function () {
$tenantA = Tenant::factory()->create(); $tenantA = Tenant::factory()->create();
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner'); $tenantB = Tenant::factory()->create();
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $tenantA->workspace_id,
]);
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
OperationRun::factory()->create([ OperationRun::factory()->create([
'tenant_id' => (int) $tenantA->getKey(), 'tenant_id' => $tenantA->getKey(),
'workspace_id' => (int) $tenantA->workspace_id,
'type' => 'policy.sync', 'type' => 'policy.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
]); ]);
OperationRun::factory()->create([ OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(), 'tenant_id' => $tenantB->getKey(),
'workspace_id' => (int) $tenantB->workspace_id,
'type' => 'inventory.sync', 'type' => 'inventory.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
]); ]);
Filament::setTenant($tenantA, true); [$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB->forceFill(['workspace_id' => (int) $tenantA->workspace_id])->save();
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenantA->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenantA))
->get('/admin/operations')
->assertOk() ->assertOk()
->assertSee('Policy sync') ->assertSee('Policy sync')
->assertDontSee('Inventory sync'); ->assertDontSee('Inventory sync');
}); });
test('operation run view is not accessible cross-workspace', function (): void { test('operation run view is not accessible cross-tenant', function () {
$workspaceA = Workspace::factory()->create(); $tenantA = Tenant::factory()->create();
$workspaceB = Workspace::factory()->create(); $tenantB = Tenant::factory()->create();
$user = User::factory()->create();
WorkspaceMembership::factory()->create([
'workspace_id' => (int) $workspaceA->getKey(),
'user_id' => (int) $user->getKey(),
'role' => 'owner',
]);
$tenantB = Tenant::factory()->create([
'status' => 'active',
'workspace_id' => (int) $workspaceB->getKey(),
]);
$runB = OperationRun::factory()->create([ $runB = OperationRun::factory()->create([
'tenant_id' => (int) $tenantB->getKey(), 'tenant_id' => $tenantB->getKey(),
'workspace_id' => (int) $workspaceB->getKey(),
'type' => 'inventory.sync', 'type' => 'inventory.sync',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
]); ]);
[$user, $tenantA] = createUserWithTenant($tenantA, role: 'owner');
$tenantB->forceFill(['workspace_id' => (int) $tenantA->workspace_id])->save();
$user->tenants()->syncWithoutDetaching([
$tenantB->getKey() => ['role' => 'owner'],
]);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceA->getKey()]) ->get(OperationRunResource::getUrl('view', ['record' => $runB], tenant: $tenantA))
->get(route('admin.operations.view', ['run' => (int) $runB->getKey()]))
->assertNotFound(); ->assertNotFound();
}); });
test('readonly users can view operation runs in their workspace', function (): void { test('readonly users can view operation runs for their tenant', function () {
$tenant = Tenant::factory()->create(); $tenant = Tenant::factory()->create();
$run = OperationRun::factory()->create([ $run = OperationRun::factory()->create([
'tenant_id' => (int) $tenant->getKey(), 'tenant_id' => $tenant->getKey(),
'workspace_id' => (int) $tenant->workspace_id,
'type' => 'drift.generate', 'type' => 'drift.generate',
'status' => 'queued', 'status' => 'queued',
'outcome' => 'pending', 'outcome' => 'pending',
@ -95,17 +73,13 @@
[$user, $tenant] = createUserWithTenant($tenant, role: 'readonly'); [$user, $tenant] = createUserWithTenant($tenant, role: 'readonly');
Filament::setTenant(null, true);
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('index', tenant: $tenant))
->get('/admin/operations')
->assertOk() ->assertOk()
->assertSee('Drift generation'); ->assertSee('Drift generation');
$this->actingAs($user) $this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $tenant->workspace_id]) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->get(route('admin.operations.view', ['run' => (int) $run->getKey()]))
->assertOk() ->assertOk()
->assertSee('Operation run'); ->assertSee('Drift generation');
}); });

View File

@ -2,6 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\Tenant;
@ -34,7 +35,7 @@
]); ]);
$this->actingAs($user) $this->actingAs($user)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()])) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->assertStatus(404); ->assertStatus(404);
$connection = ProviderConnection::factory()->create([ $connection = ProviderConnection::factory()->create([
@ -70,7 +71,7 @@
]); ]);
$this->actingAs($user) $this->actingAs($user)
->get(route('admin.operations.view', ['run' => (int) $run->getKey()])) ->get(OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant))
->assertOk() ->assertOk()
->assertSee('Verification report'); ->assertSee('Verification report');

View File

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\Operations\TenantlessOperationRunViewer; use App\Filament\Resources\OperationRunResource\Pages\ViewOperationRun;
use App\Models\OperationRun; use App\Models\OperationRun;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Livewire\Livewire; use Livewire\Livewire;
@ -24,7 +24,7 @@
]); ]);
assertNoOutboundHttp(function () use ($run): void { assertNoOutboundHttp(function () use ($run): void {
Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run]) Livewire::test(ViewOperationRun::class, ['record' => $run->getRouteKey()])
->assertSee('Verification report') ->assertSee('Verification report')
->assertSee('Verification report unavailable'); ->assertSee('Verification report unavailable');
}); });
@ -52,7 +52,7 @@
]); ]);
assertNoOutboundHttp(function () use ($run): void { assertNoOutboundHttp(function () use ($run): void {
Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run]) Livewire::test(ViewOperationRun::class, ['record' => $run->getRouteKey()])
->assertSee('Verification report') ->assertSee('Verification report')
->assertSee('Verification report unavailable'); ->assertSee('Verification report unavailable');
}); });

View File

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\Operations\TenantlessOperationRunViewer; use App\Filament\Resources\OperationRunResource\Pages\ViewOperationRun;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Support\Verification\VerificationReportFingerprint; use App\Support\Verification\VerificationReportFingerprint;
use Filament\Facades\Filament; use Filament\Facades\Filament;
@ -54,7 +54,7 @@
$fingerprint = VerificationReportFingerprint::forReport($report); $fingerprint = VerificationReportFingerprint::forReport($report);
assertNoOutboundHttp(function () use ($run, $fingerprint): void { assertNoOutboundHttp(function () use ($run, $fingerprint): void {
Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run]) Livewire::test(ViewOperationRun::class, ['record' => $run->getRouteKey()])
->assertSee('Verification report') ->assertSee('Verification report')
->assertSee('Open previous verification') ->assertSee('Open previous verification')
->assertSee($fingerprint) ->assertSee($fingerprint)

View File

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
use App\Filament\Pages\Operations\TenantlessOperationRunViewer; use App\Filament\Resources\OperationRunResource\Pages\ViewOperationRun;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\Tenant;
@ -45,7 +45,7 @@
]); ]);
assertNoOutboundHttp(function () use ($run): void { assertNoOutboundHttp(function () use ($run): void {
$component = Livewire::test(TenantlessOperationRunViewer::class, ['run' => $run]) $component = Livewire::test(ViewOperationRun::class, ['record' => $run->getRouteKey()])
->assertSee('Verification report') ->assertSee('Verification report')
->assertSee('Blocked') ->assertSee('Blocked')
->assertSee('Token acquisition works'); ->assertSee('Token acquisition works');

View File

@ -58,8 +58,6 @@
'tenant_id' => 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'tenant_id' => 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
]); ]);
$tenantInOther->makeCurrent();
$user->tenants()->syncWithoutDetaching([ $user->tenants()->syncWithoutDetaching([
$tenantInOther->getKey() => ['role' => 'owner'], $tenantInOther->getKey() => ['role' => 'owner'],
]); ]);

View File

@ -1,40 +0,0 @@
<?php
declare(strict_types=1);
use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceIntendedUrl;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('stores and consumes an intended admin URL (path + query)', function (): void {
session()->forget(WorkspaceContext::INTENDED_URL_SESSION_KEY);
WorkspaceIntendedUrl::store('/admin/operations?tab=active');
expect(session(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBe('/admin/operations?tab=active');
$consumed = WorkspaceIntendedUrl::consume();
expect($consumed)->toBe('/admin/operations?tab=active');
expect(session()->has(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBeFalse();
});
it('rejects non-admin intended URLs', function (): void {
session()->forget(WorkspaceContext::INTENDED_URL_SESSION_KEY);
WorkspaceIntendedUrl::store('/logout');
expect(session()->has(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBeFalse();
});
it('rejects absolute URLs and protocol-relative URLs', function (): void {
session()->forget(WorkspaceContext::INTENDED_URL_SESSION_KEY);
WorkspaceIntendedUrl::store('https://example.com/admin/operations');
expect(session()->has(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBeFalse();
WorkspaceIntendedUrl::store('//example.com/admin/operations');
expect(session()->has(WorkspaceContext::INTENDED_URL_SESSION_KEY))->toBeFalse();
});

View File

@ -1,40 +0,0 @@
<?php
declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('does not show "Switch workspace" in sidebar navigation (topbar-only)', function (): void {
$user = User::factory()->create();
$workspace = Workspace::factory()->create();
WorkspaceMembership::factory()->create([
'workspace_id' => $workspace->getKey(),
'user_id' => $user->getKey(),
'role' => 'owner',
]);
Filament::setTenant(null, true);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
->get('/admin/operations')
->assertOk();
$panel = Filament::getCurrentOrDefaultPanel();
$labels = collect($panel->getNavigationItems())
->map(static fn ($item): string => $item->getLabel())
->all();
expect($labels)->not->toContain('Switch workspace');
expect($labels)->toContain('Manage workspaces');
expect($labels)->not->toContain('Workspaces');
});

View File

@ -32,23 +32,6 @@
->assertOk(); ->assertOk();
}); });
it('serves /admin/workspaces without an active workspace selected (Global Mode)', function (): void {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['slug' => 'acme']);
WorkspaceMembership::factory()->create([
'workspace_id' => $workspace->getKey(),
'user_id' => $user->getKey(),
'role' => 'owner',
]);
$this->actingAs($user)
->get('/admin/workspaces')
->assertOk()
->assertSee('Select workspace')
->assertSee('Choose a workspace first.');
});
it('serves the Workspaces view page tenantless at /admin/workspaces/{record}', function (): void { it('serves the Workspaces view page tenantless at /admin/workspaces/{record}', function (): void {
$user = User::factory()->create(); $user = User::factory()->create();
@ -90,21 +73,3 @@
->get('/admin/t/11111111-1111-1111-1111-111111111111/workspaces') ->get('/admin/t/11111111-1111-1111-1111-111111111111/workspaces')
->assertNotFound(); ->assertNotFound();
}); });
it('returns 404 when accessing a workspace record outside membership', function (): void {
$user = User::factory()->create();
$workspaceA = Workspace::factory()->create(['slug' => 'acme-a']);
WorkspaceMembership::factory()->create([
'workspace_id' => $workspaceA->getKey(),
'user_id' => $user->getKey(),
'role' => 'owner',
]);
$workspaceB = Workspace::factory()->create(['slug' => 'acme-b']);
$this->actingAs($user)
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceA->getKey()])
->get('/admin/workspaces/'.(int) $workspaceB->getKey())
->assertNotFound();
});