feat: cut over tenant core to managed environments
Some checks failed
PR Fast Feedback / fast-feedback (pull_request) Failing after 7m13s

This commit is contained in:
Ahmed Darrazi 2026-05-07 08:35:42 +02:00
parent bf561b867c
commit 1123b122d9
1478 changed files with 13710 additions and 11751 deletions

View File

@ -31,7 +31,8 @@ ### Platform
- Install PHP dependencies: `cd apps/platform && composer install` - Install PHP dependencies: `cd apps/platform && composer install`
- Start Sail: `cd apps/platform && ./vendor/bin/sail up -d` - Start Sail: `cd apps/platform && ./vendor/bin/sail up -d`
- Generate the app key: `cd apps/platform && ./vendor/bin/sail artisan key:generate` - Generate the app key: `cd apps/platform && ./vendor/bin/sail artisan key:generate`
- Run migrations and seeders: `cd apps/platform && ./vendor/bin/sail artisan migrate --seed` - Apply incremental migrations on an already cut-over local database: `cd apps/platform && ./vendor/bin/sail artisan migrate`
- Initialize or reset the local database: `cd apps/platform && ./vendor/bin/sail artisan migrate:fresh --seed`
- Run frontend watch/build inside Sail: `corepack pnpm dev:platform`, `cd apps/platform && ./vendor/bin/sail pnpm dev`, or `cd apps/platform && ./vendor/bin/sail pnpm build` - Run frontend watch/build inside Sail: `corepack pnpm dev:platform`, `cd apps/platform && ./vendor/bin/sail pnpm dev`, or `cd apps/platform && ./vendor/bin/sail pnpm build`
- Run tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact` - Run tests: `cd apps/platform && ./vendor/bin/sail artisan test --compact`
@ -152,6 +153,7 @@ ### DB Reset and Seed Rules
- Default lanes use SQLite `:memory:` with `RefreshDatabase` as the reset strategy. - Default lanes use SQLite `:memory:` with `RefreshDatabase` as the reset strategy.
- The isolated PostgreSQL coverage remains the `Pgsql` suite and is reserved for schema or foreign-key assertions. - The isolated PostgreSQL coverage remains the `Pgsql` suite and is reserved for schema or foreign-key assertions.
- Spec 279 managed-environment core cutover is destructive for old local databases. If a local database still contains legacy `tenants`, `tenant_user`, `tenant_memberships`, or `user_tenant_preferences` tables, reset it with `cd apps/platform && ./vendor/bin/sail artisan migrate:fresh --seed` instead of trying to preserve that schema.
- Keep seeds out of default lanes. Opt into seeded fixtures only inside the test that needs business-truth seed data. - Keep seeds out of default lanes. Opt into seeded fixtures only inside the test that needs business-truth seed data.
- Schema-baseline or dump-based acceleration remains a follow-up investigation, not a default requirement for the current lane model. - Schema-baseline or dump-based acceleration remains a follow-up investigation, not a default requirement for the current lane model.

View File

@ -6,7 +6,7 @@
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\ProviderCredential; use App\Models\ProviderCredential;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use App\Services\Providers\ProviderConnectionClassificationResult; use App\Services\Providers\ProviderConnectionClassificationResult;
use App\Services\Providers\ProviderConnectionClassifier; use App\Services\Providers\ProviderConnectionClassifier;
@ -43,9 +43,9 @@ public function handle(ProviderConnectionClassifier $classifier): int
} }
$tenantCounts = (clone $query) $tenantCounts = (clone $query)
->selectRaw('tenant_id, count(*) as aggregate') ->selectRaw('managed_environment_id, count(*) as aggregate')
->groupBy('tenant_id') ->groupBy('managed_environment_id')
->pluck('aggregate', 'tenant_id') ->pluck('aggregate', 'managed_environment_id')
->map(static fn (mixed $count): int => (int) $count) ->map(static fn (mixed $count): int => (int) $count)
->all(); ->all();
@ -84,7 +84,7 @@ public function handle(ProviderConnectionClassifier $classifier): int
$tenant = $connection->tenant; $tenant = $connection->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
$this->warn(sprintf('Skipping provider connection #%d without tenant context.', (int) $connection->getKey())); $this->warn(sprintf('Skipping provider connection #%d without tenant context.', (int) $connection->getKey()));
continue; continue;
@ -123,11 +123,11 @@ private function query(): Builder
$tenantOption = $this->option('tenant'); $tenantOption = $this->option('tenant');
if (is_string($tenantOption) && trim($tenantOption) !== '') { if (is_string($tenantOption) && trim($tenantOption) !== '') {
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->forTenant(trim($tenantOption)) ->forTenant(trim($tenantOption))
->firstOrFail(); ->firstOrFail();
$query->where('tenant_id', (int) $tenant->getKey()); $query->where('managed_environment_id', (int) $tenant->getKey());
} }
$connectionOption = $this->option('connection'); $connectionOption = $this->option('connection');
@ -175,7 +175,7 @@ private function applyClassification(
return $connection->fresh(['tenant', 'credential']); return $connection->fresh(['tenant', 'credential']);
} }
private function auditStart(Tenant $tenant, int $candidateCount): void private function auditStart(ManagedEnvironment $tenant, int $candidateCount): void
{ {
app(AuditLogger::class)->log( app(AuditLogger::class)->log(
tenant: $tenant, tenant: $tenant,
@ -195,7 +195,7 @@ private function auditStart(Tenant $tenant, int $candidateCount): void
} }
private function auditApplied( private function auditApplied(
Tenant $tenant, ManagedEnvironment $tenant,
ProviderConnection $connection, ProviderConnection $connection,
ProviderConnectionClassificationResult $result, ProviderConnectionClassificationResult $result,
): void { ): void {

View File

@ -15,7 +15,7 @@ class OpsReconcileAdapterRuns extends Command
*/ */
protected $signature = 'ops:reconcile-adapter-runs protected $signature = 'ops:reconcile-adapter-runs
{--type= : Adapter run type (e.g. restore.execute)} {--type= : Adapter run type (e.g. restore.execute)}
{--tenant= : Tenant ID} {--tenant= : ManagedEnvironment ID}
{--older-than=60 : Only consider runs older than N minutes} {--older-than=60 : Only consider runs older than N minutes}
{--dry-run=true : Preview only (true/false)} {--dry-run=true : Preview only (true/false)}
{--limit=50 : Max number of runs to inspect}'; {--limit=50 : Max number of runs to inspect}';
@ -56,7 +56,7 @@ public function handle()
$result = $reconciler->reconcile([ $result = $reconciler->reconcile([
'type' => $type, 'type' => $type,
'tenant_id' => $tenantId, 'managed_environment_id' => $tenantId,
'older_than_minutes' => $olderThanMinutes, 'older_than_minutes' => $olderThanMinutes,
'limit' => $limit, 'limit' => $limit,
'dry_run' => $dryRun, 'dry_run' => $dryRun,

View File

@ -5,7 +5,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\OperationCatalog; use App\Support\OperationCatalog;
use App\Support\OperationRunType; use App\Support\OperationRunType;
use Illuminate\Console\Command; use Illuminate\Console\Command;
@ -51,7 +51,7 @@ public function handle(): int
} }
if ($tenantIds !== []) { if ($tenantIds !== []) {
$query->whereIn('tenant_id', $tenantIds); $query->whereIn('managed_environment_id', $tenantIds);
} }
$candidates = $query->get(); $candidates = $query->get();
@ -66,12 +66,12 @@ public function handle(): int
} }
$this->table( $this->table(
['Run', 'Type', 'Tenant', 'Workspace', 'Legacy signal'], ['Run', 'Type', 'ManagedEnvironment', 'Workspace', 'Legacy signal'],
$matched $matched
->map(fn (OperationRun $run): array => [ ->map(fn (OperationRun $run): array => [
'Run' => (string) $run->getKey(), 'Run' => (string) $run->getKey(),
'Type' => (string) $run->type, 'Type' => (string) $run->type,
'Tenant' => $run->tenant_id !== null ? (string) $run->tenant_id : '—', 'ManagedEnvironment' => $run->managed_environment_id !== null ? (string) $run->managed_environment_id : '—',
'Workspace' => $run->workspace_id !== null ? (string) $run->workspace_id : '—', 'Workspace' => $run->workspace_id !== null ? (string) $run->workspace_id : '—',
'Legacy signal' => $this->legacySignal($run), 'Legacy signal' => $this->legacySignal($run),
]) ])
@ -145,9 +145,9 @@ private function resolveTenantIds(array $tenantIdentifiers): array
$tenantIds = []; $tenantIds = [];
foreach ($tenantIdentifiers as $identifier) { foreach ($tenantIdentifiers as $identifier) {
$tenant = Tenant::query()->forTenant($identifier)->first(); $tenant = ManagedEnvironment::query()->forTenant($identifier)->first();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$tenantIds[] = (int) $tenant->getKey(); $tenantIds[] = (int) $tenant->getKey();
} }
} }

View File

@ -4,7 +4,7 @@
use App\Models\Policy; use App\Models\Policy;
use App\Models\PolicyVersion; use App\Models\PolicyVersion;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\Graph\GraphClientInterface; use App\Services\Graph\GraphClientInterface;
use Illuminate\Console\Command; use Illuminate\Console\Command;
@ -43,7 +43,7 @@ public function handle(): int
->where('policy_type', 'enrollmentRestriction'); ->where('policy_type', 'enrollmentRestriction');
if ($tenant) { if ($tenant) {
$query->where('tenant_id', $tenant->id); $query->where('managed_environment_id', $tenant->id);
} }
$candidates = $query->get(); $candidates = $query->get();
@ -69,9 +69,9 @@ public function handle(): int
} }
$this->line(sprintf( $this->line(sprintf(
'ESP detected: policy=%s tenant_id=%s external_id=%s', 'ESP detected: policy=%s managed_environment_id=%s external_id=%s',
(string) $policy->getKey(), (string) $policy->getKey(),
(string) $policy->tenant_id, (string) $policy->managed_environment_id,
(string) $policy->external_id, (string) $policy->external_id,
)); ));
@ -80,7 +80,7 @@ public function handle(): int
} }
$existingTarget = Policy::query() $existingTarget = Policy::query()
->where('tenant_id', $policy->tenant_id) ->where('managed_environment_id', $policy->managed_environment_id)
->where('external_id', $policy->external_id) ->where('external_id', $policy->external_id)
->where('policy_type', 'windowsEnrollmentStatusPage') ->where('policy_type', 'windowsEnrollmentStatusPage')
->first(); ->first();
@ -130,7 +130,7 @@ private function fetchSnapshotOrNull(Policy $policy): ?array
return null; return null;
} }
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
$response = $this->graphClient->getPolicy('enrollmentRestriction', $policy->external_id, [ $response = $this->graphClient->getPolicy('enrollmentRestriction', $policy->external_id, [
'tenant' => $tenantIdentifier, 'tenant' => $tenantIdentifier,
@ -148,7 +148,7 @@ private function fetchSnapshotOrNull(Policy $policy): ?array
return is_array($payload) ? $payload : null; return is_array($payload) ? $payload : null;
} }
private function resolveTenantOrNull(): ?Tenant private function resolveTenantOrNull(): ?ManagedEnvironment
{ {
$tenantOption = $this->option('tenant'); $tenantOption = $this->option('tenant');
@ -156,7 +156,7 @@ private function resolveTenantOrNull(): ?Tenant
return null; return null;
} }
return Tenant::query() return ManagedEnvironment::query()
->forTenant($tenantOption) ->forTenant($tenantOption)
->firstOrFail(); ->firstOrFail();
} }

View File

@ -7,8 +7,8 @@
use App\Models\BackupItem; use App\Models\BackupItem;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\Policy; use App\Models\Policy;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantMembership; use App\Models\ManagedEnvironmentMembership;
use App\Models\User; use App\Models\User;
use App\Models\UserTenantPreference; use App\Models\UserTenantPreference;
use App\Models\Workspace; use App\Models\Workspace;
@ -42,7 +42,7 @@ public function handle(): int
$workspaceConfig = is_array($fixture['workspace'] ?? null) ? $fixture['workspace'] : []; $workspaceConfig = is_array($fixture['workspace'] ?? null) ? $fixture['workspace'] : [];
$userConfig = is_array($fixture['user'] ?? null) ? $fixture['user'] : []; $userConfig = is_array($fixture['user'] ?? null) ? $fixture['user'] : [];
$scenarioConfig = is_array($fixture['blocked_drillthrough'] ?? null) ? $fixture['blocked_drillthrough'] : []; $scenarioConfig = is_array($fixture['blocked_drillthrough'] ?? null) ? $fixture['blocked_drillthrough'] : [];
$tenantRouteKey = (string) ($scenarioConfig['tenant_id'] ?? $scenarioConfig['tenant_external_id'] ?? '18000000-0000-4000-8000-000000000180'); $tenantRouteKey = (string) ($scenarioConfig['managed_environment_id'] ?? $scenarioConfig['tenant_external_id'] ?? '18000000-0000-4000-8000-000000000180');
$workspace = Workspace::query()->updateOrCreate( $workspace = Workspace::query()->updateOrCreate(
['slug' => (string) ($workspaceConfig['slug'] ?? 'spec-180-backup-health-smoke')], ['slug' => (string) ($workspaceConfig['slug'] ?? 'spec-180-backup-health-smoke')],
@ -60,16 +60,13 @@ public function handle(): int
], ],
); );
$tenant = Tenant::query()->updateOrCreate( $tenant = ManagedEnvironment::query()->updateOrCreate(
['external_id' => $tenantRouteKey], ['slug' => $tenantRouteKey],
[ [
'workspace_id' => (int) $workspace->getKey(), 'workspace_id' => (int) $workspace->getKey(),
'name' => (string) ($scenarioConfig['tenant_name'] ?? 'Spec 180 Blocked Backup Tenant'), 'name' => (string) ($scenarioConfig['tenant_name'] ?? 'Spec 180 Blocked Backup ManagedEnvironment'),
'tenant_id' => $tenantRouteKey, 'lifecycle_status' => ManagedEnvironment::STATUS_ACTIVE,
'app_certificate_thumbprint' => null, 'kind' => 'dev',
'app_notes' => null,
'status' => Tenant::STATUS_ACTIVE,
'environment' => 'dev',
'is_current' => false, 'is_current' => false,
'metadata' => ['fixture' => 'spec-180-browser-smoke'], 'metadata' => ['fixture' => 'spec-180-browser-smoke'],
'rbac_status' => 'ok', 'rbac_status' => 'ok',
@ -82,8 +79,8 @@ public function handle(): int
['role' => 'owner'], ['role' => 'owner'],
); );
TenantMembership::query()->updateOrCreate( ManagedEnvironmentMembership::query()->updateOrCreate(
['tenant_id' => (int) $tenant->getKey(), 'user_id' => (int) $user->getKey()], ['managed_environment_id' => (int) $tenant->getKey(), 'user_id' => (int) $user->getKey()],
['role' => 'owner', 'source' => 'manual', 'source_ref' => 'spec-180-browser-smoke'], ['role' => 'owner', 'source' => 'manual', 'source_ref' => 'spec-180-browser-smoke'],
); );
@ -91,16 +88,16 @@ public function handle(): int
$user->forceFill(['last_workspace_id' => (int) $workspace->getKey()])->save(); $user->forceFill(['last_workspace_id' => (int) $workspace->getKey()])->save();
} }
if (Schema::hasTable('user_tenant_preferences')) { if (Schema::hasTable('user_managed_environment_preferences')) {
UserTenantPreference::query()->updateOrCreate( UserTenantPreference::query()->updateOrCreate(
['user_id' => (int) $user->getKey(), 'tenant_id' => (int) $tenant->getKey()], ['user_id' => (int) $user->getKey(), 'managed_environment_id' => (int) $tenant->getKey()],
['last_used_at' => now()], ['last_used_at' => now()],
); );
} }
$policy = Policy::query()->updateOrCreate( $policy = Policy::query()->updateOrCreate(
[ [
'tenant_id' => (int) $tenant->getKey(), 'managed_environment_id' => (int) $tenant->getKey(),
'external_id' => (string) ($scenarioConfig['policy_external_id'] ?? 'spec-180-rbac-stale-policy'), 'external_id' => (string) ($scenarioConfig['policy_external_id'] ?? 'spec-180-rbac-stale-policy'),
'policy_type' => (string) ($scenarioConfig['policy_type'] ?? 'settingsCatalogPolicy'), 'policy_type' => (string) ($scenarioConfig['policy_type'] ?? 'settingsCatalogPolicy'),
], ],
@ -113,7 +110,7 @@ public function handle(): int
); );
$backupSet = BackupSet::withTrashed()->firstOrNew([ $backupSet = BackupSet::withTrashed()->firstOrNew([
'tenant_id' => (int) $tenant->getKey(), 'managed_environment_id' => (int) $tenant->getKey(),
'name' => (string) ($scenarioConfig['backup_set_name'] ?? 'Spec 180 Blocked Stale Backup'), 'name' => (string) ($scenarioConfig['backup_set_name'] ?? 'Spec 180 Blocked Stale Backup'),
]); ]);
@ -137,7 +134,7 @@ public function handle(): int
]); ]);
$backupItem->forceFill([ $backupItem->forceFill([
'tenant_id' => (int) $tenant->getKey(), 'managed_environment_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(), 'policy_id' => (int) $policy->getKey(),
'platform' => 'windows', 'platform' => 'windows',
'captured_at' => $backupSet->completed_at, 'captured_at' => $backupSet->completed_at,
@ -173,8 +170,8 @@ public function handle(): int
['Workspace', (string) $workspace->name], ['Workspace', (string) $workspace->name],
['User email', (string) $user->email], ['User email', (string) $user->email],
['User password', $password], ['User password', $password],
['Tenant', (string) $tenant->name], ['ManagedEnvironment', (string) $tenant->name],
['Tenant external id', (string) $tenant->external_id], ['ManagedEnvironment external id', (string) $tenant->external_id],
['Dashboard URL', "/admin/t/{$tenant->external_id}"], ['Dashboard URL', "/admin/t/{$tenant->external_id}"],
['Fixture login URL', route('admin.local.backup-health-browser-fixture-login', absolute: false)], ['Fixture login URL', route('admin.local.backup-health-browser-fixture-login', absolute: false)],
['Blocked route', "/admin/t/{$tenant->external_id}/backup-sets"], ['Blocked route', "/admin/t/{$tenant->external_id}/backup-sets"],

View File

@ -3,7 +3,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\SyncPoliciesJob; use App\Jobs\SyncPoliciesJob;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use Illuminate\Console\Command; use Illuminate\Console\Command;
class SyncPolicies extends Command class SyncPolicies extends Command
@ -24,16 +24,16 @@ public function handle(): int
return Command::SUCCESS; return Command::SUCCESS;
} }
private function resolveTenant(): Tenant private function resolveTenant(): ManagedEnvironment
{ {
$tenantId = $this->option('tenant'); $tenantId = $this->option('tenant');
if ($tenantId) { if ($tenantId) {
return Tenant::query() return ManagedEnvironment::query()
->forTenant($tenantId) ->forTenant($tenantId)
->firstOrFail(); ->firstOrFail();
} }
return Tenant::currentOrFail(); return ManagedEnvironment::currentOrFail();
} }
} }

View File

@ -258,21 +258,21 @@ private function collectTableStats(array $tables): array
$missing = (int) DB::table($table)->whereNull('workspace_id')->count(); $missing = (int) DB::table($table)->whereNull('workspace_id')->count();
$unresolvableQuery = DB::table($table) $unresolvableQuery = DB::table($table)
->leftJoin('tenants', 'tenants.id', '=', sprintf('%s.tenant_id', $table)) ->leftJoin('managed_environments', 'managed_environments.id', '=', sprintf('%s.managed_environment_id', $table))
->whereNull(sprintf('%s.workspace_id', $table)) ->whereNull(sprintf('%s.workspace_id', $table))
->where(function ($query): void { ->where(function ($query): void {
$query->whereNull('tenants.id') $query->whereNull('managed_environments.id')
->orWhereNull('tenants.workspace_id'); ->orWhereNull('managed_environments.workspace_id');
}); });
$unresolvable = (int) $unresolvableQuery->count(); $unresolvable = (int) $unresolvableQuery->count();
$sampleIds = DB::table($table) $sampleIds = DB::table($table)
->leftJoin('tenants', 'tenants.id', '=', sprintf('%s.tenant_id', $table)) ->leftJoin('managed_environments', 'managed_environments.id', '=', sprintf('%s.managed_environment_id', $table))
->whereNull(sprintf('%s.workspace_id', $table)) ->whereNull(sprintf('%s.workspace_id', $table))
->where(function ($query): void { ->where(function ($query): void {
$query->whereNull('tenants.id') $query->whereNull('managed_environments.id')
->orWhereNull('tenants.workspace_id'); ->orWhereNull('managed_environments.workspace_id');
}) })
->orderBy(sprintf('%s.id', $table)) ->orderBy(sprintf('%s.id', $table))
->limit(5) ->limit(5)
@ -302,11 +302,11 @@ private function collectWorkspaceWorkloads(array $tables, ?int $maxRows): array
foreach ($tables as $table) { foreach ($tables as $table) {
$rows = DB::table($table) $rows = DB::table($table)
->join('tenants', 'tenants.id', '=', sprintf('%s.tenant_id', $table)) ->join('managed_environments', 'managed_environments.id', '=', sprintf('%s.managed_environment_id', $table))
->whereNull(sprintf('%s.workspace_id', $table)) ->whereNull(sprintf('%s.workspace_id', $table))
->whereNotNull('tenants.workspace_id') ->whereNotNull('managed_environments.workspace_id')
->selectRaw('tenants.workspace_id as workspace_id, COUNT(*) as row_count') ->selectRaw('managed_environments.workspace_id as workspace_id, COUNT(*) as row_count')
->groupBy('tenants.workspace_id') ->groupBy('managed_environments.workspace_id')
->get(); ->get();
foreach ($rows as $row) { foreach ($rows as $row) {

View File

@ -7,7 +7,7 @@
class TenantpilotDispatchBackupSchedules extends Command class TenantpilotDispatchBackupSchedules extends Command
{ {
protected $signature = 'tenantpilot:schedules:dispatch {--tenant=* : Limit to tenant_id/external_id}'; protected $signature = 'tenantpilot:schedules:dispatch {--tenant=* : Limit to managed_environment_id/external_id}';
protected $description = 'Dispatch due backup schedules (idempotent per schedule minute-slot).'; protected $description = 'Dispatch due backup schedules (idempotent per schedule minute-slot).';

View File

@ -2,7 +2,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Support\OperationRunType; use App\Support\OperationRunType;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
@ -10,7 +10,7 @@
class TenantpilotDispatchDirectoryGroupsSync extends Command class TenantpilotDispatchDirectoryGroupsSync extends Command
{ {
protected $signature = 'tenantpilot:directory-groups:dispatch {--tenant=* : Limit to tenant_id/external_id}'; protected $signature = 'tenantpilot:directory-groups:dispatch {--tenant=* : Limit to managed_environment_id/external_id}';
protected $description = 'Dispatch scheduled directory group sync runs (idempotent per tenant minute-slot).'; protected $description = 'Dispatch scheduled directory group sync runs (idempotent per tenant minute-slot).';
@ -96,7 +96,7 @@ public function handle(): int
*/ */
private function resolveTenants(array $tenantIdentifiers): \Illuminate\Support\Collection private function resolveTenants(array $tenantIdentifiers): \Illuminate\Support\Collection
{ {
$query = Tenant::activeQuery(); $query = ManagedEnvironment::activeQuery();
if ($tenantIdentifiers !== []) { if ($tenantIdentifiers !== []) {
$query->where(function ($subQuery) use ($tenantIdentifiers) { $query->where(function ($subQuery) use ($tenantIdentifiers) {
@ -107,8 +107,7 @@ private function resolveTenants(array $tenantIdentifiers): \Illuminate\Support\C
continue; continue;
} }
$subQuery->orWhere('tenant_id', $identifier) $subQuery->orWhere('slug', $identifier);
->orWhere('external_id', $identifier);
} }
}); });
} }

View File

@ -10,7 +10,7 @@
use App\Models\Policy; use App\Models\Policy;
use App\Models\PolicyVersion; use App\Models\PolicyVersion;
use App\Models\RestoreRun; use App\Models\RestoreRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\OperationRunType; use App\Support\OperationRunType;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@ -26,7 +26,7 @@ class TenantpilotPurgeNonPersistentData extends Command
* @var string * @var string
*/ */
protected $signature = 'tenantpilot:purge-nonpersistent protected $signature = 'tenantpilot:purge-nonpersistent
{tenant? : Tenant id / tenant_id / external_id (defaults to current tenant)} {tenant? : ManagedEnvironment id / managed_environment_id / external_id (defaults to current tenant)}
{--all : Purge for all tenants} {--all : Purge for all tenants}
{--force : Actually delete rows}'; {--force : Actually delete rows}';
@ -68,7 +68,7 @@ public function handle(): int
$counts = $this->countsForTenant($tenant); $counts = $this->countsForTenant($tenant);
$this->line(''); $this->line('');
$this->info("Tenant: {$tenant->id} ({$tenant->name})"); $this->info("ManagedEnvironment: {$tenant->id} ({$tenant->name})");
$this->table( $this->table(
['Table', 'Rows'], ['Table', 'Rows'],
collect($counts) collect($counts)
@ -83,31 +83,31 @@ public function handle(): int
DB::transaction(function () use ($tenant): void { DB::transaction(function () use ($tenant): void {
BackupSchedule::query() BackupSchedule::query()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->delete(); ->delete();
OperationRun::query() OperationRun::query()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->delete(); ->delete();
RestoreRun::withTrashed() RestoreRun::withTrashed()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->forceDelete(); ->forceDelete();
BackupItem::withTrashed() BackupItem::withTrashed()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->forceDelete(); ->forceDelete();
BackupSet::withTrashed() BackupSet::withTrashed()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->forceDelete(); ->forceDelete();
PolicyVersion::withTrashed() PolicyVersion::withTrashed()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->forceDelete(); ->forceDelete();
Policy::query() Policy::query()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->delete(); ->delete();
}); });
@ -122,19 +122,19 @@ public function handle(): int
private function resolveTenants() private function resolveTenants()
{ {
if ((bool) $this->option('all')) { if ((bool) $this->option('all')) {
return Tenant::query()->get(); return ManagedEnvironment::query()->get();
} }
$tenantArg = $this->argument('tenant'); $tenantArg = $this->argument('tenant');
if ($tenantArg !== null && $tenantArg !== '') { if ($tenantArg !== null && $tenantArg !== '') {
$tenant = Tenant::query()->forTenant($tenantArg)->first(); $tenant = ManagedEnvironment::query()->forTenant($tenantArg)->first();
return $tenant ? collect([$tenant]) : collect(); return $tenant ? collect([$tenant]) : collect();
} }
try { try {
return collect([Tenant::currentOrFail()]); return collect([ManagedEnvironment::currentOrFail()]);
} catch (RuntimeException) { } catch (RuntimeException) {
return collect(); return collect();
} }
@ -143,30 +143,30 @@ private function resolveTenants()
/** /**
* @return array<string,int> * @return array<string,int>
*/ */
private function countsForTenant(Tenant $tenant): array private function countsForTenant(ManagedEnvironment $tenant): array
{ {
return [ return [
'backup_schedules' => BackupSchedule::query()->where('tenant_id', $tenant->id)->count(), 'backup_schedules' => BackupSchedule::query()->where('managed_environment_id', $tenant->id)->count(),
'operation_runs' => OperationRun::query()->where('tenant_id', $tenant->id)->count(), 'operation_runs' => OperationRun::query()->where('managed_environment_id', $tenant->id)->count(),
'audit_logs_retained' => AuditLog::query()->where('tenant_id', $tenant->id)->count(), 'audit_logs_retained' => AuditLog::query()->where('managed_environment_id', $tenant->id)->count(),
'restore_runs' => RestoreRun::withTrashed()->where('tenant_id', $tenant->id)->count(), 'restore_runs' => RestoreRun::withTrashed()->where('managed_environment_id', $tenant->id)->count(),
'backup_items' => BackupItem::withTrashed()->where('tenant_id', $tenant->id)->count(), 'backup_items' => BackupItem::withTrashed()->where('managed_environment_id', $tenant->id)->count(),
'backup_sets' => BackupSet::withTrashed()->where('tenant_id', $tenant->id)->count(), 'backup_sets' => BackupSet::withTrashed()->where('managed_environment_id', $tenant->id)->count(),
'policy_versions' => PolicyVersion::withTrashed()->where('tenant_id', $tenant->id)->count(), 'policy_versions' => PolicyVersion::withTrashed()->where('managed_environment_id', $tenant->id)->count(),
'policies' => Policy::query()->where('tenant_id', $tenant->id)->count(), 'policies' => Policy::query()->where('managed_environment_id', $tenant->id)->count(),
]; ];
} }
/** /**
* @param array<string, int> $counts * @param array<string, int> $counts
*/ */
private function recordPurgeOperationRun(Tenant $tenant, array $counts): void private function recordPurgeOperationRun(ManagedEnvironment $tenant, array $counts): void
{ {
$deletedRows = Arr::except($counts, ['audit_logs_retained']); $deletedRows = Arr::except($counts, ['audit_logs_retained']);
OperationRun::query()->create([ OperationRun::query()->create([
'workspace_id' => (int) $tenant->workspace_id, 'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->id, 'managed_environment_id' => (int) $tenant->id,
'user_id' => null, 'user_id' => null,
'initiator_name' => 'System', 'initiator_name' => 'System',
'type' => OperationRunType::BackupSchedulePurge->value, 'type' => OperationRunType::BackupSchedulePurge->value,

View File

@ -4,7 +4,7 @@
use App\Models\BackupSchedule; use App\Models\BackupSchedule;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Services\Operations\OperationLifecycleReconciler; use App\Services\Operations\OperationLifecycleReconciler;
use App\Support\OperationCatalog; use App\Support\OperationCatalog;
@ -15,7 +15,7 @@
class TenantpilotReconcileBackupScheduleOperationRuns extends Command class TenantpilotReconcileBackupScheduleOperationRuns extends Command
{ {
protected $signature = 'tenantpilot:operation-runs:reconcile-backup-schedules protected $signature = 'tenantpilot:operation-runs:reconcile-backup-schedules
{--tenant=* : Limit to tenant_id/external_id} {--tenant=* : Limit to managed_environment_id/external_id}
{--older-than=5 : Only reconcile runs older than N minutes} {--older-than=5 : Only reconcile runs older than N minutes}
{--dry-run : Do not write changes}'; {--dry-run : Do not write changes}';
@ -46,7 +46,7 @@ public function handle(
return self::SUCCESS; return self::SUCCESS;
} }
$query->whereIn('tenant_id', $tenantIds); $query->whereIn('managed_environment_id', $tenantIds);
} }
$reconciled = 0; $reconciled = 0;
@ -78,7 +78,7 @@ public function handle(
$schedule = BackupSchedule::query() $schedule = BackupSchedule::query()
->whereKey((int) $backupScheduleId) ->whereKey((int) $backupScheduleId)
->where('tenant_id', (int) $operationRun->tenant_id) ->where('managed_environment_id', (int) $operationRun->managed_environment_id)
->first(); ->first();
if (! $schedule instanceof BackupSchedule) { if (! $schedule instanceof BackupSchedule) {
@ -135,7 +135,7 @@ private function resolveTenantIds(array $tenantIdentifiers): array
$tenantIds = []; $tenantIds = [];
foreach ($tenantIdentifiers as $identifier) { foreach ($tenantIdentifiers as $identifier) {
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->forTenant($identifier) ->forTenant($identifier)
->first(); ->first();

View File

@ -4,7 +4,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\Operations\OperationLifecycleReconciler; use App\Services\Operations\OperationLifecycleReconciler;
use App\Support\Operations\OperationLifecyclePolicy; use App\Support\Operations\OperationLifecyclePolicy;
use Illuminate\Console\Command; use Illuminate\Console\Command;
@ -13,7 +13,7 @@ class TenantpilotReconcileOperationRuns extends Command
{ {
protected $signature = 'tenantpilot:operation-runs:reconcile protected $signature = 'tenantpilot:operation-runs:reconcile
{--type=* : Limit reconciliation to one or more covered operation types} {--type=* : Limit reconciliation to one or more covered operation types}
{--tenant=* : Limit reconciliation to tenant_id or tenant external_id} {--tenant=* : Limit reconciliation to managed_environment_id or tenant external_id}
{--workspace=* : Limit reconciliation to workspace ids} {--workspace=* : Limit reconciliation to workspace ids}
{--limit=100 : Maximum number of active runs to inspect} {--limit=100 : Maximum number of active runs to inspect}
{--dry-run : Report the changes without writing them}'; {--dry-run : Report the changes without writing them}';
@ -93,9 +93,9 @@ private function resolveTenantIds(array $tenantIdentifiers): array
$tenantIds = []; $tenantIds = [];
foreach ($tenantIdentifiers as $identifier) { foreach ($tenantIdentifiers as $identifier) {
$tenant = Tenant::query()->forTenant($identifier)->first(); $tenant = ManagedEnvironment::query()->forTenant($identifier)->first();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$tenantIds[] = (int) $tenant->getKey(); $tenantIds[] = (int) $tenant->getKey();
} }
} }

View File

@ -55,7 +55,7 @@ public function handle(PolicySnapshotService $snapshotService): int
// Create PolicyVersion to save the snapshot // Create PolicyVersion to save the snapshot
$policy->versions()->create([ $policy->versions()->create([
'tenant_id' => $policy->tenant_id, 'managed_environment_id' => $policy->managed_environment_id,
'version_number' => $policy->versions()->max('version_number') + 1, 'version_number' => $policy->versions()->max('version_number') + 1,
'policy_type' => $policy->policy_type, 'policy_type' => $policy->policy_type,
'platform' => $policy->platform, 'platform' => $policy->platform,

View File

@ -3,7 +3,7 @@
namespace App\Contracts\Hardening; namespace App\Contracts\Hardening;
use App\Exceptions\Hardening\ProviderAccessHardeningRequired; use App\Exceptions\Hardening\ProviderAccessHardeningRequired;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
interface WriteGateInterface interface WriteGateInterface
{ {
@ -12,12 +12,12 @@ interface WriteGateInterface
* *
* @throws ProviderAccessHardeningRequired when the operation is blocked * @throws ProviderAccessHardeningRequired when the operation is blocked
*/ */
public function evaluate(Tenant $tenant, string $operationType): void; public function evaluate(ManagedEnvironment $tenant, string $operationType): void;
/** /**
* Check whether the gate would block a write operation for the given tenant. * Check whether the gate would block a write operation for the given tenant.
* *
* Non-throwing variant for UI disabled-state checks. * Non-throwing variant for UI disabled-state checks.
*/ */
public function wouldBlock(Tenant $tenant): bool; public function wouldBlock(ManagedEnvironment $tenant): bool;
} }

View File

@ -4,7 +4,7 @@
namespace App\Filament\Concerns; namespace App\Filament\Concerns;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\WorkspaceIsolation\TenantOwnedQueryScope; use App\Support\WorkspaceIsolation\TenantOwnedQueryScope;
use App\Support\WorkspaceIsolation\TenantOwnedRecordResolver; use App\Support\WorkspaceIsolation\TenantOwnedRecordResolver;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
@ -23,7 +23,7 @@ protected static function tenantOwnedRelationshipName(): string
: 'tenant'; : 'tenant';
} }
protected static function resolveTenantContextForTenantOwnedRecords(): ?Tenant protected static function resolveTenantContextForTenantOwnedRecords(): ?ManagedEnvironment
{ {
if (method_exists(static::class, 'resolveTenantContextForCurrentPanel')) { if (method_exists(static::class, 'resolveTenantContextForCurrentPanel')) {
return static::resolveTenantContextForCurrentPanel(); return static::resolveTenantContextForCurrentPanel();
@ -41,7 +41,7 @@ public static function getTenantOwnedEloquentQuery(): Builder
return static::scopeTenantOwnedQuery(parent::getEloquentQuery()); return static::scopeTenantOwnedQuery(parent::getEloquentQuery());
} }
protected static function scopeTenantOwnedQuery(Builder $query, ?Tenant $tenant = null): Builder protected static function scopeTenantOwnedQuery(Builder $query, ?ManagedEnvironment $tenant = null): Builder
{ {
return app(TenantOwnedQueryScope::class)->apply( return app(TenantOwnedQueryScope::class)->apply(
$query, $query,
@ -50,7 +50,7 @@ protected static function scopeTenantOwnedQuery(Builder $query, ?Tenant $tenant
); );
} }
protected static function resolveTenantOwnedRecord(Model|int|string|null $record, ?Builder $query = null, ?Tenant $tenant = null): ?Model protected static function resolveTenantOwnedRecord(Model|int|string|null $record, ?Builder $query = null, ?ManagedEnvironment $tenant = null): ?Model
{ {
$scopedQuery = static::scopeTenantOwnedQuery( $scopedQuery = static::scopeTenantOwnedQuery(
$query ?? parent::getEloquentQuery(), $query ?? parent::getEloquentQuery(),
@ -60,7 +60,7 @@ protected static function resolveTenantOwnedRecord(Model|int|string|null $record
return app(TenantOwnedRecordResolver::class)->resolve($scopedQuery, $record); return app(TenantOwnedRecordResolver::class)->resolve($scopedQuery, $record);
} }
protected static function resolveTenantOwnedRecordOrFail(Model|int|string|null $record, ?Builder $query = null, ?Tenant $tenant = null): Model protected static function resolveTenantOwnedRecordOrFail(Model|int|string|null $record, ?Builder $query = null, ?ManagedEnvironment $tenant = null): Model
{ {
$scopedQuery = static::scopeTenantOwnedQuery( $scopedQuery = static::scopeTenantOwnedQuery(
$query ?? parent::getEloquentQuery(), $query ?? parent::getEloquentQuery(),

View File

@ -4,50 +4,50 @@
namespace App\Filament\Concerns; namespace App\Filament\Concerns;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use RuntimeException; use RuntimeException;
trait ResolvesPanelTenantContext trait ResolvesPanelTenantContext
{ {
protected static function resolveTenantContextForCurrentPanel(): ?Tenant protected static function resolveTenantContextForCurrentPanel(): ?ManagedEnvironment
{ {
$request = request(); $request = request();
if (static::currentPanelId($request) === 'admin') { if (static::currentPanelId($request) === 'admin') {
$tenant = app(OperateHubShell::class)->tenantOwnedPanelContext(request()); $tenant = app(OperateHubShell::class)->tenantOwnedPanelContext(request());
return $tenant instanceof Tenant ? $tenant : null; return $tenant instanceof ManagedEnvironment ? $tenant : null;
} }
$tenant = Tenant::current(); $tenant = ManagedEnvironment::current();
return $tenant instanceof Tenant ? $tenant : null; return $tenant instanceof ManagedEnvironment ? $tenant : null;
} }
public static function panelTenantContext(): ?Tenant public static function panelTenantContext(): ?ManagedEnvironment
{ {
return static::resolveTenantContextForCurrentPanel(); return static::resolveTenantContextForCurrentPanel();
} }
public static function trustedPanelTenantContext(): ?Tenant public static function trustedPanelTenantContext(): ?ManagedEnvironment
{ {
return static::panelTenantContext(); return static::panelTenantContext();
} }
protected static function resolveTenantContextForCurrentPanelOrFail(): Tenant protected static function resolveTenantContextForCurrentPanelOrFail(): ManagedEnvironment
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
throw new RuntimeException('No tenant context selected.'); throw new RuntimeException('No tenant context selected.');
} }
return $tenant; return $tenant;
} }
protected static function resolveTrustedPanelTenantContextOrFail(): Tenant protected static function resolveTrustedPanelTenantContextOrFail(): ManagedEnvironment
{ {
return static::resolveTenantContextForCurrentPanelOrFail(); return static::resolveTenantContextForCurrentPanelOrFail();
} }

View File

@ -4,7 +4,7 @@
namespace App\Filament\Concerns; namespace App\Filament\Concerns;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use App\Support\WorkspaceIsolation\TenantOwnedModelFamilies; use App\Support\WorkspaceIsolation\TenantOwnedModelFamilies;
use Filament\Facades\Filament; use Filament\Facades\Filament;
@ -54,7 +54,7 @@ protected static function resolveGlobalSearchTenant(): ?Model
if (Filament::getCurrentPanel()?->getId() === 'admin') { if (Filament::getCurrentPanel()?->getId() === 'admin') {
$tenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $tenant = app(OperateHubShell::class)->activeEntitledTenant(request());
return $tenant instanceof Tenant ? $tenant : null; return $tenant instanceof ManagedEnvironment ? $tenant : null;
} }
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();

View File

@ -9,7 +9,7 @@
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\BaselineProfile; use App\Models\BaselineProfile;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Baselines\BaselineCompareService; use App\Services\Baselines\BaselineCompareService;
@ -185,7 +185,7 @@ public static function canAccess(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return false; return false;
} }
@ -217,7 +217,7 @@ public function refreshStats(): void
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$stats = BaselineCompareStats::forTenant($tenant); $stats = BaselineCompareStats::forTenant($tenant);
$aggregate = $tenant instanceof Tenant $aggregate = $tenant instanceof ManagedEnvironment
? $this->governanceAggregate($tenant, $stats) ? $this->governanceAggregate($tenant, $stats)
: null; : null;
@ -442,7 +442,7 @@ private function compareNowAction(): Action
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
Notification::make()->title('Select a tenant to compare baselines')->danger()->send(); Notification::make()->title('Select a tenant to compare baselines')->danger()->send();
return; return;
@ -509,7 +509,7 @@ public function getFindingsUrl(): ?string
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -524,7 +524,7 @@ public function getRunUrl(): ?string
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -551,7 +551,7 @@ public function openCompareMatrixUrl(): ?string
return $url.(str_contains($url, '?') ? '&' : '?').http_build_query($query); return $url.(str_contains($url, '?') ? '&' : '?').http_build_query($query);
} }
private function governanceAggregate(Tenant $tenant, BaselineCompareStats $stats): TenantGovernanceAggregate private function governanceAggregate(ManagedEnvironment $tenant, BaselineCompareStats $stats): TenantGovernanceAggregate
{ {
/** @var TenantGovernanceAggregateResolver $resolver */ /** @var TenantGovernanceAggregateResolver $resolver */
$resolver = app(TenantGovernanceAggregateResolver::class); $resolver = app(TenantGovernanceAggregateResolver::class);
@ -575,7 +575,7 @@ private function resolveCompareMatrixProfile(): ?BaselineProfile
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\BaselineProfileResource; use App\Filament\Resources\BaselineProfileResource;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\BaselineProfile; use App\Models\BaselineProfile;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
@ -283,7 +283,7 @@ public function form(Schema $schema): Schema
]) ])
->schema([ ->schema([
Select::make('draftTenantSort') Select::make('draftTenantSort')
->label('Tenant sort') ->label('ManagedEnvironment sort')
->options(fn (): array => $this->matrixOptions('tenantSortOptions')) ->options(fn (): array => $this->matrixOptions('tenantSortOptions'))
->default('tenant_name') ->default('tenant_name')
->native(false) ->native(false)
@ -441,7 +441,7 @@ public function tenantCompareUrl(int $tenantId, ?string $subjectKey = null): ?st
{ {
$tenant = $this->tenant($tenantId); $tenant = $this->tenant($tenantId);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -456,7 +456,7 @@ public function findingUrl(int $tenantId, int $findingId, ?string $subjectKey =
{ {
$tenant = $this->tenant($tenantId); $tenant = $this->tenant($tenantId);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -573,7 +573,7 @@ public function stagedFilterSummary(): array
} }
if ($this->draftTenantSort !== $this->tenantSort) { if ($this->draftTenantSort !== $this->tenantSort) {
$summary['Tenant sort'] = $this->draftTenantSort; $summary['ManagedEnvironment sort'] = $this->draftTenantSort;
} }
if ($this->draftSubjectSort !== $this->subjectSort) { if ($this->draftSubjectSort !== $this->subjectSort) {
@ -855,7 +855,7 @@ private function routeParameters(array $overrides = []): array
], static fn (mixed $value): bool => $value !== null && $value !== [] && $value !== ''); ], static fn (mixed $value): bool => $value !== null && $value !== [] && $value !== '');
} }
private function navigationContext(?Tenant $tenant = null, ?string $subjectKey = null): CanonicalNavigationContext private function navigationContext(?ManagedEnvironment $tenant = null, ?string $subjectKey = null): CanonicalNavigationContext
{ {
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */
$profile = $this->getRecord(); $profile = $this->getRecord();
@ -870,9 +870,9 @@ private function navigationContext(?Tenant $tenant = null, ?string $subjectKey =
); );
} }
private function tenant(int $tenantId): ?Tenant private function tenant(int $tenantId): ?ManagedEnvironment
{ {
return Tenant::query() return ManagedEnvironment::query()
->whereKey($tenantId) ->whereKey($tenantId)
->where('workspace_id', (int) $this->getRecord()->workspace_id) ->where('workspace_id', (int) $this->getRecord()->workspace_id)
->first(); ->first();

View File

@ -4,7 +4,7 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\UserTenantPreference; use App\Models\UserTenantPreference;
use App\Services\Tenants\TenantOperabilityService; use App\Services\Tenants\TenantOperabilityService;
@ -43,14 +43,14 @@ protected function getLayoutData(): array
} }
/** /**
* @return Collection<int, Tenant> * @return Collection<int, ManagedEnvironment>
*/ */
public function getTenants(): Collection public function getTenants(): Collection
{ {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
return Tenant::query()->whereRaw('1 = 0')->get(); return ManagedEnvironment::query()->whereRaw('1 = 0')->get();
} }
$tenants = $user->getTenants(Filament::getCurrentOrDefaultPanel()); $tenants = $user->getTenants(Filament::getCurrentOrDefaultPanel());
@ -75,9 +75,9 @@ public function selectTenant(int $tenantId): void
$tenant = null; $tenant = null;
if ($workspaceId === null) { if ($workspaceId === null) {
$tenant = Tenant::query()->whereKey($tenantId)->first(); $tenant = ManagedEnvironment::query()->whereKey($tenantId)->first();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$workspace = $tenant->workspace; $workspace = $tenant->workspace;
if ($workspace !== null && $user->canAccessTenant($tenant)) { if ($workspace !== null && $user->canAccessTenant($tenant)) {
@ -93,14 +93,14 @@ public function selectTenant(int $tenantId): void
return; return;
} }
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== $workspaceId) { if (! $tenant instanceof ManagedEnvironment || (int) $tenant->workspace_id !== $workspaceId) {
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->where('workspace_id', $workspaceId) ->where('workspace_id', $workspaceId)
->whereKey($tenantId) ->whereKey($tenantId)
->first(); ->first();
} }
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -129,12 +129,12 @@ public function selectTenant(int $tenantId): void
$this->redirect(TenantDashboard::getUrl(panel: 'tenant', tenant: $tenant)); $this->redirect(TenantDashboard::getUrl(panel: 'tenant', tenant: $tenant));
} }
public function tenantLifecyclePresentation(Tenant $tenant): TenantLifecyclePresentation public function tenantLifecyclePresentation(ManagedEnvironment $tenant): TenantLifecyclePresentation
{ {
return TenantLifecyclePresentation::fromTenant($tenant); return TenantLifecyclePresentation::fromTenant($tenant);
} }
private function persistLastTenant(User $user, Tenant $tenant): void private function persistLastTenant(User $user, ManagedEnvironment $tenant): void
{ {
if (Schema::hasColumn('users', 'last_tenant_id')) { if (Schema::hasColumn('users', 'last_tenant_id')) {
$user->forceFill(['last_tenant_id' => $tenant->getKey()])->save(); $user->forceFill(['last_tenant_id' => $tenant->getKey()])->save();
@ -142,12 +142,12 @@ private function persistLastTenant(User $user, Tenant $tenant): void
return; return;
} }
if (! Schema::hasTable('user_tenant_preferences')) { if (! Schema::hasTable('user_managed_environment_preferences')) {
return; return;
} }
UserTenantPreference::query()->updateOrCreate( UserTenantPreference::query()->updateOrCreate(
['user_id' => $user->getKey(), 'tenant_id' => $tenant->getKey()], ['user_id' => $user->getKey(), 'managed_environment_id' => $tenant->getKey()],
['last_used_at' => now()] ['last_used_at' => now()]
); );
} }

View File

@ -64,7 +64,7 @@ public function getWorkspaces(): Collection
}) })
->whereNull('archived_at') ->whereNull('archived_at')
->withCount(['tenants' => function ($query): void { ->withCount(['tenants' => function ($query): void {
$query->where('status', 'active'); $query->where('lifecycle_status', 'active');
}]) }])
->orderBy('name') ->orderBy('name')
->get(); ->get();

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Models\InventoryItem; use App\Models\InventoryItem;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
@ -60,7 +60,7 @@ class CrossTenantComparePage extends Page implements HasForms
protected static string|UnitEnum|null $navigationGroup = 'Governance'; protected static string|UnitEnum|null $navigationGroup = 'Governance';
protected static ?string $title = 'Cross-Tenant Compare'; protected static ?string $title = 'Cross-ManagedEnvironment Compare';
protected static ?string $slug = 'cross-tenant-compare'; protected static ?string $slug = 'cross-tenant-compare';
@ -178,7 +178,7 @@ protected function getHeaderActions(): array
$sourceTenant = $this->selectedSourceTenant(); $sourceTenant = $this->selectedSourceTenant();
if ($sourceTenant instanceof Tenant) { if ($sourceTenant instanceof ManagedEnvironment) {
$actions[] = Action::make('open_source_tenant') $actions[] = Action::make('open_source_tenant')
->label('Open source tenant') ->label('Open source tenant')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
@ -188,7 +188,7 @@ protected function getHeaderActions(): array
$targetTenant = $this->selectedTargetTenant(); $targetTenant = $this->selectedTargetTenant();
if ($targetTenant instanceof Tenant) { if ($targetTenant instanceof ManagedEnvironment) {
$actions[] = Action::make('open_target_tenant') $actions[] = Action::make('open_target_tenant')
->label('Open target tenant') ->label('Open target tenant')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
@ -388,17 +388,17 @@ public function selectionUrl(): string
} }
public static function launchUrl( public static function launchUrl(
?Tenant $sourceTenant = null, ?ManagedEnvironment $sourceTenant = null,
?Tenant $targetTenant = null, ?ManagedEnvironment $targetTenant = null,
?CanonicalNavigationContext $navigationContext = null, ?CanonicalNavigationContext $navigationContext = null,
): string { ): string {
$parameters = []; $parameters = [];
if ($sourceTenant instanceof Tenant) { if ($sourceTenant instanceof ManagedEnvironment) {
$parameters[self::SOURCE_TENANT_QUERY_KEY] = (int) $sourceTenant->getKey(); $parameters[self::SOURCE_TENANT_QUERY_KEY] = (int) $sourceTenant->getKey();
} }
if ($targetTenant instanceof Tenant) { if ($targetTenant instanceof ManagedEnvironment) {
$parameters[self::TARGET_TENANT_QUERY_KEY] = (int) $targetTenant->getKey(); $parameters[self::TARGET_TENANT_QUERY_KEY] = (int) $targetTenant->getKey();
} }
@ -442,7 +442,7 @@ public function sourceTenantUrl(): ?string
{ {
$tenant = $this->selectedSourceTenant(); $tenant = $this->selectedSourceTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -453,7 +453,7 @@ public function targetTenantUrl(): ?string
{ {
$tenant = $this->selectedTargetTenant(); $tenant = $this->selectedTargetTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -556,7 +556,7 @@ private function authorizePromotionExecution(): void
$targetTenant = $this->selectedTargetTenant(); $targetTenant = $this->selectedTargetTenant();
if (! $targetTenant instanceof Tenant) { if (! $targetTenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -573,7 +573,7 @@ private function compareSelection(): ?CrossTenantCompareSelection
$sourceTenant = $this->selectedSourceTenant(); $sourceTenant = $this->selectedSourceTenant();
$targetTenant = $this->selectedTargetTenant(); $targetTenant = $this->selectedTargetTenant();
if (! $sourceTenant instanceof Tenant || ! $targetTenant instanceof Tenant) { if (! $sourceTenant instanceof ManagedEnvironment || ! $targetTenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -590,7 +590,7 @@ private function compareSelection(): ?CrossTenantCompareSelection
); );
} }
private function selectedSourceTenant(): ?Tenant private function selectedSourceTenant(): ?ManagedEnvironment
{ {
if ($this->sourceTenantId === null) { if ($this->sourceTenantId === null) {
return null; return null;
@ -599,7 +599,7 @@ private function selectedSourceTenant(): ?Tenant
return $this->resolveAuthorizedTenant($this->sourceTenantId); return $this->resolveAuthorizedTenant($this->sourceTenantId);
} }
private function selectedTargetTenant(): ?Tenant private function selectedTargetTenant(): ?ManagedEnvironment
{ {
if ($this->targetTenantId === null) { if ($this->targetTenantId === null) {
return null; return null;
@ -608,7 +608,7 @@ private function selectedTargetTenant(): ?Tenant
return $this->resolveAuthorizedTenant($this->targetTenantId); return $this->resolveAuthorizedTenant($this->targetTenantId);
} }
private function resolveAuthorizedTenant(string $tenantId): Tenant private function resolveAuthorizedTenant(string $tenantId): ManagedEnvironment
{ {
$workspace = $this->workspace(); $workspace = $this->workspace();
$user = auth()->user(); $user = auth()->user();
@ -617,12 +617,12 @@ private function resolveAuthorizedTenant(string $tenantId): Tenant
abort(404); abort(404);
} }
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->where('workspace_id', (int) $workspace->getKey()) ->where('workspace_id', (int) $workspace->getKey())
->whereKey((int) $tenantId) ->whereKey((int) $tenantId)
->first(); ->first();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -652,16 +652,16 @@ private function tenantOptions(): array
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
$tenants = $user->tenants() $tenants = $user->tenants()
->where('tenants.workspace_id', (int) $workspace->getKey()) ->where('managed_environments.workspace_id', (int) $workspace->getKey())
->select('tenants.*') ->select('managed_environments.*')
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(); ->get();
$resolver->primeMemberships($user, $tenants->modelKeys()); $resolver->primeMemberships($user, $tenants->modelKeys());
return $tenants return $tenants
->filter(fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)) ->filter(fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_VIEW))
->mapWithKeys(fn (Tenant $tenant): array => [ ->mapWithKeys(fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => (string) $tenant->name, (string) $tenant->getKey() => (string) $tenant->name,
]) ])
->all(); ->all();
@ -679,7 +679,7 @@ private function policyTypeOptions(): array
} }
return InventoryItem::query() return InventoryItem::query()
->whereIn('tenant_id', $tenantIds) ->whereIn('managed_environment_id', $tenantIds)
->whereNotNull('policy_type') ->whereNotNull('policy_type')
->where('policy_type', '!=', '') ->where('policy_type', '!=', '')
->distinct() ->distinct()
@ -740,7 +740,7 @@ private function executePromotionDisabledReason(): ?string
$targetTenant = $this->selectedTargetTenant(); $targetTenant = $this->selectedTargetTenant();
if ($targetTenant instanceof Tenant) { if ($targetTenant instanceof ManagedEnvironment) {
/** @var CapabilityResolver $resolver */ /** @var CapabilityResolver $resolver */
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\Finding; use App\Models\Finding;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
@ -54,7 +54,7 @@ class FindingsHygieneReport extends Page implements HasTable
protected string $view = 'filament.pages.findings.findings-hygiene-report'; protected string $view = 'filament.pages.findings.findings-hygiene-report';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $visibleTenants = null; private ?array $visibleTenants = null;
@ -109,7 +109,7 @@ public function table(Table $table): Table
->persistFiltersInSession() ->persistFiltersInSession()
->columns([ ->columns([
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant'), ->label('ManagedEnvironment'),
TextColumn::make('subject_display_name') TextColumn::make('subject_display_name')
->label('Finding') ->label('Finding')
->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey()) ->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey())
@ -138,8 +138,8 @@ public function table(Table $table): Table
->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($this->hygieneService()->lastWorkflowActivityAt($record))), ->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($this->hygieneService()->lastWorkflowActivityAt($record))),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->searchable(), ->searchable(),
]) ])
@ -183,10 +183,10 @@ public function availableFilters(): array
], ],
[ [
'key' => 'tenant', 'key' => 'tenant',
'label' => 'Tenant', 'label' => 'ManagedEnvironment',
'fixed' => false, 'fixed' => false,
'options' => collect($this->visibleTenants()) 'options' => collect($this->visibleTenants())
->map(fn (Tenant $tenant): array => [ ->map(fn (ManagedEnvironment $tenant): array => [
'value' => (string) $tenant->getKey(), 'value' => (string) $tenant->getKey(),
'label' => (string) $tenant->name, 'label' => (string) $tenant->name,
]) ])
@ -290,12 +290,12 @@ public function updatedTableFilters(): void
public function clearTenantFilter(): void public function clearTenantFilter(): void
{ {
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->resetTable(); $this->resetTable();
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function visibleTenants(): array public function visibleTenants(): array
{ {
@ -394,7 +394,7 @@ private function filteredIssueQuery(bool $includeTenantFilter = true, ?string $r
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->visibleTenants()) return collect($this->visibleTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => (string) $tenant->name, (string) $tenant->getKey() => (string) $tenant->name,
]) ])
->all(); ->all();
@ -413,8 +413,8 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
@ -422,7 +422,7 @@ private function applyRequestedTenantPrefilter(): void
private function normalizeTenantFilterState(): void private function normalizeTenantFilterState(): void
{ {
$configuredTenantFilter = data_get($this->currentFiltersState(), 'tenant_id.value'); $configuredTenantFilter = data_get($this->currentFiltersState(), 'managed_environment_id.value');
if ($configuredTenantFilter === null || $configuredTenantFilter === '') { if ($configuredTenantFilter === null || $configuredTenantFilter === '') {
return; return;
@ -432,7 +432,7 @@ private function normalizeTenantFilterState(): void
return; return;
} }
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
} }
/** /**
@ -450,7 +450,7 @@ private function currentFiltersState(): array
private function currentTenantFilterId(): ?int private function currentTenantFilterId(): ?int
{ {
$tenantFilter = data_get($this->currentFiltersState(), 'tenant_id.value'); $tenantFilter = data_get($this->currentFiltersState(), 'managed_environment_id.value');
if (! is_numeric($tenantFilter)) { if (! is_numeric($tenantFilter)) {
return null; return null;
@ -467,7 +467,7 @@ private function currentTenantFilterId(): ?int
return null; return null;
} }
private function filteredTenant(): ?Tenant private function filteredTenant(): ?ManagedEnvironment
{ {
$tenantId = $this->currentTenantFilterId(); $tenantId = $this->currentTenantFilterId();
@ -484,11 +484,11 @@ private function filteredTenant(): ?Tenant
return null; return null;
} }
private function activeVisibleTenant(): ?Tenant private function activeVisibleTenant(): ?ManagedEnvironment
{ {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -505,13 +505,13 @@ private function tenantPrefilterSource(): string
{ {
$tenant = $this->filteredTenant(); $tenant = $this->filteredTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'none'; return 'none';
} }
$activeTenant = $this->activeVisibleTenant(); $activeTenant = $this->activeVisibleTenant();
if ($activeTenant instanceof Tenant && $activeTenant->is($tenant)) { if ($activeTenant instanceof ManagedEnvironment && $activeTenant->is($tenant)) {
return 'active_tenant_context'; return 'active_tenant_context';
} }
@ -561,7 +561,7 @@ private function findingDetailUrl(Finding $record): string
{ {
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '#'; return '#';
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\Finding; use App\Models\Finding;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -62,12 +62,12 @@ class FindingsIntakeQueue extends Page implements HasTable
protected string $view = 'filament.pages.findings.findings-intake-queue'; protected string $view = 'filament.pages.findings.findings-intake-queue';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $visibleTenants = null; private ?array $visibleTenants = null;
@ -135,7 +135,7 @@ public function table(Table $table): Table
->persistFiltersInSession() ->persistFiltersInSession()
->columns([ ->columns([
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant'), ->label('ManagedEnvironment'),
TextColumn::make('subject_display_name') TextColumn::make('subject_display_name')
->label('Finding') ->label('Finding')
->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey()) ->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey())
@ -166,8 +166,8 @@ public function table(Table $table): Table
->color(fn (Finding $record): string => $this->queueReasonColor($record)), ->color(fn (Finding $record): string => $this->queueReasonColor($record)),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->searchable(), ->searchable(),
]) ])
@ -278,12 +278,12 @@ public function updatedTableFilters(): void
public function clearTenantFilter(): void public function clearTenantFilter(): void
{ {
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->resetTable(); $this->resetTable();
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function visibleTenants(): array public function visibleTenants(): array
{ {
@ -301,12 +301,12 @@ public function visibleTenants(): array
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
$resolver->primeMemberships( $resolver->primeMemberships(
$user, $user,
array_map(static fn (Tenant $tenant): int => (int) $tenant->getKey(), $tenants), array_map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(), $tenants),
); );
return $this->visibleTenants = array_values(array_filter( return $this->visibleTenants = array_values(array_filter(
$tenants, $tenants,
fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW), fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW),
)); ));
} }
@ -335,7 +335,7 @@ private function claimAction(): Action
$tenant = $record->tenant; $tenant = $record->tenant;
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
throw new NotFoundHttpException; throw new NotFoundHttpException;
} }
@ -406,7 +406,7 @@ private function authorizePageAccess(): void
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function authorizedTenants(): array private function authorizedTenants(): array
{ {
@ -422,10 +422,10 @@ private function authorizedTenants(): array
} }
return $this->authorizedTenants = $user->tenants() return $this->authorizedTenants = $user->tenants()
->where('tenants.workspace_id', (int) $workspace->getKey()) ->where('managed_environments.workspace_id', (int) $workspace->getKey())
->where('tenants.status', 'active') ->where('managed_environments.lifecycle_status', 'active')
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(['tenants.id', 'tenants.name', 'tenants.external_id', 'tenants.workspace_id']) ->get(['managed_environments.id', 'managed_environments.name', 'managed_environments.slug', 'managed_environments.workspace_id'])
->all(); ->all();
} }
@ -448,7 +448,7 @@ private function queueBaseQuery(): Builder
{ {
$workspace = $this->workspace(); $workspace = $this->workspace();
$tenantIds = array_map( $tenantIds = array_map(
static fn (Tenant $tenant): int => (int) $tenant->getKey(), static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(),
$this->visibleTenants(), $this->visibleTenants(),
); );
@ -460,7 +460,7 @@ private function queueBaseQuery(): Builder
->with(['tenant', 'ownerUser', 'assigneeUser']) ->with(['tenant', 'ownerUser', 'assigneeUser'])
->withSubjectDisplayName() ->withSubjectDisplayName()
->where('workspace_id', (int) $workspace->getKey()) ->where('workspace_id', (int) $workspace->getKey())
->whereIn('tenant_id', $tenantIds === [] ? [-1] : $tenantIds) ->whereIn('managed_environment_id', $tenantIds === [] ? [-1] : $tenantIds)
->whereNull('assignee_user_id') ->whereNull('assignee_user_id')
->whereIn('status', Finding::openStatuses()); ->whereIn('status', Finding::openStatuses());
} }
@ -479,7 +479,7 @@ private function filteredQueueQuery(
$resolvedQueueView = $queueView ?? $this->queueView; $resolvedQueueView = $queueView ?? $this->queueView;
if ($includeTenantFilter && ($tenantId = $this->currentTenantFilterId()) !== null) { if ($includeTenantFilter && ($tenantId = $this->currentTenantFilterId()) !== null) {
$query->where('tenant_id', $tenantId); $query->where('managed_environment_id', $tenantId);
} }
if ($resolvedQueueView === 'needs_triage') { if ($resolvedQueueView === 'needs_triage') {
@ -514,7 +514,7 @@ private function filteredQueueQuery(
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->visibleTenants()) return collect($this->visibleTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => (string) $tenant->name, (string) $tenant->getKey() => (string) $tenant->name,
]) ])
->all(); ->all();
@ -533,8 +533,8 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
@ -542,7 +542,7 @@ private function applyRequestedTenantPrefilter(): void
private function normalizeTenantFilterState(): void private function normalizeTenantFilterState(): void
{ {
$configuredTenantFilter = data_get($this->currentQueueFiltersState(), 'tenant_id.value'); $configuredTenantFilter = data_get($this->currentQueueFiltersState(), 'managed_environment_id.value');
if ($configuredTenantFilter === null || $configuredTenantFilter === '') { if ($configuredTenantFilter === null || $configuredTenantFilter === '') {
return; return;
@ -552,7 +552,7 @@ private function normalizeTenantFilterState(): void
return; return;
} }
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
} }
/** /**
@ -570,7 +570,7 @@ private function currentQueueFiltersState(): array
private function currentTenantFilterId(): ?int private function currentTenantFilterId(): ?int
{ {
$tenantFilter = data_get($this->currentQueueFiltersState(), 'tenant_id.value'); $tenantFilter = data_get($this->currentQueueFiltersState(), 'managed_environment_id.value');
if (! is_numeric($tenantFilter)) { if (! is_numeric($tenantFilter)) {
return null; return null;
@ -587,7 +587,7 @@ private function currentTenantFilterId(): ?int
return null; return null;
} }
private function filteredTenant(): ?Tenant private function filteredTenant(): ?ManagedEnvironment
{ {
$tenantId = $this->currentTenantFilterId(); $tenantId = $this->currentTenantFilterId();
@ -604,11 +604,11 @@ private function filteredTenant(): ?Tenant
return null; return null;
} }
private function activeVisibleTenant(): ?Tenant private function activeVisibleTenant(): ?ManagedEnvironment
{ {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -625,13 +625,13 @@ private function tenantPrefilterSource(): string
{ {
$tenant = $this->filteredTenant(); $tenant = $this->filteredTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'none'; return 'none';
} }
$activeTenant = $this->activeVisibleTenant(); $activeTenant = $this->activeVisibleTenant();
if ($activeTenant instanceof Tenant && $activeTenant->is($tenant)) { if ($activeTenant instanceof ManagedEnvironment && $activeTenant->is($tenant)) {
return 'active_tenant_context'; return 'active_tenant_context';
} }
@ -690,7 +690,7 @@ private function findingDetailUrl(Finding $record): string
{ {
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '#'; return '#';
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\Finding; use App\Models\Finding;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -58,12 +58,12 @@ class MyFindingsInbox extends Page implements HasTable
protected string $view = 'filament.pages.findings.my-findings-inbox'; protected string $view = 'filament.pages.findings.my-findings-inbox';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $visibleTenants = null; private ?array $visibleTenants = null;
@ -127,7 +127,7 @@ public function table(Table $table): Table
->persistFiltersInSession() ->persistFiltersInSession()
->columns([ ->columns([
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant'), ->label('ManagedEnvironment'),
TextColumn::make('subject_display_name') TextColumn::make('subject_display_name')
->label('Finding') ->label('Finding')
->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey()) ->state(fn (Finding $record): string => $record->resolvedSubjectDisplayName() ?? 'Finding #'.$record->getKey())
@ -153,8 +153,8 @@ public function table(Table $table): Table
->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($record->due_at) ?? FindingResource::dueAttentionLabelFor($record)), ->description(fn (Finding $record): ?string => FindingExceptionResource::relativeTimeDescription($record->due_at) ?? FindingResource::dueAttentionLabelFor($record)),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->searchable(), ->searchable(),
Filter::make('overdue') Filter::make('overdue')
@ -207,10 +207,10 @@ public function availableFilters(): array
], ],
[ [
'key' => 'tenant', 'key' => 'tenant',
'label' => 'Tenant', 'label' => 'ManagedEnvironment',
'fixed' => false, 'fixed' => false,
'options' => collect($this->visibleTenants()) 'options' => collect($this->visibleTenants())
->map(fn (Tenant $tenant): array => [ ->map(fn (ManagedEnvironment $tenant): array => [
'value' => (string) $tenant->getKey(), 'value' => (string) $tenant->getKey(),
'label' => (string) $tenant->name, 'label' => (string) $tenant->name,
]) ])
@ -272,7 +272,7 @@ public function emptyState(): array
$activeTenant = $this->activeVisibleTenant(); $activeTenant = $this->activeVisibleTenant();
if ($activeTenant instanceof Tenant) { if ($activeTenant instanceof ManagedEnvironment) {
return [ return [
'title' => 'No visible assigned findings right now', 'title' => 'No visible assigned findings right now',
'body' => 'Nothing currently assigned to you needs attention in the visible tenant scope. You can still open tenant findings for broader context.', 'body' => 'Nothing currently assigned to you needs attention in the visible tenant scope. You can still open tenant findings for broader context.',
@ -302,12 +302,12 @@ public function updatedTableFilters(): void
public function clearTenantFilter(): void public function clearTenantFilter(): void
{ {
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->resetTable(); $this->resetTable();
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function visibleTenants(): array public function visibleTenants(): array
{ {
@ -325,12 +325,12 @@ public function visibleTenants(): array
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
$resolver->primeMemberships( $resolver->primeMemberships(
$user, $user,
array_map(static fn (Tenant $tenant): int => (int) $tenant->getKey(), $tenants), array_map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(), $tenants),
); );
return $this->visibleTenants = array_values(array_filter( return $this->visibleTenants = array_values(array_filter(
$tenants, $tenants,
fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW), fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW),
)); ));
} }
@ -355,7 +355,7 @@ private function authorizePageAccess(): void
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function authorizedTenants(): array private function authorizedTenants(): array
{ {
@ -371,10 +371,10 @@ private function authorizedTenants(): array
} }
return $this->authorizedTenants = $user->tenants() return $this->authorizedTenants = $user->tenants()
->where('tenants.workspace_id', (int) $workspace->getKey()) ->where('managed_environments.workspace_id', (int) $workspace->getKey())
->where('tenants.status', 'active') ->where('managed_environments.lifecycle_status', 'active')
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(['tenants.id', 'tenants.name', 'tenants.external_id', 'tenants.workspace_id']) ->get(['managed_environments.id', 'managed_environments.name', 'managed_environments.slug', 'managed_environments.workspace_id'])
->all(); ->all();
} }
@ -398,7 +398,7 @@ private function queueBaseQuery(): Builder
$user = auth()->user(); $user = auth()->user();
$workspace = $this->workspace(); $workspace = $this->workspace();
$tenantIds = array_map( $tenantIds = array_map(
static fn (Tenant $tenant): int => (int) $tenant->getKey(), static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(),
$this->visibleTenants(), $this->visibleTenants(),
); );
@ -410,7 +410,7 @@ private function queueBaseQuery(): Builder
->with(['tenant', 'ownerUser', 'assigneeUser']) ->with(['tenant', 'ownerUser', 'assigneeUser'])
->withSubjectDisplayName() ->withSubjectDisplayName()
->where('workspace_id', (int) $workspace->getKey()) ->where('workspace_id', (int) $workspace->getKey())
->whereIn('tenant_id', $tenantIds === [] ? [-1] : $tenantIds) ->whereIn('managed_environment_id', $tenantIds === [] ? [-1] : $tenantIds)
->where('assignee_user_id', (int) $user->getKey()) ->where('assignee_user_id', (int) $user->getKey())
->whereIn('status', Finding::openStatusesForQuery()) ->whereIn('status', Finding::openStatusesForQuery())
->orderByRaw( ->orderByRaw(
@ -428,7 +428,7 @@ private function filteredQueueQuery(bool $includeTenantFilter = true): Builder
$filters = $this->currentQueueFiltersState(); $filters = $this->currentQueueFiltersState();
if ($includeTenantFilter && ($tenantId = $this->currentTenantFilterIdFromFilters($filters)) !== null) { if ($includeTenantFilter && ($tenantId = $this->currentTenantFilterIdFromFilters($filters)) !== null) {
$query->where('tenant_id', $tenantId); $query->where('managed_environment_id', $tenantId);
} }
if ($this->filterIsActive($filters, 'overdue')) { if ($this->filterIsActive($filters, 'overdue')) {
@ -454,7 +454,7 @@ private function filteredQueueQuery(bool $includeTenantFilter = true): Builder
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->visibleTenants()) return collect($this->visibleTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => (string) $tenant->name, (string) $tenant->getKey() => (string) $tenant->name,
]) ])
->all(); ->all();
@ -473,8 +473,8 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
@ -482,7 +482,7 @@ private function applyRequestedTenantPrefilter(): void
private function normalizeTenantFilterState(): void private function normalizeTenantFilterState(): void
{ {
$configuredTenantFilter = data_get($this->currentQueueFiltersState(), 'tenant_id.value'); $configuredTenantFilter = data_get($this->currentQueueFiltersState(), 'managed_environment_id.value');
if ($configuredTenantFilter === null || $configuredTenantFilter === '') { if ($configuredTenantFilter === null || $configuredTenantFilter === '') {
return; return;
@ -492,7 +492,7 @@ private function normalizeTenantFilterState(): void
return; return;
} }
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
} }
/** /**
@ -518,7 +518,7 @@ private function currentTenantFilterId(): ?int
*/ */
private function currentTenantFilterIdFromFilters(array $filters): ?int private function currentTenantFilterIdFromFilters(array $filters): ?int
{ {
$tenantFilter = data_get($filters, 'tenant_id.value'); $tenantFilter = data_get($filters, 'managed_environment_id.value');
if (! is_numeric($tenantFilter)) { if (! is_numeric($tenantFilter)) {
return null; return null;
@ -543,7 +543,7 @@ private function filterIsActive(array $filters, string $name): bool
return (bool) data_get($filters, "{$name}.isActive", false); return (bool) data_get($filters, "{$name}.isActive", false);
} }
private function filteredTenant(): ?Tenant private function filteredTenant(): ?ManagedEnvironment
{ {
$tenantId = $this->currentTenantFilterId(); $tenantId = $this->currentTenantFilterId();
@ -560,11 +560,11 @@ private function filteredTenant(): ?Tenant
return null; return null;
} }
private function activeVisibleTenant(): ?Tenant private function activeVisibleTenant(): ?ManagedEnvironment
{ {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -581,13 +581,13 @@ private function tenantPrefilterSource(): string
{ {
$tenant = $this->filteredTenant(); $tenant = $this->filteredTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'none'; return 'none';
} }
$activeTenant = $this->activeVisibleTenant(); $activeTenant = $this->activeVisibleTenant();
if ($activeTenant instanceof Tenant && $activeTenant->is($tenant)) { if ($activeTenant instanceof ManagedEnvironment && $activeTenant->is($tenant)) {
return 'active_tenant_context'; return 'active_tenant_context';
} }
@ -632,7 +632,7 @@ private function findingDetailUrl(Finding $record): string
{ {
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '#'; return '#';
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -58,12 +58,12 @@ class DecisionRegister extends Page implements HasTable
protected string $view = 'filament.pages.governance.decision-register'; protected string $view = 'filament.pages.governance.decision-register';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $visibleDecisionTenants = null; private ?array $visibleDecisionTenants = null;
@ -92,7 +92,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
{ {
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport) return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport)
->satisfy(ActionSurfaceSlot::ListHeader, 'Header controls keep tenant and register-state scope visible without introducing a second mutation surface.') ->satisfy(ActionSurfaceSlot::ListHeader, 'Header controls keep tenant and register-state scope visible without introducing a second mutation surface.')
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ViewAction->value) ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The decision register keeps one dominant row action and avoids a More menu in v1.') ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The decision register keeps one dominant row action and avoids a More menu in v1.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The decision register is read-only and intentionally omits bulk actions.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The decision register is read-only and intentionally omits bulk actions.')
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Filtered empty states stay truthful and provide one path back to the broader register scope.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Filtered empty states stay truthful and provide one path back to the broader register scope.')
@ -166,7 +166,7 @@ public function pageUrl(array $overrides = []): string
return static::getUrl( return static::getUrl(
panel: 'admin', panel: 'admin',
parameters: array_filter([ parameters: array_filter([
'tenant_id' => is_string($resolvedTenant) && $resolvedTenant !== '' ? $resolvedTenant : null, 'managed_environment_id' => is_string($resolvedTenant) && $resolvedTenant !== '' ? $resolvedTenant : null,
'register_state' => is_string($resolvedRegisterState) && $resolvedRegisterState !== 'open' ? $resolvedRegisterState : null, 'register_state' => is_string($resolvedRegisterState) && $resolvedRegisterState !== 'open' ? $resolvedRegisterState : null,
], static fn (mixed $value): bool => $value !== null && $value !== ''), ], static fn (mixed $value): bool => $value !== null && $value !== ''),
); );
@ -205,7 +205,7 @@ public function availableRegisterStates(): array
public function hasTenantPrefilter(): bool public function hasTenantPrefilter(): bool
{ {
return $this->selectedTenant() instanceof Tenant; return $this->selectedTenant() instanceof ManagedEnvironment;
} }
public function isActiveRegisterState(string $registerState): bool public function isActiveRegisterState(string $registerState): bool
@ -274,10 +274,10 @@ public function table(Table $table): Table
->persistFiltersInSession() ->persistFiltersInSession()
->persistSearchInSession() ->persistSearchInSession()
->persistSortInSession() ->persistSortInSession()
->recordUrl(null) ->recordUrl(fn (FindingException $record): ?string => $this->decisionUrl($record))
->columns([ ->columns([
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('status') TextColumn::make('status')
@ -327,12 +327,6 @@ public function table(Table $table): Table
->visible(fn (): bool => $this->registerState === 'recently_closed') ->visible(fn (): bool => $this->registerState === 'recently_closed')
->wrap(), ->wrap(),
]) ])
->actions([
Action::make('open_decision')
->label('Open decision')
->color('gray')
->url(fn (FindingException $record): ?string => $this->decisionUrl($record)),
])
->emptyStateHeading($this->emptyStateHeading()) ->emptyStateHeading($this->emptyStateHeading())
->emptyStateDescription($this->emptyStateDescription()) ->emptyStateDescription($this->emptyStateDescription())
->emptyStateActions($this->emptyStateActions()); ->emptyStateActions($this->emptyStateActions());
@ -363,13 +357,13 @@ private function emptyStateActions(): array
private function tableQuery(): Builder private function tableQuery(): Builder
{ {
$tenantIds = array_values(array_map( $tenantIds = array_values(array_map(
static fn (Tenant $tenant): int => (int) $tenant->getKey(), static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(),
$this->currentScopeTenants(), $this->currentScopeTenants(),
)); ));
$query = FindingException::query() $query = FindingException::query()
->where('workspace_id', (int) $this->workspace()?->getKey()) ->where('workspace_id', (int) $this->workspace()?->getKey())
->whereIn('tenant_id', $tenantIds) ->whereIn('managed_environment_id', $tenantIds)
->with(['tenant', 'owner', 'currentDecision']); ->with(['tenant', 'owner', 'currentDecision']);
if ($this->registerState === 'recently_closed') { if ($this->registerState === 'recently_closed') {
@ -428,7 +422,7 @@ private function ensureRegisterIsVisible(): void
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function authorizedTenants(): array private function authorizedTenants(): array
{ {
@ -447,7 +441,7 @@ private function authorizedTenants(): array
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function visibleDecisionTenants(): array private function visibleDecisionTenants(): array
{ {
@ -468,7 +462,7 @@ private function visibleDecisionTenants(): array
private function applyRequestedTenantPrefilter(): void private function applyRequestedTenantPrefilter(): void
{ {
$requestedTenant = request()->query('tenant_id', request()->query('tenant')); $requestedTenant = request()->query('managed_environment_id', request()->query('tenant'));
if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) { if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) {
return; return;
@ -502,7 +496,7 @@ private function resolveRequestedRegisterState(): string
private static function hasRequestedTenantPrefilter(): bool private static function hasRequestedTenantPrefilter(): bool
{ {
$requestedTenant = request()->query('tenant_id', request()->query('tenant')); $requestedTenant = request()->query('managed_environment_id', request()->query('tenant'));
return is_string($requestedTenant) || is_numeric($requestedTenant); return is_string($requestedTenant) || is_numeric($requestedTenant);
} }
@ -519,21 +513,21 @@ private static function resolveWorkspaceFromRequest(): ?Workspace
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private static function resolveAuthorizedTenantsFor(User $user, Workspace $workspace): array private static function resolveAuthorizedTenantsFor(User $user, Workspace $workspace): array
{ {
return $user->tenants() return $user->tenants()
->where('tenants.workspace_id', (int) $workspace->getKey()) ->where('managed_environments.workspace_id', (int) $workspace->getKey())
->where('tenants.status', 'active') ->where('managed_environments.lifecycle_status', 'active')
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(['tenants.id', 'tenants.name', 'tenants.external_id', 'tenants.workspace_id']) ->get(['managed_environments.id', 'managed_environments.name', 'managed_environments.slug', 'managed_environments.workspace_id'])
->all(); ->all();
} }
/** /**
* @param array<int, Tenant>|null $authorizedTenants * @param array<int, ManagedEnvironment>|null $authorizedTenants
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private static function resolveVisibleDecisionTenantsFor(User $user, Workspace $workspace, ?array $authorizedTenants = null): array private static function resolveVisibleDecisionTenantsFor(User $user, Workspace $workspace, ?array $authorizedTenants = null): array
{ {
@ -546,12 +540,12 @@ private static function resolveVisibleDecisionTenantsFor(User $user, Workspace $
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
$resolver->primeMemberships( $resolver->primeMemberships(
$user, $user,
array_map(static fn (Tenant $tenant): int => (int) $tenant->getKey(), $tenants), array_map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(), $tenants),
); );
return array_values(array_filter( return array_values(array_filter(
$tenants, $tenants,
fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::FINDING_EXCEPTION_VIEW), fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::FINDING_EXCEPTION_VIEW),
)); ));
} }
@ -564,7 +558,7 @@ private function workspace(): ?Workspace
return $this->workspace = static::resolveWorkspaceFromRequest(); return $this->workspace = static::resolveWorkspaceFromRequest();
} }
private function selectedTenant(): ?Tenant private function selectedTenant(): ?ManagedEnvironment
{ {
if (! is_int($this->tenantId)) { if (! is_int($this->tenantId)) {
return null; return null;
@ -580,13 +574,13 @@ private function selectedTenant(): ?Tenant
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function currentScopeTenants(): array private function currentScopeTenants(): array
{ {
$selectedTenant = $this->selectedTenant(); $selectedTenant = $this->selectedTenant();
if ($selectedTenant instanceof Tenant) { if ($selectedTenant instanceof ManagedEnvironment) {
return [$selectedTenant]; return [$selectedTenant];
} }
@ -682,7 +676,7 @@ public function decisionUrl(FindingException $record): ?string
{ {
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Pages\Findings\FindingsIntakeQueue; use App\Filament\Pages\Findings\FindingsIntakeQueue;
use App\Filament\Pages\Findings\MyFindingsInbox; use App\Filament\Pages\Findings\MyFindingsInbox;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -47,17 +47,17 @@ class GovernanceInbox extends Page
protected string $view = 'filament.pages.governance.governance-inbox'; protected string $view = 'filament.pages.governance.governance-inbox';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $visibleFindingTenants = null; private ?array $visibleFindingTenants = null;
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $reviewTenants = null; private ?array $reviewTenants = null;
@ -113,7 +113,7 @@ public function appliedScope(): array
return [ return [
'workspace_label' => $this->workspace()?->name, 'workspace_label' => $this->workspace()?->name,
'tenant_label' => $selectedTenant?->name, 'tenant_label' => $selectedTenant?->name,
'tenant_prefilter_source' => $selectedTenant instanceof Tenant ? 'explicit_filter' : 'none', 'tenant_prefilter_source' => $selectedTenant instanceof ManagedEnvironment ? 'explicit_filter' : 'none',
'family_key' => $this->family, 'family_key' => $this->family,
'family_label' => $this->family !== null 'family_label' => $this->family !== null
? ($availableFamilies->get($this->family)['label'] ?? Str::headline($this->family)) ? ($availableFamilies->get($this->family)['label'] ?? Str::headline($this->family))
@ -162,7 +162,7 @@ public function calmEmptyState(): array
public function hasTenantPrefilter(): bool public function hasTenantPrefilter(): bool
{ {
return $this->selectedTenant() instanceof Tenant; return $this->selectedTenant() instanceof ManagedEnvironment;
} }
public function isActiveFamily(?string $familyKey): bool public function isActiveFamily(?string $familyKey): bool
@ -183,7 +183,7 @@ public function pageUrl(array $overrides = []): string
return static::getUrl( return static::getUrl(
panel: 'admin', panel: 'admin',
parameters: array_filter([ parameters: array_filter([
'tenant_id' => is_string($resolvedTenant) && $resolvedTenant !== '' ? $resolvedTenant : null, 'managed_environment_id' => is_string($resolvedTenant) && $resolvedTenant !== '' ? $resolvedTenant : null,
'family' => is_string($resolvedFamily) && $resolvedFamily !== '' ? $resolvedFamily : null, 'family' => is_string($resolvedFamily) && $resolvedFamily !== '' ? $resolvedFamily : null,
], static fn (mixed $value): bool => $value !== null && $value !== ''), ], static fn (mixed $value): bool => $value !== null && $value !== ''),
); );
@ -290,7 +290,7 @@ private function hasVisibleFindingExceptionsFamily(): bool
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function visibleFindingTenants(): array private function visibleFindingTenants(): array
{ {
@ -308,17 +308,17 @@ private function visibleFindingTenants(): array
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
$resolver->primeMemberships( $resolver->primeMemberships(
$user, $user,
array_map(static fn (Tenant $tenant): int => (int) $tenant->getKey(), $tenants), array_map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(), $tenants),
); );
return $this->visibleFindingTenants = array_values(array_filter( return $this->visibleFindingTenants = array_values(array_filter(
$tenants, $tenants,
fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW), fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW),
)); ));
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function reviewTenants(): array private function reviewTenants(): array
{ {
@ -343,7 +343,7 @@ private function reviewTenants(): array
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function authorizedTenants(): array private function authorizedTenants(): array
{ {
@ -359,16 +359,16 @@ private function authorizedTenants(): array
} }
return $this->authorizedTenants = $user->tenants() return $this->authorizedTenants = $user->tenants()
->where('tenants.workspace_id', (int) $workspace->getKey()) ->where('managed_environments.workspace_id', (int) $workspace->getKey())
->where('tenants.status', 'active') ->where('managed_environments.lifecycle_status', 'active')
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(['tenants.id', 'tenants.name', 'tenants.external_id', 'tenants.workspace_id']) ->get(['managed_environments.id', 'managed_environments.name', 'managed_environments.slug', 'managed_environments.workspace_id'])
->all(); ->all();
} }
private function applyRequestedTenantPrefilter(): void private function applyRequestedTenantPrefilter(): void
{ {
$requestedTenant = request()->query('tenant_id', request()->query('tenant')); $requestedTenant = request()->query('managed_environment_id', request()->query('tenant'));
if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) { if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) {
return; return;
@ -490,7 +490,7 @@ private function unfilteredInboxPayload(): array
); );
} }
private function selectedTenant(): ?Tenant private function selectedTenant(): ?ManagedEnvironment
{ {
if (! is_int($this->tenantId)) { if (! is_int($this->tenantId)) {
return null; return null;

View File

@ -9,7 +9,7 @@
use App\Filament\Resources\InventoryItemResource; use App\Filament\Resources\InventoryItemResource;
use App\Filament\Widgets\Inventory\InventoryKpiHeader; use App\Filament\Widgets\Inventory\InventoryKpiHeader;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -89,7 +89,7 @@ public static function canAccess(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -509,7 +509,7 @@ public function basisRunSummary(): array
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $truth instanceof TenantCoverageTruth || ! $tenant instanceof Tenant) { if (! $truth instanceof TenantCoverageTruth || ! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
@ -551,7 +551,7 @@ protected function coverageTruth(): ?TenantCoverageTruth
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -560,7 +560,7 @@ protected function coverageTruth(): ?TenantCoverageTruth
return $this->cachedCoverageTruth; return $this->cachedCoverageTruth;
} }
private function inventorySyncHistoryUrl(Tenant $tenant): string private function inventorySyncHistoryUrl(ManagedEnvironment $tenant): string
{ {
return OperationRunLinks::index($tenant, operationType: OperationRunType::InventorySync->value); return OperationRunLinks::index($tenant, operationType: OperationRunType::InventorySync->value);
} }

View File

@ -6,7 +6,7 @@
use App\Models\AuditLog as AuditLogModel; use App\Models\AuditLog as AuditLogModel;
use App\Models\SupportAccessGrant; use App\Models\SupportAccessGrant;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
@ -72,7 +72,7 @@ class AuditLog extends Page implements HasTable
'invalidFallback' => 'discard_and_continue', 'invalidFallback' => 'discard_and_continue',
], ],
[ [
'stateKey' => 'tenant_id', 'stateKey' => 'managed_environment_id',
'stateClass' => 'contextual_prefilter', 'stateClass' => 'contextual_prefilter',
'carrier' => 'session', 'carrier' => 'session',
'queryRole' => 'durable_restorable', 'queryRole' => 'durable_restorable',
@ -96,7 +96,7 @@ class AuditLog extends Page implements HasTable
'precedenceOrder' => ['query', 'session', 'default'], 'precedenceOrder' => ['query', 'session', 'default'],
'appliesOnInitialMountOnly' => true, 'appliesOnInitialMountOnly' => true,
'activeStateBecomesAuthoritativeAfterMount' => true, 'activeStateBecomesAuthoritativeAfterMount' => true,
'clearsOnTenantSwitch' => ['tenant_id', 'action', 'actor_label', 'resource_type'], 'clearsOnTenantSwitch' => ['managed_environment_id', 'action', 'actor_label', 'resource_type'],
'invalidRequestedStateFallback' => 'clear_selection_and_continue', 'invalidRequestedStateFallback' => 'clear_selection_and_continue',
], ],
'inspectContract' => [ 'inspectContract' => [
@ -132,7 +132,7 @@ class AuditLog extends Page implements HasTable
protected string $view = 'filament.pages.monitoring.audit-log'; protected string $view = 'filament.pages.monitoring.audit-log';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
@ -281,7 +281,7 @@ public function table(Table $table): Table
->searchable() ->searchable()
->toggleable(), ->toggleable(),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->formatStateUsing(fn (?string $state): string => $state ?: 'Workspace') ->formatStateUsing(fn (?string $state): string => $state ?: 'Workspace')
->toggleable(), ->toggleable(),
TextColumn::make('recorded_at') TextColumn::make('recorded_at')
@ -290,8 +290,8 @@ public function table(Table $table): Table
->sortable(), ->sortable(),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->default(fn (): ?string => $this->defaultTenantFilter()) ->default(fn (): ?string => $this->defaultTenantFilter())
->searchable(), ->searchable(),
@ -335,7 +335,7 @@ public function table(Table $table): Table
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function authorizedTenants(): array public function authorizedTenants(): array
{ {
@ -351,9 +351,9 @@ public function authorizedTenants(): array
} }
$tenants = collect($user->getTenants(Filament::getCurrentOrDefaultPanel())) $tenants = collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->filter(static fn (Tenant $tenant): bool => (int) $tenant->workspace_id === (int) $workspaceId) ->filter(static fn (ManagedEnvironment $tenant): bool => (int) $tenant->workspace_id === (int) $workspaceId)
->filter(static fn (Tenant $tenant): bool => $tenant->isActive()) ->filter(static fn (ManagedEnvironment $tenant): bool => $tenant->isActive())
->keyBy(fn (Tenant $tenant): int => (int) $tenant->getKey()) ->keyBy(fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey())
->all(); ->all();
return $this->authorizedTenants = $tenants; return $this->authorizedTenants = $tenants;
@ -389,7 +389,7 @@ private function auditBaseQuery(): Builder
{ {
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request()); $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
$authorizedTenantIds = array_map( $authorizedTenantIds = array_map(
static fn (Tenant $tenant): int => (int) $tenant->getKey(), static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(),
$this->authorizedTenants(), $this->authorizedTenants(),
); );
@ -397,10 +397,10 @@ private function auditBaseQuery(): Builder
->with(['tenant', 'workspace', 'operationRun']) ->with(['tenant', 'workspace', 'operationRun'])
->forWorkspace((int) $workspaceId) ->forWorkspace((int) $workspaceId)
->where(function (Builder $query) use ($authorizedTenantIds): void { ->where(function (Builder $query) use ($authorizedTenantIds): void {
$query->whereNull('tenant_id'); $query->whereNull('managed_environment_id');
if ($authorizedTenantIds !== []) { if ($authorizedTenantIds !== []) {
$query->orWhereIn('tenant_id', $authorizedTenantIds); $query->orWhereIn('managed_environment_id', $authorizedTenantIds);
} }
}) })
->when($this->supportAccessOnly, function (Builder $query): void { ->when($this->supportAccessOnly, function (Builder $query): void {
@ -552,9 +552,9 @@ private function matchesSelectedAuditFilters(AuditLogModel $record): bool
$filters = $this->currentTableFiltersState(); $filters = $this->currentTableFiltersState();
$tenantFilter = data_get($filters, 'tenant_id.value'); $tenantFilter = data_get($filters, 'managed_environment_id.value');
if (is_numeric($tenantFilter) && (int) $record->tenant_id !== (int) $tenantFilter) { if (is_numeric($tenantFilter) && (int) $record->managed_environment_id !== (int) $tenantFilter) {
return false; return false;
} }
@ -608,7 +608,7 @@ private function matchesSelectedAuditSearch(AuditLogModel $record): bool
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->authorizedTenants()) return collect($this->authorizedTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->getFilamentName(), (string) $tenant->getKey() => $tenant->getFilamentName(),
]) ])
->all(); ->all();
@ -618,7 +618,7 @@ private function defaultTenantFilter(): ?string
{ {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\EvidenceSnapshotResource; use App\Filament\Resources\EvidenceSnapshotResource;
use App\Models\EvidenceSnapshot; use App\Models\EvidenceSnapshot;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantReview; use App\Models\TenantReview;
use App\Models\User; use App\Models\User;
use App\Support\Badges\BadgeCatalog; use App\Support\Badges\BadgeCatalog;
@ -46,7 +46,7 @@ class EvidenceOverview extends Page implements HasTable
'surfaceType' => 'simple_monitoring', 'surfaceType' => 'simple_monitoring',
'stateFields' => [ 'stateFields' => [
[ [
'stateKey' => 'tenant_id', 'stateKey' => 'managed_environment_id',
'stateClass' => 'contextual_prefilter', 'stateClass' => 'contextual_prefilter',
'carrier' => 'query_param', 'carrier' => 'query_param',
'queryRole' => 'durable_restorable', 'queryRole' => 'durable_restorable',
@ -90,7 +90,7 @@ class EvidenceOverview extends Page implements HasTable
'precedenceOrder' => ['query', 'session', 'default'], 'precedenceOrder' => ['query', 'session', 'default'],
'appliesOnInitialMountOnly' => true, 'appliesOnInitialMountOnly' => true,
'activeStateBecomesAuthoritativeAfterMount' => true, 'activeStateBecomesAuthoritativeAfterMount' => true,
'clearsOnTenantSwitch' => ['tenant_id'], 'clearsOnTenantSwitch' => ['managed_environment_id'],
'invalidRequestedStateFallback' => 'discard_and_continue', 'invalidRequestedStateFallback' => 'discard_and_continue',
], ],
'inspectContract' => [ 'inspectContract' => [
@ -101,7 +101,7 @@ class EvidenceOverview extends Page implements HasTable
'shareable' => false, 'shareable' => false,
'invalidSelectionFallback' => 'discard_and_continue', 'invalidSelectionFallback' => 'discard_and_continue',
], ],
'shareableStateKeys' => ['tenant_id', 'search'], 'shareableStateKeys' => ['managed_environment_id', 'search'],
'localOnlyStateKeys' => [], 'localOnlyStateKeys' => [],
]; ];
@ -123,7 +123,7 @@ class EvidenceOverview extends Page implements HasTable
public array $rows = []; public array $rows = [];
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $accessibleTenants = null; private ?array $accessibleTenants = null;
@ -181,14 +181,14 @@ public function table(Table $table): Table
return $this->paginateRows($rows, $page, $recordsPerPage); return $this->paginateRows($rows, $page, $recordsPerPage);
}) })
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->searchable(), ->searchable(),
]) ])
->columns([ ->columns([
TextColumn::make('tenant_name') TextColumn::make('tenant_name')
->label('Tenant') ->label('ManagedEnvironment')
->sortable(), ->sortable(),
TextColumn::make('artifact_truth_label') TextColumn::make('artifact_truth_label')
->label('Outcome') ->label('Outcome')
@ -240,7 +240,7 @@ protected function getHeaderActions(): array
public function clearOverviewFilters(): void public function clearOverviewFilters(): void
{ {
$this->tableFilters = [ $this->tableFilters = [
'tenant_id' => ['value' => null], 'managed_environment_id' => ['value' => null],
]; ];
$this->tableDeferredFilters = $this->tableFilters; $this->tableDeferredFilters = $this->tableFilters;
$this->tableSearch = ''; $this->tableSearch = '';
@ -284,7 +284,7 @@ private function authorizeWorkspaceAccess(): void
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
private function accessibleTenants(): array private function accessibleTenants(): array
{ {
@ -301,10 +301,10 @@ private function accessibleTenants(): array
$workspaceId = $this->workspaceId(); $workspaceId = $this->workspaceId();
return $this->accessibleTenants = $user->tenants() return $this->accessibleTenants = $user->tenants()
->where('tenants.workspace_id', $workspaceId) ->where('managed_environments.workspace_id', $workspaceId)
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get() ->get()
->filter(fn (Tenant $tenant): bool => (int) $tenant->workspace_id === $workspaceId && $user->can('evidence.view', $tenant)) ->filter(fn (ManagedEnvironment $tenant): bool => (int) $tenant->workspace_id === $workspaceId && $user->can('evidence.view', $tenant))
->values() ->values()
->all(); ->all();
} }
@ -315,7 +315,7 @@ private function accessibleTenants(): array
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->accessibleTenants()) return collect($this->accessibleTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->name, (string) $tenant->getKey() => $tenant->name,
]) ])
->all(); ->all();
@ -328,11 +328,11 @@ private function tenantFilterOptions(): array
private function rowsForState(array $filters = [], ?string $search = null): Collection private function rowsForState(array $filters = [], ?string $search = null): Collection
{ {
$rows = $this->baseRows(); $rows = $this->baseRows();
$tenantFilter = $this->normalizeTenantFilter($filters['tenant_id']['value'] ?? data_get($this->tableFilters, 'tenant_id.value')); $tenantFilter = $this->normalizeTenantFilter($filters['managed_environment_id']['value'] ?? data_get($this->tableFilters, 'managed_environment_id.value'));
$normalizedSearch = Str::lower(trim((string) ($search ?? $this->tableSearch))); $normalizedSearch = Str::lower(trim((string) ($search ?? $this->tableSearch)));
if ($tenantFilter !== null) { if ($tenantFilter !== null) {
$rows = $rows->where('tenant_id', $tenantFilter); $rows = $rows->where('managed_environment_id', $tenantFilter);
} }
if ($normalizedSearch === '') { if ($normalizedSearch === '') {
@ -375,7 +375,7 @@ private function latestAccessibleSnapshots(): Collection
} }
$tenantIds = collect($this->accessibleTenants()) $tenantIds = collect($this->accessibleTenants())
->map(static fn (Tenant $tenant): int => (int) $tenant->getKey()) ->map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey())
->all(); ->all();
$query = EvidenceSnapshot::query() $query = EvidenceSnapshot::query()
@ -387,10 +387,10 @@ private function latestAccessibleSnapshots(): Collection
if ($tenantIds === []) { if ($tenantIds === []) {
$query->whereRaw('1 = 0'); $query->whereRaw('1 = 0');
} else { } else {
$query->whereIn('tenant_id', $tenantIds); $query->whereIn('managed_environment_id', $tenantIds);
} }
return $this->cachedSnapshots = $query->get()->unique('tenant_id')->values(); return $this->cachedSnapshots = $query->get()->unique('managed_environment_id')->values();
} }
/** /**
@ -401,13 +401,13 @@ private function currentReviewTenantIds(Collection $snapshots): array
{ {
return TenantReview::query() return TenantReview::query()
->where('workspace_id', $this->workspaceId()) ->where('workspace_id', $this->workspaceId())
->whereIn('tenant_id', $snapshots->pluck('tenant_id')->map(static fn (mixed $tenantId): int => (int) $tenantId)->all()) ->whereIn('managed_environment_id', $snapshots->pluck('managed_environment_id')->map(static fn (mixed $tenantId): int => (int) $tenantId)->all())
->whereIn('status', [ ->whereIn('status', [
TenantReviewStatus::Draft->value, TenantReviewStatus::Draft->value,
TenantReviewStatus::Ready->value, TenantReviewStatus::Ready->value,
TenantReviewStatus::Published->value, TenantReviewStatus::Published->value,
]) ])
->pluck('tenant_id') ->pluck('managed_environment_id')
->mapWithKeys(static fn (mixed $tenantId): array => [(int) $tenantId => true]) ->mapWithKeys(static fn (mixed $tenantId): array => [(int) $tenantId => true])
->all(); ->all();
} }
@ -420,7 +420,7 @@ private function rowForSnapshot(EvidenceSnapshot $snapshot, array $currentReview
{ {
$truth = $this->snapshotTruth($snapshot); $truth = $this->snapshotTruth($snapshot);
$outcome = $this->snapshotOutcome($snapshot); $outcome = $this->snapshotOutcome($snapshot);
$tenantId = (int) $snapshot->tenant_id; $tenantId = (int) $snapshot->managed_environment_id;
$hasCurrentReview = $currentReviewTenantIds[$tenantId] ?? false; $hasCurrentReview = $currentReviewTenantIds[$tenantId] ?? false;
$nextStep = ! $hasCurrentReview && $truth->contentState === 'trusted' && $truth->freshnessState === 'current' $nextStep = ! $hasCurrentReview && $truth->contentState === 'trusted' && $truth->freshnessState === 'current'
? 'Create a current review from this evidence snapshot' ? 'Create a current review from this evidence snapshot'
@ -428,7 +428,7 @@ private function rowForSnapshot(EvidenceSnapshot $snapshot, array $currentReview
return [ return [
'tenant_name' => $snapshot->tenant?->name ?? 'Unknown tenant', 'tenant_name' => $snapshot->tenant?->name ?? 'Unknown tenant',
'tenant_id' => $tenantId, 'managed_environment_id' => $tenantId,
'snapshot_id' => (int) $snapshot->getKey(), 'snapshot_id' => (int) $snapshot->getKey(),
'generated_at' => $snapshot->generated_at?->toDateTimeString(), 'generated_at' => $snapshot->generated_at?->toDateTimeString(),
'artifact_truth_label' => $outcome->primaryLabel, 'artifact_truth_label' => $outcome->primaryLabel,
@ -495,18 +495,18 @@ private function seedTableStateFromQuery(): void
$this->tableSearch = trim((string) request()->query('search', '')); $this->tableSearch = trim((string) request()->query('search', ''));
} }
if (! array_key_exists('tenant_id', $query)) { if (! array_key_exists('managed_environment_id', $query)) {
return; return;
} }
$tenantFilter = $this->normalizeTenantFilter(request()->query('tenant_id')); $tenantFilter = $this->normalizeTenantFilter(request()->query('managed_environment_id'));
if ($tenantFilter === null) { if ($tenantFilter === null) {
return; return;
} }
$this->tableFilters = [ $this->tableFilters = [
'tenant_id' => ['value' => (string) $tenantFilter], 'managed_environment_id' => ['value' => (string) $tenantFilter],
]; ];
$this->tableDeferredFilters = $this->tableFilters; $this->tableDeferredFilters = $this->tableFilters;
} }
@ -519,7 +519,7 @@ private function normalizeTenantFilter(mixed $value): ?int
$requestedTenantId = (int) $value; $requestedTenantId = (int) $value;
$allowedTenantIds = collect($this->accessibleTenants()) $allowedTenantIds = collect($this->accessibleTenants())
->map(static fn (Tenant $tenant): int => (int) $tenant->getKey()) ->map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey())
->all(); ->all();
return in_array($requestedTenantId, $allowedTenantIds, true) return in_array($requestedTenantId, $allowedTenantIds, true)
@ -529,7 +529,7 @@ private function normalizeTenantFilter(mixed $value): ?int
private function hasActiveOverviewFilters(): bool private function hasActiveOverviewFilters(): bool
{ {
return filled(data_get($this->tableFilters, 'tenant_id.value')) return filled(data_get($this->tableFilters, 'managed_environment_id.value'))
|| trim((string) $this->tableSearch) !== ''; || trim((string) $this->tableSearch) !== '';
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
@ -101,7 +101,7 @@ class FindingExceptionsQueue extends Page implements HasTable
'precedenceOrder' => ['query', 'session', 'default'], 'precedenceOrder' => ['query', 'session', 'default'],
'appliesOnInitialMountOnly' => true, 'appliesOnInitialMountOnly' => true,
'activeStateBecomesAuthoritativeAfterMount' => true, 'activeStateBecomesAuthoritativeAfterMount' => true,
'clearsOnTenantSwitch' => ['tenant', 'tenant_id', 'status', 'current_validity_state'], 'clearsOnTenantSwitch' => ['tenant', 'managed_environment_id', 'status', 'current_validity_state'],
'invalidRequestedStateFallback' => 'clear_selection_and_continue', 'invalidRequestedStateFallback' => 'clear_selection_and_continue',
], ],
'inspectContract' => [ 'inspectContract' => [
@ -133,7 +133,7 @@ class FindingExceptionsQueue extends Page implements HasTable
protected string $view = 'filament.pages.monitoring.finding-exceptions-queue'; protected string $view = 'filament.pages.monitoring.finding-exceptions-queue';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
@ -224,7 +224,7 @@ protected function getHeaderActions(): array
->color('gray') ->color('gray')
->visible(fn (): bool => $this->hasActiveQueueFilters()) ->visible(fn (): bool => $this->hasActiveQueueFilters())
->action(function (): void { ->action(function (): void {
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->removeTableFilter('status'); $this->removeTableFilter('status');
$this->removeTableFilter('current_validity_state'); $this->removeTableFilter('current_validity_state');
$this->selectedFindingExceptionId = null; $this->selectedFindingExceptionId = null;
@ -235,11 +235,11 @@ protected function getHeaderActions(): array
->label('View tenant register') ->label('View tenant register')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->filteredTenant() instanceof Tenant) ->visible(fn (): bool => $this->filteredTenant() instanceof ManagedEnvironment)
->url(function (): ?string { ->url(function (): ?string {
$tenant = $this->filteredTenant(); $tenant = $this->filteredTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -383,7 +383,7 @@ public function table(Table $table): Table
->icon(BadgeRenderer::icon(BadgeDomain::FindingRiskGovernanceValidity)) ->icon(BadgeRenderer::icon(BadgeDomain::FindingRiskGovernanceValidity))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::FindingRiskGovernanceValidity)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::FindingRiskGovernanceValidity)),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable(), ->searchable(),
TextColumn::make('finding_summary') TextColumn::make('finding_summary')
->label('Finding') ->label('Finding')
@ -416,8 +416,8 @@ public function table(Table $table): Table
->sortable(), ->sortable(),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->searchable(), ->searchable(),
SelectFilter::make('status') SelectFilter::make('status')
@ -443,7 +443,7 @@ public function table(Table $table): Table
->icon('heroicon-o-x-mark') ->icon('heroicon-o-x-mark')
->color('gray') ->color('gray')
->action(function (): void { ->action(function (): void {
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->removeTableFilter('status'); $this->removeTableFilter('status');
$this->removeTableFilter('current_validity_state'); $this->removeTableFilter('current_validity_state');
$this->selectedFindingExceptionId = null; $this->selectedFindingExceptionId = null;
@ -515,7 +515,7 @@ public function clearSelectedException(): void
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function authorizedTenants(): array public function authorizedTenants(): array
{ {
@ -536,12 +536,12 @@ public function authorizedTenants(): array
} }
$tenants = $user->tenants() $tenants = $user->tenants()
->where('tenants.workspace_id', $workspaceId) ->where('managed_environments.workspace_id', $workspaceId)
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get(); ->get();
return $this->authorizedTenants = $tenants return $this->authorizedTenants = $tenants
->filter(fn (Tenant $tenant): bool => (int) $tenant->workspace_id === $workspaceId) ->filter(fn (ManagedEnvironment $tenant): bool => (int) $tenant->workspace_id === $workspaceId)
->values() ->values()
->all(); ->all();
} }
@ -550,7 +550,7 @@ private function queueBaseQuery(): Builder
{ {
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request()); $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
$tenantIds = array_values(array_map( $tenantIds = array_values(array_map(
static fn (Tenant $tenant): int => (int) $tenant->getKey(), static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey(),
$this->authorizedTenants(), $this->authorizedTenants(),
)); ));
@ -565,7 +565,7 @@ private function queueBaseQuery(): Builder
'evidenceReferences', 'evidenceReferences',
]) ])
->where('workspace_id', (int) $workspaceId) ->where('workspace_id', (int) $workspaceId)
->whereIn('tenant_id', $tenantIds === [] ? [-1] : $tenantIds); ->whereIn('managed_environment_id', $tenantIds === [] ? [-1] : $tenantIds);
} }
/** /**
@ -574,7 +574,7 @@ private function queueBaseQuery(): Builder
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return Collection::make($this->authorizedTenants()) return Collection::make($this->authorizedTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->name, (string) $tenant->getKey() => $tenant->name,
]) ])
->all(); ->all();
@ -593,14 +593,14 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
} }
private function filteredTenant(): ?Tenant private function filteredTenant(): ?ManagedEnvironment
{ {
$tenantId = $this->currentTenantFilterId(); $tenantId = $this->currentTenantFilterId();
@ -741,9 +741,9 @@ private function matchesSelectedFindingExceptionFilters(FindingException $record
{ {
$filters = $this->currentQueueFiltersState(); $filters = $this->currentQueueFiltersState();
$tenantFilter = data_get($filters, 'tenant_id.value'); $tenantFilter = data_get($filters, 'managed_environment_id.value');
if (is_numeric($tenantFilter) && (int) $record->tenant_id !== (int) $tenantFilter) { if (is_numeric($tenantFilter) && (int) $record->managed_environment_id !== (int) $tenantFilter) {
return false; return false;
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\OperationRunResource; use App\Filament\Resources\OperationRunResource;
use App\Filament\Widgets\Operations\OperationsKpiHeader; use App\Filament\Widgets\Operations\OperationsKpiHeader;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Filament\CanonicalAdminTenantFilterState; use App\Support\Filament\CanonicalAdminTenantFilterState;
use App\Support\Navigation\CanonicalNavigationContext; use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
@ -44,7 +44,7 @@ class Operations extends Page implements HasForms, HasTable
'surfaceType' => 'simple_monitoring', 'surfaceType' => 'simple_monitoring',
'stateFields' => [ 'stateFields' => [
[ [
'stateKey' => 'tenant_id', 'stateKey' => 'managed_environment_id',
'stateClass' => 'contextual_prefilter', 'stateClass' => 'contextual_prefilter',
'carrier' => 'query_param', 'carrier' => 'query_param',
'queryRole' => 'durable_restorable', 'queryRole' => 'durable_restorable',
@ -98,7 +98,7 @@ class Operations extends Page implements HasForms, HasTable
'precedenceOrder' => ['query', 'session', 'default'], 'precedenceOrder' => ['query', 'session', 'default'],
'appliesOnInitialMountOnly' => true, 'appliesOnInitialMountOnly' => true,
'activeStateBecomesAuthoritativeAfterMount' => true, 'activeStateBecomesAuthoritativeAfterMount' => true,
'clearsOnTenantSwitch' => ['tenant_id', 'type', 'initiator_name'], 'clearsOnTenantSwitch' => ['managed_environment_id', 'type', 'initiator_name'],
'invalidRequestedStateFallback' => 'discard_and_continue', 'invalidRequestedStateFallback' => 'discard_and_continue',
], ],
'inspectContract' => [ 'inspectContract' => [
@ -109,7 +109,7 @@ class Operations extends Page implements HasForms, HasTable
'shareable' => false, 'shareable' => false,
'invalidSelectionFallback' => 'discard_and_continue', 'invalidSelectionFallback' => 'discard_and_continue',
], ],
'shareableStateKeys' => ['tenant_id', 'tenant_scope', 'problemClass', 'activeTab'], 'shareableStateKeys' => ['managed_environment_id', 'tenant_scope', 'problemClass', 'activeTab'],
'localOnlyStateKeys' => [], 'localOnlyStateKeys' => [],
]; ];
@ -199,7 +199,7 @@ protected function getHeaderActions(): array
->icon('heroicon-o-arrow-left') ->icon('heroicon-o-arrow-left')
->color('gray') ->color('gray')
->url($navigationContext->backLinkUrl); ->url($navigationContext->backLinkUrl);
} elseif ($activeTenant instanceof Tenant) { } elseif ($activeTenant instanceof ManagedEnvironment) {
$actions[] = Action::make('operate_hub_back_to_tenant_operations') $actions[] = Action::make('operate_hub_back_to_tenant_operations')
->label('Back to '.$activeTenant->name) ->label('Back to '.$activeTenant->name)
->icon('heroicon-o-arrow-left') ->icon('heroicon-o-arrow-left')
@ -207,7 +207,7 @@ protected function getHeaderActions(): array
->url(\App\Filament\Pages\TenantDashboard::getUrl(panel: 'tenant', tenant: $activeTenant)); ->url(\App\Filament\Pages\TenantDashboard::getUrl(panel: 'tenant', tenant: $activeTenant));
} }
if ($activeTenant instanceof Tenant) { if ($activeTenant instanceof ManagedEnvironment) {
$actions[] = Action::make('operate_hub_show_all_tenants') $actions[] = Action::make('operate_hub_show_all_tenants')
->label('Show all tenants') ->label('Show all tenants')
->color('gray') ->color('gray')
@ -216,7 +216,7 @@ protected function getHeaderActions(): array
app(WorkspaceContext::class)->clearLastTenantId(request()); app(WorkspaceContext::class)->clearLastTenantId(request());
$this->removeTableFilter('tenant_id'); $this->removeTableFilter('managed_environment_id');
$this->redirect('/admin/operations'); $this->redirect('/admin/operations');
}); });
@ -248,20 +248,20 @@ public function landingHierarchySummary(): array
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) { if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
$returnLabel = $navigationContext->backLinkLabel; $returnLabel = $navigationContext->backLinkLabel;
$returnBody = 'Return to the originating monitoring surface without competing with the current tab, filters, or row inspection flow.'; $returnBody = 'Return to the originating monitoring surface without competing with the current tab, filters, or row inspection flow.';
} elseif ($activeTenant instanceof Tenant) { } elseif ($activeTenant instanceof ManagedEnvironment) {
$returnLabel = 'Back to '.$activeTenant->name; $returnLabel = 'Back to '.$activeTenant->name;
$returnBody = 'Return to the tenant dashboard when you need tenant-specific context outside this workspace monitoring landing.'; $returnBody = 'Return to the tenant dashboard when you need tenant-specific context outside this workspace monitoring landing.';
} }
return [ return [
'scope_label' => $operateHubShell->scopeLabel(request()), 'scope_label' => $operateHubShell->scopeLabel(request()),
'scope_body' => $activeTenant instanceof Tenant 'scope_body' => $activeTenant instanceof ManagedEnvironment
? 'The landing is currently narrowed to one tenant inside the active workspace.' ? 'The landing is currently narrowed to one tenant inside the active workspace.'
: 'The landing is currently showing workspace-wide monitoring across all entitled tenants.', : 'The landing is currently showing workspace-wide monitoring across all entitled tenants.',
'return_label' => $returnLabel, 'return_label' => $returnLabel,
'return_body' => $returnBody, 'return_body' => $returnBody,
'scope_reset_label' => $activeTenant instanceof Tenant ? 'Show all tenants' : null, 'scope_reset_label' => $activeTenant instanceof ManagedEnvironment ? 'Show all tenants' : null,
'scope_reset_body' => $activeTenant instanceof Tenant 'scope_reset_body' => $activeTenant instanceof ManagedEnvironment
? 'Reset the landing back to workspace-wide monitoring when tenant-specific context is no longer needed.' ? 'Reset the landing back to workspace-wide monitoring when tenant-specific context is no longer needed.'
: null, : null,
'inspect_body' => 'Open a run from the table to enter the canonical monitoring detail viewer.', 'inspect_body' => 'Open a run from the table to enter the canonical monitoring detail viewer.',
@ -312,7 +312,7 @@ public function table(Table $table): Table
) )
->when( ->when(
$tenantFilter !== null, $tenantFilter !== null,
fn (Builder $query): Builder => $query->where('tenant_id', $tenantFilter), fn (Builder $query): Builder => $query->where('managed_environment_id', $tenantFilter),
); );
return $this->applyActiveTab($query); return $this->applyActiveTab($query);
@ -393,19 +393,19 @@ private function scopedSummaryQuery(): ?Builder
->where('workspace_id', (int) $workspaceId) ->where('workspace_id', (int) $workspaceId)
->when( ->when(
$tenantFilter !== null, $tenantFilter !== null,
fn (Builder $query): Builder => $query->where('tenant_id', $tenantFilter), fn (Builder $query): Builder => $query->where('managed_environment_id', $tenantFilter),
); );
} }
private function applyRequestedDashboardPrefilter(): void private function applyRequestedDashboardPrefilter(): void
{ {
if (! $this->shouldForceWorkspaceWideTenantScope()) { if (! $this->shouldForceWorkspaceWideTenantScope()) {
$requestedTenantId = $this->normalizeEntitledTenantFilter(request()->query('tenant_id')); $requestedTenantId = $this->normalizeEntitledTenantFilter(request()->query('managed_environment_id'));
if ($requestedTenantId !== null) { if ($requestedTenantId !== null) {
$tenantId = (string) $requestedTenantId; $tenantId = (string) $requestedTenantId;
$this->tableFilters['tenant_id']['value'] = $tenantId; $this->tableFilters['managed_environment_id']['value'] = $tenantId;
$this->tableDeferredFilters['tenant_id']['value'] = $tenantId; $this->tableDeferredFilters['managed_environment_id']['value'] = $tenantId;
} }
} }
@ -435,7 +435,7 @@ private function operationsUrl(array $overrides = []): string
$this->navigationContext()?->toQuery() ?? [], $this->navigationContext()?->toQuery() ?? [],
[ [
'tenant_scope' => $this->shouldForceWorkspaceWideTenantScope() ? 'all' : null, 'tenant_scope' => $this->shouldForceWorkspaceWideTenantScope() ? 'all' : null,
'tenant_id' => $this->shouldForceWorkspaceWideTenantScope() ? null : $this->currentTenantFilterId(), 'managed_environment_id' => $this->shouldForceWorkspaceWideTenantScope() ? null : $this->currentTenantFilterId(),
'activeTab' => $this->activeTab !== 'all' ? $this->activeTab : null, 'activeTab' => $this->activeTab !== 'all' ? $this->activeTab : null,
'problemClass' => in_array($this->activeTab, self::problemClassTabs(), true) ? $this->activeTab : null, 'problemClass' => in_array($this->activeTab, self::problemClassTabs(), true) ? $this->activeTab : null,
], ],
@ -485,9 +485,9 @@ private function authorizedTenantIds(): array
} }
return collect($user->getTenants(Filament::getCurrentOrDefaultPanel())) return collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->filter(static fn (Tenant $tenant): bool => (int) $tenant->workspace_id === $workspaceId) ->filter(static fn (ManagedEnvironment $tenant): bool => (int) $tenant->workspace_id === $workspaceId)
->filter(static fn (Tenant $tenant): bool => $tenant->isActive()) ->filter(static fn (ManagedEnvironment $tenant): bool => $tenant->isActive())
->map(static fn (Tenant $tenant): int => (int) $tenant->getKey()) ->map(static fn (ManagedEnvironment $tenant): int => (int) $tenant->getKey())
->values() ->values()
->all(); ->all();
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\OperationRunResource; use App\Filament\Resources\OperationRunResource;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\SupportRequest; use App\Models\SupportRequest;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -108,7 +108,7 @@ protected function getHeaderActions(): array
$operateHubShell = app(OperateHubShell::class); $operateHubShell = app(OperateHubShell::class);
$navigationContext = $this->navigationContext(); $navigationContext = $this->navigationContext();
$activeTenant = $operateHubShell->activeEntitledTenant(request()); $activeTenant = $operateHubShell->activeEntitledTenant(request());
$runTenantId = isset($this->run) ? (int) ($this->run->tenant_id ?? 0) : 0; $runTenantId = isset($this->run) ? (int) ($this->run->managed_environment_id ?? 0) : 0;
$actions = [ $actions = [
Action::make('operate_hub_scope_run_detail') Action::make('operate_hub_scope_run_detail')
@ -122,7 +122,7 @@ protected function getHeaderActions(): array
->label($navigationContext->backLinkLabel) ->label($navigationContext->backLinkLabel)
->color('gray') ->color('gray')
->url($navigationContext->backLinkUrl); ->url($navigationContext->backLinkUrl);
} elseif ($activeTenant instanceof Tenant && (int) $activeTenant->getKey() === $runTenantId) { } elseif ($activeTenant instanceof ManagedEnvironment && (int) $activeTenant->getKey() === $runTenantId) {
$actions[] = Action::make('operate_hub_back_to_tenant_run_detail') $actions[] = Action::make('operate_hub_back_to_tenant_run_detail')
->label('← Back to '.$activeTenant->name) ->label('← Back to '.$activeTenant->name)
->color('gray') ->color('gray')
@ -134,7 +134,7 @@ protected function getHeaderActions(): array
->url(fn (): string => OperationRunLinks::index()); ->url(fn (): string => OperationRunLinks::index());
} }
if ($activeTenant instanceof Tenant) { if ($activeTenant instanceof ManagedEnvironment) {
$actions[] = Action::make('operate_hub_show_all_operations') $actions[] = Action::make('operate_hub_show_all_operations')
->label('Show all operations') ->label('Show all operations')
->color('gray') ->color('gray')
@ -201,7 +201,7 @@ public function monitoringDetailSummary(): array
$operateHubShell = app(OperateHubShell::class); $operateHubShell = app(OperateHubShell::class);
$navigationContext = $this->navigationContext(); $navigationContext = $this->navigationContext();
$activeTenant = $operateHubShell->activeEntitledTenant(request()); $activeTenant = $operateHubShell->activeEntitledTenant(request());
$runTenantId = isset($this->run) ? (int) ($this->run->tenant_id ?? 0) : 0; $runTenantId = isset($this->run) ? (int) ($this->run->managed_environment_id ?? 0) : 0;
$navigationLabel = 'Back to Operations'; $navigationLabel = 'Back to Operations';
$navigationBody = 'Return to the operations landing when this review is complete.'; $navigationBody = 'Return to the operations landing when this review is complete.';
@ -209,7 +209,7 @@ public function monitoringDetailSummary(): array
if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) { if ($navigationContext?->backLinkLabel !== null && $navigationContext->backLinkUrl !== null) {
$navigationLabel = $navigationContext->backLinkLabel; $navigationLabel = $navigationContext->backLinkLabel;
$navigationBody = 'Return to the originating surface while keeping refresh and follow-up work separate from navigation.'; $navigationBody = 'Return to the originating surface while keeping refresh and follow-up work separate from navigation.';
} elseif ($activeTenant instanceof Tenant && (int) $activeTenant->getKey() === $runTenantId) { } elseif ($activeTenant instanceof ManagedEnvironment && (int) $activeTenant->getKey() === $runTenantId) {
$navigationLabel = 'Back to '.$activeTenant->name; $navigationLabel = 'Back to '.$activeTenant->name;
$navigationBody = 'Return to the active tenant dashboard, then widen back to the workspace view only when you need broader monitoring context.'; $navigationBody = 'Return to the active tenant dashboard, then widen back to the workspace view only when you need broader monitoring context.';
} }
@ -391,7 +391,7 @@ private function auditOperationSupportDiagnosticsOpen(): void
); );
} }
private function supportDiagnosticsTenant(): ?Tenant private function supportDiagnosticsTenant(): ?ManagedEnvironment
{ {
if (! isset($this->run)) { if (! isset($this->run)) {
return null; return null;
@ -399,7 +399,7 @@ private function supportDiagnosticsTenant(): ?Tenant
$tenant = $this->run->tenant; $tenant = $this->run->tenant;
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return $tenant; return $tenant;
} }
@ -417,12 +417,12 @@ private function resolveViewerActor(): User
return $user; return $user;
} }
private function resolveRunTenantForCapability(string $capability): Tenant private function resolveRunTenantForCapability(string $capability): ManagedEnvironment
{ {
$tenant = $this->supportDiagnosticsTenant(); $tenant = $this->supportDiagnosticsTenant();
$user = $this->resolveViewerActor(); $user = $this->resolveViewerActor();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -444,7 +444,7 @@ private function operationSupportRequestAttachmentSummary(): string
$tenant = $this->supportDiagnosticsTenant(); $tenant = $this->supportDiagnosticsTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return 'Only canonical redacted run context will be attached.'; return 'Only canonical redacted run context will be attached.';
} }
@ -554,7 +554,7 @@ private function supportRequestNotificationBody(SupportRequest $supportRequest):
/** /**
* @param array<string, mixed> $bundle * @param array<string, mixed> $bundle
*/ */
private function recordSupportDiagnosticsOpened(Tenant $tenant, array $bundle, User $user): void private function recordSupportDiagnosticsOpened(ManagedEnvironment $tenant, array $bundle, User $user): void
{ {
if (! isset($this->run)) { if (! isset($this->run)) {
return; return;
@ -729,11 +729,11 @@ public function canonicalContextBanner(): ?array
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
$runTenant = $this->run->tenant; $runTenant = $this->run->tenant;
if (! $runTenant instanceof Tenant) { if (! $runTenant instanceof ManagedEnvironment) {
return [ return [
'tone' => 'slate', 'tone' => 'slate',
'title' => 'Workspace-level operation', 'title' => 'Workspace-level operation',
'body' => $activeTenant instanceof Tenant 'body' => $activeTenant instanceof ManagedEnvironment
? 'This canonical workspace view is not tied to the current tenant context ('.$activeTenant->name.').' ? 'This canonical workspace view is not tied to the current tenant context ('.$activeTenant->name.').'
: 'This canonical workspace view is not tied to any tenant.', : 'This canonical workspace view is not tied to any tenant.',
]; ];
@ -743,7 +743,7 @@ public function canonicalContextBanner(): ?array
$tone = 'sky'; $tone = 'sky';
$title = null; $title = null;
if ($activeTenant instanceof Tenant && ! $activeTenant->is($runTenant)) { if ($activeTenant instanceof ManagedEnvironment && ! $activeTenant->is($runTenant)) {
$title = 'Current tenant context differs from this operation'; $title = 'Current tenant context differs from this operation';
array_unshift($messages, 'Current tenant context: '.$activeTenant->name.'.'); array_unshift($messages, 'Current tenant context: '.$activeTenant->name.'.');
$messages[] = 'This canonical workspace view remains valid without switching tenant context.'; $messages[] = 'This canonical workspace view remains valid without switching tenant context.';
@ -759,7 +759,7 @@ public function canonicalContextBanner(): ?array
if ($referencedTenant->contextNote !== null) { if ($referencedTenant->contextNote !== null) {
$messages[] = $referencedTenant->contextNote; $messages[] = $referencedTenant->contextNote;
} }
} elseif (! $activeTenant instanceof Tenant) { } elseif (! $activeTenant instanceof ManagedEnvironment) {
$title ??= 'Canonical workspace view'; $title ??= 'Canonical workspace view';
$messages[] = 'No tenant context is currently selected.'; $messages[] = 'No tenant context is currently selected.';
} }
@ -925,7 +925,7 @@ private function canResumeCapture(): bool
&& $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE); && $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE);
} }
private function relatedLinksTenant(): ?Tenant private function relatedLinksTenant(): ?ManagedEnvironment
{ {
if (! isset($this->run)) { if (! isset($this->run)) {
return null; return null;
@ -934,7 +934,7 @@ private function relatedLinksTenant(): ?Tenant
$user = auth()->user(); $user = auth()->user();
$tenant = $this->run->tenant; $tenant = $this->run->tenant;
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return null; return null;
} }

View File

@ -8,7 +8,7 @@
use App\Models\EvidenceSnapshot; use App\Models\EvidenceSnapshot;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\ReviewPack; use App\Models\ReviewPack;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantReview; use App\Models\TenantReview;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
@ -74,6 +74,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::RunLog, ActionSurfaceType::ReadOnlyRegistryReport) return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::RunLog, ActionSurfaceType::ReadOnlyRegistryReport)
->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions provide a single Clear filters action for the customer review workspace.') ->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions provide a single Clear filters action for the customer review workspace.')
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::PrimaryLinkColumn->value) ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::PrimaryLinkColumn->value)
->withPrimaryLinkColumnReason('Only the dedicated review-open column should navigate away; the rest of the row stays comparative workspace context.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The customer review workspace remains scan-first and does not expose bulk actions.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The customer review workspace remains scan-first and does not expose bulk actions.')
->satisfy(ActionSurfaceSlot::ListEmptyState, 'The empty state keeps exactly one Clear filters CTA when filters are active.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'The empty state keeps exactly one Clear filters CTA when filters are active.')
->exempt(ActionSurfaceSlot::DetailHeader, 'The dedicated open link column opens the latest published review detail instead of an inline canonical detail panel.'); ->exempt(ActionSurfaceSlot::DetailHeader, 'The dedicated open link column opens the latest published review detail instead of an inline canonical detail panel.');
@ -94,7 +95,7 @@ public function getTitle(): string
return __('localization.review.customer_review_workspace'); return __('localization.review.customer_review_workspace');
} }
public static function tenantPrefilterUrl(Tenant $tenant): string public static function tenantPrefilterUrl(ManagedEnvironment $tenant): string
{ {
$tenantIdentifier = filled($tenant->external_id) $tenantIdentifier = filled($tenant->external_id)
? (string) $tenant->external_id ? (string) $tenant->external_id
@ -106,7 +107,7 @@ public static function tenantPrefilterUrl(Tenant $tenant): string
} }
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
@ -161,36 +162,36 @@ public function table(Table $table): Table
->width('9rem') ->width('9rem')
->extraHeaderAttributes(['class' => 'whitespace-normal']) ->extraHeaderAttributes(['class' => 'whitespace-normal'])
->badge() ->badge()
->getStateUsing(fn (Tenant $record): string => $this->governancePackageAvailabilityLabel($record)) ->getStateUsing(fn (ManagedEnvironment $record): string => $this->governancePackageAvailabilityLabel($record))
->color(fn (Tenant $record): string => $this->governancePackageAvailabilityColor($record)) ->color(fn (ManagedEnvironment $record): string => $this->governancePackageAvailabilityColor($record))
->tooltip(fn (Tenant $record): string => $this->governancePackageAvailability($record)['description']), ->tooltip(fn (ManagedEnvironment $record): string => $this->governancePackageAvailability($record)['description']),
TextColumn::make('latest_review') TextColumn::make('latest_review')
->label(__('localization.review.status')) ->label(__('localization.review.status'))
->width('9rem') ->width('9rem')
->badge() ->badge()
->getStateUsing(fn (Tenant $record): string => $this->latestReviewStateLabel($record)) ->getStateUsing(fn (ManagedEnvironment $record): string => $this->latestReviewStateLabel($record))
->color(fn (Tenant $record): string => $this->latestReviewStateColor($record)), ->color(fn (ManagedEnvironment $record): string => $this->latestReviewStateColor($record)),
TextColumn::make('evidence_proof_state') TextColumn::make('evidence_proof_state')
->label(__('localization.review.evidence_status')) ->label(__('localization.review.evidence_status'))
->width('8rem') ->width('8rem')
->badge() ->badge()
->getStateUsing(fn (Tenant $record): string => $this->evidenceStatusLabel($record)) ->getStateUsing(fn (ManagedEnvironment $record): string => $this->evidenceStatusLabel($record))
->color(fn (Tenant $record): string => $this->evidenceStatusColor($record)), ->color(fn (ManagedEnvironment $record): string => $this->evidenceStatusColor($record)),
TextColumn::make('recommended_next_action') TextColumn::make('recommended_next_action')
->label(__('localization.review.next_step')) ->label(__('localization.review.next_step'))
->width('10rem') ->width('10rem')
->extraHeaderAttributes(['class' => 'whitespace-normal']) ->extraHeaderAttributes(['class' => 'whitespace-normal'])
->getStateUsing(fn (Tenant $record): string => $this->controlRecommendedNextAction($record)) ->getStateUsing(fn (ManagedEnvironment $record): string => $this->controlRecommendedNextAction($record))
->wrap(), ->wrap(),
TextColumn::make('open_review') TextColumn::make('open_review')
->label(__('localization.review.open')) ->label(__('localization.review.open'))
->width('8rem') ->width('8rem')
->getStateUsing(fn (): string => __('localization.review.open_review')) ->getStateUsing(fn (): string => __('localization.review.open_review'))
->url(fn (Tenant $record): ?string => $this->latestReviewUrl($record)) ->url(fn (ManagedEnvironment $record): ?string => $this->latestReviewUrl($record))
->color('primary'), ->color('primary'),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label(__('localization.review.tenant')) ->label(__('localization.review.tenant'))
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->default(fn (): ?string => $this->defaultTenantFilter()) ->default(fn (): ?string => $this->defaultTenantFilter())
@ -220,7 +221,7 @@ public function table(Table $table): Table
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function authorizedTenants(): array public function authorizedTenants(): array
{ {
@ -296,7 +297,7 @@ private function workspaceQuery(): Builder
$workspace = $this->workspace(); $workspace = $this->workspace();
if (! $user instanceof User || ! $workspace instanceof Workspace) { if (! $user instanceof User || ! $workspace instanceof Workspace) {
return Tenant::query()->whereRaw('1 = 0'); return ManagedEnvironment::query()->whereRaw('1 = 0');
} }
return app(TenantReviewRegisterService::class)->customerWorkspaceTenantQuery($user, $workspace); return app(TenantReviewRegisterService::class)->customerWorkspaceTenantQuery($user, $workspace);
@ -308,7 +309,7 @@ private function workspaceQuery(): Builder
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->authorizedTenants()) return collect($this->authorizedTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->name, (string) $tenant->getKey() => $tenant->name,
]) ])
->all(); ->all();
@ -325,7 +326,7 @@ private function defaultTenantFilter(): ?string
private function applyRequestedTenantPrefilter(): void private function applyRequestedTenantPrefilter(): void
{ {
$requestedTenant = request()->query('tenant', request()->query('tenant_id')); $requestedTenant = request()->query('tenant', request()->query('managed_environment_id'));
if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) { if (! is_string($requestedTenant) && ! is_numeric($requestedTenant)) {
return; return;
@ -336,8 +337,8 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
@ -358,10 +359,10 @@ private function clearWorkspaceFilters(): void
private function currentTenantFilterId(): ?int private function currentTenantFilterId(): ?int
{ {
$tenantFilter = data_get($this->tableFilters, 'tenant_id.value'); $tenantFilter = data_get($this->tableFilters, 'managed_environment_id.value');
if (! is_numeric($tenantFilter)) { if (! is_numeric($tenantFilter)) {
$tenantFilter = data_get(session()->get($this->getTableFiltersSessionKey(), []), 'tenant_id.value'); $tenantFilter = data_get(session()->get($this->getTableFiltersSessionKey(), []), 'managed_environment_id.value');
} }
return is_numeric($tenantFilter) ? (int) $tenantFilter : null; return is_numeric($tenantFilter) ? (int) $tenantFilter : null;
@ -376,14 +377,14 @@ private function workspace(): ?Workspace
: null; : null;
} }
private function latestPublishedReview(Tenant $tenant): ?TenantReview private function latestPublishedReview(ManagedEnvironment $tenant): ?TenantReview
{ {
$review = $tenant->tenantReviews->first(); $review = $tenant->tenantReviews->first();
return $review instanceof TenantReview ? $review : null; return $review instanceof TenantReview ? $review : null;
} }
private function latestReviewUrl(Tenant $tenant): ?string private function latestReviewUrl(ManagedEnvironment $tenant): ?string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -406,12 +407,12 @@ private function latestReviewUrl(Tenant $tenant): ?string
return $this->appendQuery(TenantReviewResource::tenantScopedUrl('view', ['record' => $review], $tenant, 'tenant'), $query); return $this->appendQuery(TenantReviewResource::tenantScopedUrl('view', ['record' => $review], $tenant, 'tenant'), $query);
} }
private function latestPublishedAt(Tenant $tenant): ?\Illuminate\Support\Carbon private function latestPublishedAt(ManagedEnvironment $tenant): ?\Illuminate\Support\Carbon
{ {
return $this->latestPublishedReview($tenant)?->published_at; return $this->latestPublishedReview($tenant)?->published_at;
} }
private function reviewTruth(Tenant $tenant): ?ArtifactTruthEnvelope private function reviewTruth(ManagedEnvironment $tenant): ?ArtifactTruthEnvelope
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -420,7 +421,7 @@ private function reviewTruth(Tenant $tenant): ?ArtifactTruthEnvelope
: null; : null;
} }
private function reviewOutcome(Tenant $tenant): ?CompressedGovernanceOutcome private function reviewOutcome(ManagedEnvironment $tenant): ?CompressedGovernanceOutcome
{ {
$presenter = app(ArtifactTruthPresenter::class); $presenter = app(ArtifactTruthPresenter::class);
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -434,7 +435,7 @@ private function reviewOutcome(Tenant $tenant): ?CompressedGovernanceOutcome
?? $presenter->compressedOutcomeFromEnvelope($truth, SurfaceCompressionContext::reviewRegister()); ?? $presenter->compressedOutcomeFromEnvelope($truth, SurfaceCompressionContext::reviewRegister());
} }
private function latestReviewStateLabel(Tenant $tenant): string private function latestReviewStateLabel(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -447,7 +448,7 @@ private function latestReviewStateLabel(Tenant $tenant): string
: __('localization.review.ready_for_release'); : __('localization.review.ready_for_release');
} }
private function latestReviewStateColor(Tenant $tenant): string private function latestReviewStateColor(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -466,17 +467,17 @@ private function latestReviewStateColor(Tenant $tenant): string
: 'warning'; : 'warning';
} }
private function latestReviewStateIcon(Tenant $tenant): ?string private function latestReviewStateIcon(ManagedEnvironment $tenant): ?string
{ {
return $this->reviewOutcome($tenant)?->primaryBadge->icon; return $this->reviewOutcome($tenant)?->primaryBadge->icon;
} }
private function latestReviewStateIconColor(Tenant $tenant): ?string private function latestReviewStateIconColor(ManagedEnvironment $tenant): ?string
{ {
return $this->reviewOutcome($tenant)?->primaryBadge->iconColor; return $this->reviewOutcome($tenant)?->primaryBadge->iconColor;
} }
private function reviewOutcomeDescription(Tenant $tenant): ?string private function reviewOutcomeDescription(ManagedEnvironment $tenant): ?string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -501,7 +502,7 @@ private function reviewOutcomeDescription(Tenant $tenant): ?string
return trim($primaryReason.' '.__('localization.review.terminal_outcomes').': '.$findingOutcomeSummary.'.'); return trim($primaryReason.' '.__('localization.review.terminal_outcomes').': '.$findingOutcomeSummary.'.');
} }
private function controlReadinessLabel(Tenant $tenant): string private function controlReadinessLabel(ManagedEnvironment $tenant): string
{ {
$control = $this->primaryControlSummary($tenant); $control = $this->primaryControlSummary($tenant);
@ -519,7 +520,7 @@ private function controlReadinessLabel(Tenant $tenant): string
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
private function governancePackageSummary(Tenant $tenant): array private function governancePackageSummary(ManagedEnvironment $tenant): array
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -536,7 +537,7 @@ private function governancePackageSummary(Tenant $tenant): array
/** /**
* @return array{state:string,label:string,description:string} * @return array{state:string,label:string,description:string}
*/ */
private function governancePackageAvailability(Tenant $tenant): array private function governancePackageAvailability(ManagedEnvironment $tenant): array
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -603,7 +604,7 @@ private function governancePackageAvailability(Tenant $tenant): array
]; ];
} }
private function governancePackageAvailabilityLabel(Tenant $tenant): string private function governancePackageAvailabilityLabel(ManagedEnvironment $tenant): string
{ {
return match ($this->governancePackageAvailability($tenant)['state']) { return match ($this->governancePackageAvailability($tenant)['state']) {
'available' => __('localization.review.available'), 'available' => __('localization.review.available'),
@ -614,7 +615,7 @@ private function governancePackageAvailabilityLabel(Tenant $tenant): string
}; };
} }
private function governancePackageAvailabilityColor(Tenant $tenant): string private function governancePackageAvailabilityColor(ManagedEnvironment $tenant): string
{ {
return match ($this->governancePackageAvailability($tenant)['state']) { return match ($this->governancePackageAvailability($tenant)['state']) {
'available' => 'success', 'available' => 'success',
@ -624,7 +625,7 @@ private function governancePackageAvailabilityColor(Tenant $tenant): string
}; };
} }
private function governancePackageTeaser(Tenant $tenant): string private function governancePackageTeaser(ManagedEnvironment $tenant): string
{ {
$package = $this->governancePackageSummary($tenant); $package = $this->governancePackageSummary($tenant);
@ -637,7 +638,7 @@ private function governancePackageTeaser(Tenant $tenant): string
return $this->governancePackageAvailability($tenant)['description']; return $this->governancePackageAvailability($tenant)['description'];
} }
private function controlReadinessColor(Tenant $tenant): string private function controlReadinessColor(ManagedEnvironment $tenant): string
{ {
return match ((string) ($this->primaryControlSummary($tenant)['readiness_bucket'] ?? 'unmapped')) { return match ((string) ($this->primaryControlSummary($tenant)['readiness_bucket'] ?? 'unmapped')) {
'follow_up_required' => 'warning', 'follow_up_required' => 'warning',
@ -647,7 +648,7 @@ private function controlReadinessColor(Tenant $tenant): string
}; };
} }
private function controlReadinessDescription(Tenant $tenant): string private function controlReadinessDescription(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -684,7 +685,7 @@ private function controlReadinessDescription(Tenant $tenant): string
return trim($summary.($limitations !== null ? ' '.$limitations : '')); return trim($summary.($limitations !== null ? ' '.$limitations : ''));
} }
private function controlEvidenceBasisSummary(Tenant $tenant): string private function controlEvidenceBasisSummary(ManagedEnvironment $tenant): string
{ {
$control = $this->primaryControlSummary($tenant); $control = $this->primaryControlSummary($tenant);
@ -699,7 +700,7 @@ private function controlEvidenceBasisSummary(Tenant $tenant): string
: __('localization.review.control_evidence_unavailable'); : __('localization.review.control_evidence_unavailable');
} }
private function controlRecommendedNextAction(Tenant $tenant): string private function controlRecommendedNextAction(ManagedEnvironment $tenant): string
{ {
if ($this->primaryControlSummary($tenant) === null) { if ($this->primaryControlSummary($tenant) === null) {
return __('localization.review.workspace_next_step_control_mapping'); return __('localization.review.workspace_next_step_control_mapping');
@ -715,7 +716,7 @@ private function controlRecommendedNextAction(Tenant $tenant): string
}; };
} }
private function workspaceReviewNeedsAttention(Tenant $tenant): bool private function workspaceReviewNeedsAttention(ManagedEnvironment $tenant): bool
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -734,7 +735,7 @@ private function workspaceReviewNeedsAttention(Tenant $tenant): bool
return $this->governancePackageAvailability($tenant)['state'] !== 'available'; return $this->governancePackageAvailability($tenant)['state'] !== 'available';
} }
private function evidenceStatusState(Tenant $tenant): string private function evidenceStatusState(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -779,7 +780,7 @@ private function evidenceStatusColorForState(string $state): string
}; };
} }
private function controlRecommendedNextActionDescription(Tenant $tenant): string private function controlRecommendedNextActionDescription(ManagedEnvironment $tenant): string
{ {
$control = $this->primaryControlSummary($tenant); $control = $this->primaryControlSummary($tenant);
@ -797,7 +798,7 @@ private function controlRecommendedNextActionDescription(Tenant $tenant): string
/** /**
* @return array<string, mixed>|null * @return array<string, mixed>|null
*/ */
private function primaryControlSummary(Tenant $tenant): ?array private function primaryControlSummary(ManagedEnvironment $tenant): ?array
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -837,7 +838,7 @@ private function controlLimitationSummary(TenantReview $review): ?string
: __('localization.review.control_limitations_summary', ['limitations' => implode(', ', $labels)]); : __('localization.review.control_limitations_summary', ['limitations' => implode(', ', $labels)]);
} }
private function findingSummary(Tenant $tenant): string private function findingSummary(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -864,7 +865,7 @@ private function findingSummary(Tenant $tenant): string
]); ]);
} }
private function acceptedRiskSummary(Tenant $tenant): string private function acceptedRiskSummary(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -892,7 +893,7 @@ private function acceptedRiskSummary(Tenant $tenant): string
: $countSummary.' '.$accountability; : $countSummary.' '.$accountability;
} }
private function evidenceProofAvailability(Tenant $tenant): string private function evidenceProofAvailability(ManagedEnvironment $tenant): string
{ {
$review = $this->latestPublishedReview($tenant); $review = $this->latestPublishedReview($tenant);
@ -918,12 +919,12 @@ private function evidenceProofAvailability(Tenant $tenant): string
return __('localization.review.evidence_proof_available'); return __('localization.review.evidence_proof_available');
} }
private function evidenceStatusLabel(Tenant $tenant): string private function evidenceStatusLabel(ManagedEnvironment $tenant): string
{ {
return $this->evidenceStatusLabelForState($this->evidenceStatusState($tenant)); return $this->evidenceStatusLabelForState($this->evidenceStatusState($tenant));
} }
private function evidenceStatusColor(Tenant $tenant): string private function evidenceStatusColor(ManagedEnvironment $tenant): string
{ {
return $this->evidenceStatusColorForState($this->evidenceStatusState($tenant)); return $this->evidenceStatusColorForState($this->evidenceStatusState($tenant));
} }
@ -960,7 +961,7 @@ private function currentTenantFilterInterpretationVersion(): ?string
$tenant = $this->authorizedTenants()[$tenantId] ?? null; $tenant = $this->authorizedTenants()[$tenantId] ?? null;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -972,12 +973,12 @@ private function currentTenantFilterInterpretationVersion(): ?string
?->controlInterpretationVersion(); ?->controlInterpretationVersion();
} }
private function acceptedRiskAccountability(Tenant $tenant): ?string private function acceptedRiskAccountability(ManagedEnvironment $tenant): ?string
{ {
$exception = FindingException::query() $exception = FindingException::query()
->with(['owner', 'approver', 'currentDecision']) ->with(['owner', 'approver', 'currentDecision'])
->where('workspace_id', (int) $tenant->workspace_id) ->where('workspace_id', (int) $tenant->workspace_id)
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->current() ->current()
->orderByRaw("case when current_validity_state in ('valid', 'expiring') then 0 else 1 end") ->orderByRaw("case when current_validity_state in ('valid', 'expiring') then 0 else 1 end")
->latest('approved_at') ->latest('approved_at')

View File

@ -5,7 +5,7 @@
namespace App\Filament\Pages\Reviews; namespace App\Filament\Pages\Reviews;
use App\Filament\Resources\TenantReviewResource; use App\Filament\Resources\TenantReviewResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantReview; use App\Models\TenantReview;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
@ -61,7 +61,7 @@ class ReviewRegister extends Page implements HasTable
protected string $view = 'filament.pages.reviews.review-register'; protected string $view = 'filament.pages.reviews.review-register';
/** /**
* @var array<int, Tenant>|null * @var array<int, ManagedEnvironment>|null
*/ */
private ?array $authorizedTenants = null; private ?array $authorizedTenants = null;
@ -114,7 +114,7 @@ public function table(Table $table): Table
->persistSortInSession() ->persistSortInSession()
->recordUrl(fn (TenantReview $record): string => TenantReviewResource::tenantScopedUrl('view', ['record' => $record], $record->tenant, 'tenant')) ->recordUrl(fn (TenantReview $record): string => TenantReviewResource::tenantScopedUrl('view', ['record' => $record], $record->tenant, 'tenant'))
->columns([ ->columns([
TextColumn::make('tenant.name')->label('Tenant')->searchable(), TextColumn::make('tenant.name')->label('ManagedEnvironment')->searchable(),
TextColumn::make('status') TextColumn::make('status')
->badge() ->badge()
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantReviewStatus)) ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantReviewStatus))
@ -138,8 +138,8 @@ public function table(Table $table): Table
->wrap(), ->wrap(),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->tenantFilterOptions()) ->options(fn (): array => $this->tenantFilterOptions())
->default(fn (): ?string => $this->defaultTenantFilter()) ->default(fn (): ?string => $this->defaultTenantFilter())
->searchable(), ->searchable(),
@ -210,7 +210,7 @@ public function table(Table $table): Table
} }
/** /**
* @return array<int, Tenant> * @return array<int, ManagedEnvironment>
*/ */
public function authorizedTenants(): array public function authorizedTenants(): array
{ {
@ -270,7 +270,7 @@ private function registerQuery(): Builder
private function tenantFilterOptions(): array private function tenantFilterOptions(): array
{ {
return collect($this->authorizedTenants()) return collect($this->authorizedTenants())
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->name, (string) $tenant->getKey() => $tenant->name,
]) ])
->all(); ->all();
@ -298,8 +298,8 @@ private function applyRequestedTenantPrefilter(): void
continue; continue;
} }
$this->tableFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
$this->tableDeferredFilters['tenant_id']['value'] = (string) $tenant->getKey(); $this->tableDeferredFilters['managed_environment_id']['value'] = (string) $tenant->getKey();
return; return;
} }
@ -323,10 +323,10 @@ private function clearRegisterFilters(): void
private function currentTenantFilterId(): ?int private function currentTenantFilterId(): ?int
{ {
$tenantFilter = data_get($this->tableFilters, 'tenant_id.value'); $tenantFilter = data_get($this->tableFilters, 'managed_environment_id.value');
if (! is_numeric($tenantFilter)) { if (! is_numeric($tenantFilter)) {
$tenantFilter = data_get(session()->get($this->getTableFiltersSessionKey(), []), 'tenant_id.value'); $tenantFilter = data_get(session()->get($this->getTableFiltersSessionKey(), []), 'managed_environment_id.value');
} }
return is_numeric($tenantFilter) ? (int) $tenantFilter : null; return is_numeric($tenantFilter) ? (int) $tenantFilter : null;

View File

@ -2,7 +2,7 @@
namespace App\Filament\Pages\Tenancy; namespace App\Filament\Pages\Tenancy;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -43,7 +43,7 @@ public static function canView(): bool
} }
} }
$tenantIds = $user->tenants()->withTrashed()->pluck('tenants.id'); $tenantIds = $user->tenants()->withTrashed()->pluck('managed_environments.id');
if ($tenantIds->isEmpty()) { if ($tenantIds->isEmpty()) {
return false; return false;
@ -52,7 +52,7 @@ public static function canView(): bool
/** @var CapabilityResolver $resolver */ /** @var CapabilityResolver $resolver */
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
foreach (Tenant::query()->whereIn('id', $tenantIds)->cursor() as $tenant) { foreach (ManagedEnvironment::query()->whereIn('id', $tenantIds)->cursor() as $tenant) {
if ($resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)) { if ($resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)) {
return true; return true;
} }
@ -77,8 +77,8 @@ public function form(Schema $schema): Schema
]) ])
->default('other') ->default('other')
->required(), ->required(),
Forms\Components\TextInput::make('tenant_id') Forms\Components\TextInput::make('managed_environment_id')
->label('Tenant ID (GUID)') ->label('ManagedEnvironment ID (GUID)')
->required() ->required()
->maxLength(255) ->maxLength(255)
->unique(ignoreRecord: true), ->unique(ignoreRecord: true),
@ -104,7 +104,7 @@ protected function handleRegistration(array $data): Model
$data['workspace_id'] = $workspaceId; $data['workspace_id'] = $workspaceId;
} }
$tenant = Tenant::create($data); $tenant = ManagedEnvironment::create($data);
$user = auth()->user(); $user = auth()->user();

View File

@ -9,7 +9,7 @@
use App\Filament\Widgets\Dashboard\TenantDashboardContextChips; use App\Filament\Widgets\Dashboard\TenantDashboardContextChips;
use App\Filament\Widgets\Dashboard\TenantDashboardOverview; use App\Filament\Widgets\Dashboard\TenantDashboardOverview;
use App\Models\SupportRequest; use App\Models\SupportRequest;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -62,7 +62,7 @@ public function getTitle(): string | Htmlable
{ {
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return __('localization.dashboard.tenant_title'); return __('localization.dashboard.tenant_title');
} }
@ -99,6 +99,7 @@ public static function getUrl(array $parameters = [], bool $isAbsolute = true, ?
public function getWidgets(): array public function getWidgets(): array
{ {
return [ return [
TenantTriageArrivalContinuity::class,
TenantDashboardContextChips::class, TenantDashboardContextChips::class,
DashboardKpis::class, DashboardKpis::class,
TenantDashboardOverview::class, TenantDashboardOverview::class,
@ -228,7 +229,7 @@ private function governanceInboxHeaderAction(): ?Action
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User || ! $user->canAccessTenant($tenant)) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || ! $user->canAccessTenant($tenant)) {
return null; return null;
} }
@ -237,7 +238,7 @@ private function governanceInboxHeaderAction(): ?Action
->icon('heroicon-o-inbox-stack') ->icon('heroicon-o-inbox-stack')
->color('primary') ->color('primary')
->url(GovernanceInbox::getUrl(panel: 'admin').'?'.http_build_query([ ->url(GovernanceInbox::getUrl(panel: 'admin').'?'.http_build_query([
'tenant_id' => (int) $tenant->getKey(), 'managed_environment_id' => (int) $tenant->getKey(),
])); ]));
} }
@ -285,7 +286,7 @@ private function dashboardSummary(): ?TenantDashboardSummary
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return null; return null;
} }
@ -459,7 +460,7 @@ private function auditTenantSupportDiagnosticsOpen(): void
/** /**
* @param array<string, mixed> $bundle * @param array<string, mixed> $bundle
*/ */
private function recordSupportDiagnosticsOpened(Tenant $tenant, array $bundle, User $user): void private function recordSupportDiagnosticsOpened(ManagedEnvironment $tenant, array $bundle, User $user): void
{ {
$auditKey = 'tenant:'.$tenant->getKey(); $auditKey = 'tenant:'.$tenant->getKey();
@ -500,12 +501,12 @@ private function resolveDashboardActor(): User
return $user; return $user;
} }
private function resolveCurrentTenantForCapability(string $capability): Tenant private function resolveCurrentTenantForCapability(string $capability): ManagedEnvironment
{ {
$user = $this->resolveDashboardActor(); $user = $this->resolveDashboardActor();
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -527,7 +528,7 @@ private function tenantSupportRequestAttachmentSummary(): string
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return 'Only canonical redacted tenant context will be attached.'; return 'Only canonical redacted tenant context will be attached.';
} }

View File

@ -5,7 +5,7 @@
namespace App\Filament\Pages; namespace App\Filament\Pages;
use App\Filament\Concerns\ResolvesPanelTenantContext; use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Models\TenantMembership; use App\Models\ManagedEnvironmentMembership;
use App\Models\User; use App\Models\User;
use App\Services\Auth\TenantDiagnosticsService; use App\Services\Auth\TenantDiagnosticsService;
use App\Services\Auth\TenantMembershipManager; use App\Services\Auth\TenantMembershipManager;
@ -32,7 +32,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
{ {
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly) return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly)
->satisfy(ActionSurfaceSlot::ListHeader, 'Header exposes capability-gated tenant repair actions when inconsistent membership state is detected.') ->satisfy(ActionSurfaceSlot::ListHeader, 'Header exposes capability-gated tenant repair actions when inconsistent membership state is detected.')
->exempt(ActionSurfaceSlot::InspectAffordance, 'Tenant diagnostics is already the singleton diagnostic surface for the active tenant.') ->exempt(ActionSurfaceSlot::InspectAffordance, 'ManagedEnvironment diagnostics is already the singleton diagnostic surface for the active tenant.')
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The diagnostics page does not render row-level secondary actions.') ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The diagnostics page does not render row-level secondary actions.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The diagnostics page does not expose bulk actions.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The diagnostics page does not expose bulk actions.')
->exempt(ActionSurfaceSlot::ListEmptyState, 'Diagnostics content is always rendered instead of a list-style empty state.'); ->exempt(ActionSurfaceSlot::ListEmptyState, 'Diagnostics content is always rendered instead of a list-style empty state.');
@ -47,8 +47,8 @@ public function mount(): void
$tenant = static::resolveTenantContextForCurrentPanelOrFail(); $tenant = static::resolveTenantContextForCurrentPanelOrFail();
$tenantId = (int) $tenant->getKey(); $tenantId = (int) $tenant->getKey();
$this->missingOwner = ! TenantMembership::query() $this->missingOwner = ! ManagedEnvironmentMembership::query()
->where('tenant_id', $tenantId) ->where('managed_environment_id', $tenantId)
->where('role', 'owner') ->where('role', 'owner')
->exists(); ->exists();

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\WorkspaceMembership; use App\Models\WorkspaceMembership;
use App\Services\Intune\TenantRequiredPermissionsViewModelBuilder; use App\Services\Intune\TenantRequiredPermissionsViewModelBuilder;
@ -69,16 +69,16 @@ public static function canAccess(): bool
return static::hasScopedTenantAccess(static::resolveScopedTenant()); return static::hasScopedTenantAccess(static::resolveScopedTenant());
} }
public function currentTenant(): ?Tenant public function currentTenant(): ?ManagedEnvironment
{ {
return $this->trustedScopedTenant(); return $this->trustedScopedTenant();
} }
public function mount(Tenant|string|null $tenant = null): void public function mount(ManagedEnvironment|string|null $tenant = null): void
{ {
$tenant = static::resolveScopedTenant($tenant); $tenant = static::resolveScopedTenant($tenant);
if (! $tenant instanceof Tenant || ! static::hasScopedTenantAccess($tenant)) { if (! $tenant instanceof ManagedEnvironment || ! static::hasScopedTenantAccess($tenant)) {
abort(404); abort(404);
} }
@ -206,7 +206,7 @@ public function reRunVerificationUrl(): string
{ {
$tenant = $this->trustedScopedTenant(); $tenant = $this->trustedScopedTenant();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return TenantResource::getUrl('view', ['record' => $tenant]); return TenantResource::getUrl('view', ['record' => $tenant]);
} }
@ -217,53 +217,53 @@ public function manageProviderConnectionUrl(): ?string
{ {
$tenant = $this->trustedScopedTenant(); $tenant = $this->trustedScopedTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
return ProviderConnectionResource::getUrl('index', ['tenant' => $tenant], panel: 'admin'); return ProviderConnectionResource::getUrl('index', ['tenant' => $tenant], panel: 'admin');
} }
protected static function resolveScopedTenant(Tenant|string|null $tenant = null): ?Tenant protected static function resolveScopedTenant(ManagedEnvironment|string|null $tenant = null): ?ManagedEnvironment
{ {
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return $tenant; return $tenant;
} }
if (is_string($tenant) && $tenant !== '') { if (is_string($tenant) && $tenant !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $tenant) ->where('slug', $tenant)
->first(); ->first();
} }
$routeTenant = request()->route('tenant'); $routeTenant = request()->route('tenant');
if ($routeTenant instanceof Tenant) { if ($routeTenant instanceof ManagedEnvironment) {
return $routeTenant; return $routeTenant;
} }
if (is_string($routeTenant) && $routeTenant !== '') { if (is_string($routeTenant) && $routeTenant !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $routeTenant) ->where('slug', $routeTenant)
->first(); ->first();
} }
$queryTenant = request()->query('tenant'); $queryTenant = request()->query('tenant');
if (is_string($queryTenant) && $queryTenant !== '') { if (is_string($queryTenant) && $queryTenant !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $queryTenant) ->where('slug', $queryTenant)
->first(); ->first();
} }
return null; return null;
} }
private static function hasScopedTenantAccess(?Tenant $tenant): bool private static function hasScopedTenantAccess(?ManagedEnvironment $tenant): bool
{ {
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -285,7 +285,7 @@ private static function hasScopedTenantAccess(?Tenant $tenant): bool
return $user->canAccessTenant($tenant); return $user->canAccessTenant($tenant);
} }
private function trustedScopedTenant(): ?Tenant private function trustedScopedTenant(): ?ManagedEnvironment
{ {
$user = auth()->user(); $user = auth()->user();
@ -303,7 +303,7 @@ private function trustedScopedTenant(): ?Tenant
$routeTenant = static::resolveScopedTenant(); $routeTenant = static::resolveScopedTenant();
if ($routeTenant instanceof Tenant) { if ($routeTenant instanceof ManagedEnvironment) {
try { try {
return $workspaceContext->ensureTenantAccessibleInCurrentWorkspace($routeTenant, $user, request()); return $workspaceContext->ensureTenantAccessibleInCurrentWorkspace($routeTenant, $user, request());
} catch (NotFoundHttpException) { } catch (NotFoundHttpException) {
@ -315,9 +315,9 @@ private function trustedScopedTenant(): ?Tenant
return null; return null;
} }
$tenant = Tenant::query()->withTrashed()->whereKey($this->scopedTenantId)->first(); $tenant = ManagedEnvironment::query()->withTrashed()->whereKey($this->scopedTenantId)->first();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -350,7 +350,7 @@ private function viewModelForState(array $state): array
{ {
$tenant = $this->trustedScopedTenant(); $tenant = $this->trustedScopedTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }

View File

@ -16,8 +16,8 @@
use App\Jobs\ProviderInventorySyncJob; use App\Jobs\ProviderInventorySyncJob;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantMembership; use App\Models\ManagedEnvironmentMembership;
use App\Models\TenantOnboardingSession; use App\Models\TenantOnboardingSession;
use App\Models\User; use App\Models\User;
use App\Models\VerificationCheckAcknowledgement; use App\Models\VerificationCheckAcknowledgement;
@ -133,7 +133,7 @@ protected function getLayoutData(): array
public Workspace $workspace; public Workspace $workspace;
public ?Tenant $managedTenant = null; public ?ManagedEnvironment $managedTenant = null;
#[Locked] #[Locked]
public ?int $managedTenantId = null; public ?int $managedTenantId = null;
@ -190,7 +190,7 @@ protected function getHeaderActions(): array
$actions[] = Action::make('view_linked_tenant') $actions[] = Action::make('view_linked_tenant')
->label($this->linkedTenantActionLabel()) ->label($this->linkedTenantActionLabel())
->color('gray') ->color('gray')
->url($tenant instanceof Tenant ? TenantResource::getUrl('view', ['record' => $tenant]) : null); ->url($tenant instanceof ManagedEnvironment ? TenantResource::getUrl('view', ['record' => $tenant]) : null);
} }
if ($this->canResumeDraft($draft)) { if ($this->canResumeDraft($draft)) {
@ -224,7 +224,7 @@ private function canViewLinkedTenant(): bool
$user = auth()->user(); $user = auth()->user();
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
return false; return false;
} }
@ -245,7 +245,7 @@ private function linkedTenantActionLabel(): string
{ {
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'View tenant'; return 'View tenant';
} }
@ -325,10 +325,10 @@ public function content(Schema $schema): Schema
Step::make('Identify managed tenant') Step::make('Identify managed tenant')
->description('Create or resume a managed tenant in this workspace.') ->description('Create or resume a managed tenant in this workspace.')
->schema([ ->schema([
Section::make('Tenant') Section::make('ManagedEnvironment')
->schema([ ->schema([
TextInput::make('entra_tenant_id') TextInput::make('entra_tenant_id')
->label('Tenant ID (GUID)') ->label('ManagedEnvironment ID (GUID)')
->required() ->required()
->placeholder('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx') ->placeholder('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
->rules(['uuid']) ->rules(['uuid'])
@ -373,7 +373,7 @@ public function content(Schema $schema): Schema
]); ]);
} catch (NotFoundHttpException) { } catch (NotFoundHttpException) {
Notification::make() Notification::make()
->title('Tenant not available') ->title('ManagedEnvironment not available')
->body('This tenant cannot be onboarded in this workspace.') ->body('This tenant cannot be onboarded in this workspace.')
->danger() ->danger()
->send(); ->send();
@ -475,7 +475,7 @@ public function content(Schema $schema): Schema
->visible(fn (Get $get): bool => $get('connection_mode') === 'new'), ->visible(fn (Get $get): bool => $get('connection_mode') === 'new'),
TextInput::make('new_connection.target_scope_id') TextInput::make('new_connection.target_scope_id')
->label('Target scope ID') ->label('Target scope ID')
->default(fn (): string => $this->currentManagedTenantRecord()?->tenant_id ?? '') ->default(fn (): string => $this->currentManagedTenantRecord()?->managed_environment_id ?? '')
->disabled() ->disabled()
->dehydrated(false) ->dehydrated(false)
->visible(fn (Get $get): bool => $get('connection_mode') === 'new') ->visible(fn (Get $get): bool => $get('connection_mode') === 'new')
@ -518,7 +518,7 @@ public function content(Schema $schema): Schema
]), ]),
]) ])
->afterValidation(function (): void { ->afterValidation(function (): void {
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
throw new Halt; throw new Halt;
} }
@ -567,7 +567,7 @@ public function content(Schema $schema): Schema
SchemaActions::make([ SchemaActions::make([
Action::make('wizardStartVerification') Action::make('wizardStartVerification')
->label('Start verification') ->label('Start verification')
->visible(fn (): bool => $this->managedTenant instanceof Tenant && ! $this->verificationRunIsActive()) ->visible(fn (): bool => $this->managedTenant instanceof ManagedEnvironment && ! $this->verificationRunIsActive())
->disabled(fn (): bool => ! $this->currentUserCan(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START)) ->disabled(fn (): bool => ! $this->currentUserCan(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START))
->tooltip(fn (): ?string => $this->currentUserCan(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START) ->tooltip(fn (): ?string => $this->currentUserCan(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START)
? null ? null
@ -583,7 +583,7 @@ public function content(Schema $schema): Schema
->default(null) ->default(null)
->view('filament.forms.components.managed-tenant-onboarding-verification-report') ->view('filament.forms.components.managed-tenant-onboarding-verification-report')
->viewData(fn (): array => $this->verificationReportViewData()) ->viewData(fn (): array => $this->verificationReportViewData())
->visible(fn (): bool => $this->managedTenant instanceof Tenant), ->visible(fn (): bool => $this->managedTenant instanceof ManagedEnvironment),
]), ]),
]) ])
->beforeValidation(function (): void { ->beforeValidation(function (): void {
@ -612,7 +612,7 @@ public function content(Schema $schema): Schema
SchemaActions::make([ SchemaActions::make([
Action::make('wizardStartBootstrap') Action::make('wizardStartBootstrap')
->label('Start bootstrap') ->label('Start bootstrap')
->visible(fn (): bool => $this->managedTenant instanceof Tenant) ->visible(fn (): bool => $this->managedTenant instanceof ManagedEnvironment)
->disabled(fn (): bool => ! $this->canStartAnyBootstrap()) ->disabled(fn (): bool => ! $this->canStartAnyBootstrap())
->tooltip(fn (): ?string => $this->canStartAnyBootstrap() ->tooltip(fn (): ?string => $this->canStartAnyBootstrap()
? null ? null
@ -646,7 +646,7 @@ public function content(Schema $schema): Schema
->compact() ->compact()
->columns(2) ->columns(2)
->schema([ ->schema([
Text::make('Tenant') Text::make('ManagedEnvironment')
->color('gray'), ->color('gray'),
Text::make(fn (): string => $this->completionSummaryTenantLine()) Text::make(fn (): string => $this->completionSummaryTenantLine())
->weight(FontWeight::SemiBold), ->weight(FontWeight::SemiBold),
@ -683,7 +683,7 @@ public function content(Schema $schema): Schema
->info() ->info()
->footer([ ->footer([
UnorderedList::make([ UnorderedList::make([
'Tenant status will be set to Active.', 'ManagedEnvironment status will be set to Active.',
'Backup, inventory, and compliance operations become available.', 'Backup, inventory, and compliance operations become available.',
'The provider connection will be used for provider API calls.', 'The provider connection will be used for provider API calls.',
]), ]),
@ -705,7 +705,7 @@ public function content(Schema $schema): Schema
->color('success') ->color('success')
->requiresConfirmation() ->requiresConfirmation()
->modalHeading('Complete onboarding') ->modalHeading('Complete onboarding')
->modalDescription(fn (): string => $this->managedTenant instanceof Tenant ->modalDescription(fn (): string => $this->managedTenant instanceof ManagedEnvironment
? sprintf('Are you sure you want to complete onboarding for "%s"? This will make the tenant operational.', $this->managedTenant->name) ? sprintf('Are you sure you want to complete onboarding for "%s"? This will make the tenant operational.', $this->managedTenant->name)
: 'Are you sure you want to complete onboarding for this tenant?') : 'Are you sure you want to complete onboarding for this tenant?')
->modalSubmitActionLabel('Yes, complete onboarding') ->modalSubmitActionLabel('Yes, complete onboarding')
@ -758,7 +758,7 @@ private function loadOnboardingDraft(User $user, TenantOnboardingSession|int|str
$tenant = $draft->tenant; $tenant = $draft->tenant;
if ($tenant instanceof Tenant && (int) $tenant->workspace_id === (int) $this->workspace->getKey()) { if ($tenant instanceof ManagedEnvironment && (int) $tenant->workspace_id === (int) $this->workspace->getKey()) {
$this->setManagedTenant($tenant); $this->setManagedTenant($tenant);
} }
@ -974,7 +974,7 @@ private function resumeContextSchema(): array
->collapsed() ->collapsed()
->columns(2) ->columns(2)
->schema([ ->schema([
Text::make('Tenant') Text::make('ManagedEnvironment')
->color('gray'), ->color('gray'),
Text::make(fn () => $this->draftTitle($this->currentOnboardingSessionRecord() ?? $draft)) Text::make(fn () => $this->draftTitle($this->currentOnboardingSessionRecord() ?? $draft))
->weight(FontWeight::SemiBold), ->weight(FontWeight::SemiBold),
@ -1225,7 +1225,7 @@ private function onboardingReadinessPayload(TenantOnboardingSession $draft): arr
? $snapshot['last_completed_checkpoint'] ? $snapshot['last_completed_checkpoint']
: null; : null;
$tenant = $draft->tenant instanceof Tenant ? $draft->tenant : null; $tenant = $draft->tenant instanceof ManagedEnvironment ? $draft->tenant : null;
$providerConnection = $this->readinessProviderConnection($draft); $providerConnection = $this->readinessProviderConnection($draft);
$selectedProviderConnectionId = $providerConnection instanceof ProviderConnection $selectedProviderConnectionId = $providerConnection instanceof ProviderConnection
? (int) $providerConnection->getKey() ? (int) $providerConnection->getKey()
@ -1240,7 +1240,7 @@ private function onboardingReadinessPayload(TenantOnboardingSession $draft): arr
$verificationMatchesSelectedConnection = $verificationRun instanceof OperationRun $verificationMatchesSelectedConnection = $verificationRun instanceof OperationRun
? $this->readinessRunMatchesSelectedConnection($verificationRun, $selectedProviderConnectionId) ? $this->readinessRunMatchesSelectedConnection($verificationRun, $selectedProviderConnectionId)
: null; : null;
$permissions = $tenant instanceof Tenant ? $this->readinessPermissionOverview($tenant) : null; $permissions = $tenant instanceof ManagedEnvironment ? $this->readinessPermissionOverview($tenant) : null;
$verificationReport = $verificationRun instanceof OperationRun ? VerificationReportViewer::report($verificationRun) : null; $verificationReport = $verificationRun instanceof OperationRun ? VerificationReportViewer::report($verificationRun) : null;
$verificationReport = is_array($verificationReport) ? $verificationReport : null; $verificationReport = is_array($verificationReport) ? $verificationReport : null;
$verificationPrimaryReasonCode = $verificationReport !== null $verificationPrimaryReasonCode = $verificationReport !== null
@ -1300,7 +1300,7 @@ private function onboardingReadinessPayload(TenantOnboardingSession $draft): arr
? $this->readinessVerificationOverall($verificationRun, $verificationReport) ? $this->readinessVerificationOverall($verificationRun, $verificationReport)
: null, : null,
], ],
'verification_assist' => $tenant instanceof Tenant && $verificationReport !== null 'verification_assist' => $tenant instanceof ManagedEnvironment && $verificationReport !== null
? app(VerificationAssistViewModelBuilder::class)->visibility($tenant, $verificationReport) ? app(VerificationAssistViewModelBuilder::class)->visibility($tenant, $verificationReport)
: $this->hiddenVerificationAssistVisibility(), : $this->hiddenVerificationAssistVisibility(),
'permissions' => $permissions, 'permissions' => $permissions,
@ -1443,14 +1443,14 @@ private function readinessProviderConnection(TenantOnboardingSession $draft): ?P
$state['provider_connection_id'] ?? $state['selected_provider_connection_id'] ?? null, $state['provider_connection_id'] ?? $state['selected_provider_connection_id'] ?? null,
); );
if ($providerConnectionId === null || $draft->tenant_id === null) { if ($providerConnectionId === null || $draft->managed_environment_id === null) {
return null; return null;
} }
return ProviderConnection::query() return ProviderConnection::query()
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->where('workspace_id', (int) $draft->workspace_id) ->where('workspace_id', (int) $draft->workspace_id)
->where('tenant_id', (int) $draft->tenant_id) ->where('managed_environment_id', (int) $draft->managed_environment_id)
->first(); ->first();
} }
@ -1488,7 +1488,7 @@ private function readinessProviderSummary(?ProviderConnection $connection): ?arr
/** /**
* @return array{overall: string|null, counts: array<string, int>, freshness: array{last_refreshed_at: string|null, is_stale: bool}, missing_permissions: array{application: list<string>, delegated: list<string>}, required_permissions_url: string|null} * @return array{overall: string|null, counts: array<string, int>, freshness: array{last_refreshed_at: string|null, is_stale: bool}, missing_permissions: array{application: list<string>, delegated: list<string>}, required_permissions_url: string|null}
*/ */
private function readinessPermissionOverview(Tenant $tenant): array private function readinessPermissionOverview(ManagedEnvironment $tenant): array
{ {
$viewModel = app(TenantRequiredPermissionsViewModelBuilder::class)->build($tenant, [ $viewModel = app(TenantRequiredPermissionsViewModelBuilder::class)->build($tenant, [
'status' => 'all', 'status' => 'all',
@ -1608,7 +1608,7 @@ private function readinessSummaryText(
bool $verificationMismatch, bool $verificationMismatch,
): string { ): string {
if (! $this->readinessDraftHasTenantIdentity($draft)) { if (! $this->readinessDraftHasTenantIdentity($draft)) {
return 'Tenant identity required'; return 'ManagedEnvironment identity required';
} }
if (! $providerConnection instanceof ProviderConnection) { if (! $providerConnection instanceof ProviderConnection) {
@ -1704,7 +1704,7 @@ private function readinessNextAction(
return $this->readinessAction( return $this->readinessAction(
label: 'Grant admin consent', label: 'Grant admin consent',
kind: 'grant_consent', kind: 'grant_consent',
url: $draft->tenant instanceof Tenant ? RequiredPermissionsLinks::adminConsentPrimaryUrl($draft->tenant) : null, url: $draft->tenant instanceof ManagedEnvironment ? RequiredPermissionsLinks::adminConsentPrimaryUrl($draft->tenant) : null,
); );
} }
@ -1718,7 +1718,7 @@ private function readinessNextAction(
return $this->readinessAction( return $this->readinessAction(
label: 'Grant admin consent', label: 'Grant admin consent',
kind: 'grant_consent', kind: 'grant_consent',
url: $draft->tenant instanceof Tenant ? RequiredPermissionsLinks::adminConsentPrimaryUrl($draft->tenant) : null, url: $draft->tenant instanceof ManagedEnvironment ? RequiredPermissionsLinks::adminConsentPrimaryUrl($draft->tenant) : null,
); );
} }
@ -1726,7 +1726,7 @@ private function readinessNextAction(
return $this->readinessAction( return $this->readinessAction(
label: 'Review permissions', label: 'Review permissions',
kind: 'review_permissions', kind: 'review_permissions',
url: $draft->tenant instanceof Tenant ? RequiredPermissionsLinks::requiredPermissions($draft->tenant) : null, url: $draft->tenant instanceof ManagedEnvironment ? RequiredPermissionsLinks::requiredPermissions($draft->tenant) : null,
); );
} }
@ -1862,7 +1862,7 @@ private function readinessConnectionRecentlyUpdated(TenantOnboardingSession $dra
private function readinessDraftHasTenantIdentity(TenantOnboardingSession $draft): bool private function readinessDraftHasTenantIdentity(TenantOnboardingSession $draft): bool
{ {
if ($draft->tenant_id !== null) { if ($draft->managed_environment_id !== null) {
return true; return true;
} }
@ -1981,7 +1981,7 @@ private function resumeOnboardingDraft(int $draftId, bool $logSelection): void
'metadata' => [ 'metadata' => [
'workspace_id' => (int) $this->workspace->getKey(), 'workspace_id' => (int) $this->workspace->getKey(),
'onboarding_session_id' => (int) $draft->getKey(), 'onboarding_session_id' => (int) $draft->getKey(),
'tenant_db_id' => $draft->tenant_id !== null ? (int) $draft->tenant_id : null, 'tenant_db_id' => $draft->managed_environment_id !== null ? (int) $draft->managed_environment_id : null,
], ],
], ],
actor: $user, actor: $user,
@ -2055,7 +2055,7 @@ private function cancelOnboardingDraft(): void
context: [ context: [
'metadata' => [ 'metadata' => [
'workspace_id' => (int) $this->workspace->getKey(), 'workspace_id' => (int) $this->workspace->getKey(),
'tenant_db_id' => $this->onboardingSession->tenant_id !== null ? (int) $this->onboardingSession->tenant_id : null, 'tenant_db_id' => $this->onboardingSession->managed_environment_id !== null ? (int) $this->onboardingSession->managed_environment_id : null,
'onboarding_session_id' => (int) $this->onboardingSession->getKey(), 'onboarding_session_id' => (int) $this->onboardingSession->getKey(),
], ],
], ],
@ -2067,7 +2067,7 @@ private function cancelOnboardingDraft(): void
$normalizedTenant = $this->lifecycleService()->syncLinkedTenantAfterCancellation($this->onboardingSession); $normalizedTenant = $this->lifecycleService()->syncLinkedTenantAfterCancellation($this->onboardingSession);
if ($normalizedTenant instanceof Tenant) { if ($normalizedTenant instanceof ManagedEnvironment) {
app(WorkspaceAuditLogger::class)->logTenantLifecycleAction( app(WorkspaceAuditLogger::class)->logTenantLifecycleAction(
tenant: $normalizedTenant, tenant: $normalizedTenant,
action: AuditActionId::TenantReturnedToDraft, action: AuditActionId::TenantReturnedToDraft,
@ -2129,7 +2129,7 @@ private function deleteOnboardingDraft(): void
$draftTitle = $this->draftTitle($draft); $draftTitle = $this->draftTitle($draft);
$draftStatus = $draft->status()->value; $draftStatus = $draft->status()->value;
$draftLifecycle = $draft->lifecycleState()->value; $draftLifecycle = $draft->lifecycleState()->value;
$tenantId = $draft->tenant_id !== null ? (int) $draft->tenant_id : null; $tenantId = $draft->managed_environment_id !== null ? (int) $draft->managed_environment_id : null;
$draft->delete(); $draft->delete();
@ -2312,14 +2312,14 @@ private function setOnboardingSession(?TenantOnboardingSession $draft): void
? $draft->expectedVersion() ? $draft->expectedVersion()
: null; : null;
if ($draft instanceof TenantOnboardingSession && $draft->tenant instanceof Tenant) { if ($draft instanceof TenantOnboardingSession && $draft->tenant instanceof ManagedEnvironment) {
$this->setManagedTenant($draft->tenant); $this->setManagedTenant($draft->tenant);
return; return;
} }
if ($draft instanceof TenantOnboardingSession && $draft->tenant_id !== null) { if ($draft instanceof TenantOnboardingSession && $draft->managed_environment_id !== null) {
$this->managedTenantId = (int) $draft->tenant_id; $this->managedTenantId = (int) $draft->managed_environment_id;
return; return;
} }
@ -2327,14 +2327,14 @@ private function setOnboardingSession(?TenantOnboardingSession $draft): void
$this->setManagedTenant(null); $this->setManagedTenant(null);
} }
private function setManagedTenant(?Tenant $tenant): void private function setManagedTenant(?ManagedEnvironment $tenant): void
{ {
$this->managedTenant = $tenant; $this->managedTenant = $tenant;
$this->managedTenantId = $tenant instanceof Tenant $this->managedTenantId = $tenant instanceof ManagedEnvironment
? (int) $tenant->getKey() ? (int) $tenant->getKey()
: null; : null;
if ($this->onboardingSession instanceof TenantOnboardingSession && $tenant instanceof Tenant) { if ($this->onboardingSession instanceof TenantOnboardingSession && $tenant instanceof ManagedEnvironment) {
$this->onboardingSession->setRelation('tenant', $tenant); $this->onboardingSession->setRelation('tenant', $tenant);
} }
} }
@ -2362,15 +2362,15 @@ private function currentOnboardingSessionRecord(): ?TenantOnboardingSession
return $query->first(); return $query->first();
} }
private function currentManagedTenantRecord(): ?Tenant private function currentManagedTenantRecord(): ?ManagedEnvironment
{ {
$draft = $this->currentOnboardingSessionRecord(); $draft = $this->currentOnboardingSessionRecord();
if ($draft instanceof TenantOnboardingSession && $draft->tenant instanceof Tenant) { if ($draft instanceof TenantOnboardingSession && $draft->tenant instanceof ManagedEnvironment) {
return $draft->tenant; return $draft->tenant;
} }
if ($this->managedTenant instanceof Tenant if ($this->managedTenant instanceof ManagedEnvironment
&& $this->managedTenantId !== null && $this->managedTenantId !== null
&& (int) $this->managedTenant->getKey() === $this->managedTenantId) { && (int) $this->managedTenant->getKey() === $this->managedTenantId) {
return $this->managedTenant; return $this->managedTenant;
@ -2380,7 +2380,7 @@ private function currentManagedTenantRecord(): ?Tenant
return $this->managedTenant; return $this->managedTenant;
} }
$query = Tenant::query()->withTrashed()->whereKey($this->managedTenantId); $query = ManagedEnvironment::query()->withTrashed()->whereKey($this->managedTenantId);
if (isset($this->workspace)) { if (isset($this->workspace)) {
$query->where('workspace_id', (int) $this->workspace->getKey()); $query->where('workspace_id', (int) $this->workspace->getKey());
@ -2497,7 +2497,7 @@ public function refreshCheckpointLifecycle(): void
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$this->setManagedTenant($tenant->fresh()); $this->setManagedTenant($tenant->fresh());
} }
@ -2527,9 +2527,9 @@ private function initializeWizardData(): void
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$this->data['entra_tenant_id'] ??= (string) $tenant->tenant_id; $this->data['entra_tenant_id'] ??= (string) $tenant->managed_environment_id;
$this->data['new_connection']['target_scope_id'] ??= (string) $tenant->tenant_id; $this->data['new_connection']['target_scope_id'] ??= (string) $tenant->managed_environment_id;
$this->data['environment'] ??= (string) ($tenant->environment ?? 'other'); $this->data['environment'] ??= (string) ($tenant->environment ?? 'other');
$this->data['name'] ??= (string) $tenant->name; $this->data['name'] ??= (string) $tenant->name;
$this->data['primary_domain'] ??= (string) ($tenant->domain ?? ''); $this->data['primary_domain'] ??= (string) ($tenant->domain ?? '');
@ -2608,14 +2608,14 @@ private function providerConnectionOptions(): array
{ {
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return ProviderConnection::query() return ProviderConnection::query()
->with('tenant') ->with('tenant')
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', $tenant->getKey()) ->where('managed_environment_id', $tenant->getKey())
->orderByDesc('is_default') ->orderByDesc('is_default')
->orderBy('display_name') ->orderBy('display_name')
->get() ->get()
@ -2868,12 +2868,12 @@ private function verificationReportViewData(): array
$previousRunUrl = $this->verificationPreviousRunUrl($changeIndicator); $previousRunUrl = $this->verificationPreviousRunUrl($changeIndicator);
$user = auth()->user(); $user = auth()->user();
$canAcknowledge = $user instanceof User && $this->managedTenant instanceof Tenant $canAcknowledge = $user instanceof User && $this->managedTenant instanceof ManagedEnvironment
? $user->can(Capabilities::TENANT_VERIFICATION_ACKNOWLEDGE, $this->managedTenant) ? $user->can(Capabilities::TENANT_VERIFICATION_ACKNOWLEDGE, $this->managedTenant)
: false; : false;
$acknowledgements = VerificationCheckAcknowledgement::query() $acknowledgements = VerificationCheckAcknowledgement::query()
->where('tenant_id', (int) $run->tenant_id) ->where('managed_environment_id', (int) $run->managed_environment_id)
->where('workspace_id', (int) $run->workspace_id) ->where('workspace_id', (int) $run->workspace_id)
->where('operation_run_id', (int) $run->getKey()) ->where('operation_run_id', (int) $run->getKey())
->with('acknowledgedByUser') ->with('acknowledgedByUser')
@ -2965,7 +2965,7 @@ private function verificationContextualHelp(array $verificationReport, Operation
{ {
$tenant = $this->managedTenant; $tenant = $this->managedTenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -3056,13 +3056,13 @@ public function acknowledgeVerificationCheckAction(): Action
abort(403); abort(403);
} }
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
$tenant = $this->managedTenant->fresh(); $tenant = $this->managedTenant->fresh();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -3108,7 +3108,7 @@ public function acknowledgeVerificationCheckAction(): Action
return false; return false;
} }
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
return false; return false;
} }
@ -3235,7 +3235,7 @@ private function touchOnboardingSessionStep(string $step): void
context: [ context: [
'metadata' => [ 'metadata' => [
'workspace_id' => (int) $this->workspace->getKey(), 'workspace_id' => (int) $this->workspace->getKey(),
'tenant_db_id' => $this->onboardingSession->tenant_id !== null ? (int) $this->onboardingSession->tenant_id : null, 'tenant_db_id' => $this->onboardingSession->managed_environment_id !== null ? (int) $this->onboardingSession->managed_environment_id : null,
'onboarding_session_id' => (int) $this->onboardingSession->getKey(), 'onboarding_session_id' => (int) $this->onboardingSession->getKey(),
'current_step' => $step, 'current_step' => $step,
], ],
@ -3282,17 +3282,17 @@ private function authorizeEditableDraft(User $user): void
} }
} }
private function trustedManagedTenantForUser(User $user): Tenant private function trustedManagedTenantForUser(User $user): ManagedEnvironment
{ {
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
$tenant = $tenant->fresh(); $tenant = $tenant->fresh();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -3309,7 +3309,7 @@ private function canResumeDraft(?TenantOnboardingSession $draft): bool
return false; return false;
} }
if (! $draft->tenant instanceof Tenant) { if (! $draft->tenant instanceof ManagedEnvironment) {
return $this->lifecycleService()->canResumeDraft($draft); return $this->lifecycleService()->canResumeDraft($draft);
} }
@ -3334,12 +3334,12 @@ private function authorizeWorkspaceMember(User $user): void
); );
} }
private function resolveWorkspaceIdForUnboundTenant(Tenant $tenant): ?int private function resolveWorkspaceIdForUnboundTenant(ManagedEnvironment $tenant): ?int
{ {
$workspaceId = DB::table('tenant_memberships') $workspaceId = DB::table('managed_environment_memberships')
->join('workspace_memberships', 'workspace_memberships.user_id', '=', 'tenant_memberships.user_id') ->join('workspace_memberships', 'workspace_memberships.user_id', '=', 'managed_environment_memberships.user_id')
->where('tenant_memberships.tenant_id', (int) $tenant->getKey()) ->where('managed_environment_memberships.managed_environment_id', (int) $tenant->getKey())
->orderByRaw("CASE tenant_memberships.role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 WHEN 'operator' THEN 2 ELSE 3 END") ->orderByRaw("CASE managed_environment_memberships.role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 WHEN 'operator' THEN 2 ELSE 3 END")
->value('workspace_memberships.workspace_id'); ->value('workspace_memberships.workspace_id');
return $workspaceId === null ? null : (int) $workspaceId; return $workspaceId === null ? null : (int) $workspaceId;
@ -3385,13 +3385,13 @@ public function identifyManagedTenant(array $data): void
$currentDraftId = $this->onboardingSession?->getKey(); $currentDraftId = $this->onboardingSession?->getKey();
$sessionWasCreated = false; $sessionWasCreated = false;
$existingTenant = Tenant::query() $existingTenant = ManagedEnvironment::query()
->withTrashed() ->withTrashed()
->where('tenant_id', $entraTenantId) ->where('slug', $entraTenantId)
->first(); ->first();
if ($existingTenant instanceof Tenant) { if ($existingTenant instanceof ManagedEnvironment) {
if ($existingTenant->trashed() || $existingTenant->status === Tenant::STATUS_ARCHIVED) { if ($existingTenant->trashed() || $existingTenant->status === ManagedEnvironment::STATUS_ARCHIVED) {
abort(404); abort(404);
} }
@ -3411,7 +3411,7 @@ public function identifyManagedTenant(array $data): void
'name' => $tenantName, 'name' => $tenantName,
'environment' => $environment, 'environment' => $environment,
'domain' => $primaryDomain, 'domain' => $primaryDomain,
'status' => $existingTenant->status === Tenant::STATUS_DRAFT ? Tenant::STATUS_ONBOARDING : $existingTenant->status, 'status' => $existingTenant->status === ManagedEnvironment::STATUS_DRAFT ? ManagedEnvironment::STATUS_ONBOARDING : $existingTenant->status,
'metadata' => array_merge(is_array($existingTenant->metadata) ? $existingTenant->metadata : [], array_filter([ 'metadata' => array_merge(is_array($existingTenant->metadata) ? $existingTenant->metadata : [], array_filter([
'notes' => $notes, 'notes' => $notes,
], static fn ($value): bool => $value !== null)), ], static fn ($value): bool => $value !== null)),
@ -3420,30 +3420,30 @@ public function identifyManagedTenant(array $data): void
$tenant = $existingTenant; $tenant = $existingTenant;
} else { } else {
try { try {
$tenant = Tenant::query()->create([ $tenant = ManagedEnvironment::query()->create([
'workspace_id' => (int) $this->workspace->getKey(), 'workspace_id' => (int) $this->workspace->getKey(),
'name' => $tenantName, 'name' => $tenantName,
'tenant_id' => $entraTenantId, 'slug' => $entraTenantId,
'domain' => $primaryDomain, 'domain' => $primaryDomain,
'environment' => $environment, 'environment' => $environment,
'status' => Tenant::STATUS_ONBOARDING, 'status' => ManagedEnvironment::STATUS_ONBOARDING,
'metadata' => array_filter([ 'metadata' => array_filter([
'notes' => $notes, 'notes' => $notes,
], static fn ($value): bool => $value !== null), ], static fn ($value): bool => $value !== null),
]); ]);
} catch (QueryException $exception) { } catch (QueryException $exception) {
// Race-safe global uniqueness: if another workspace created the tenant_id first, // Race-safe global uniqueness: if another workspace created the managed_environment_id first,
// treat it as deny-as-not-found. // treat it as deny-as-not-found.
$existingTenant = Tenant::query() $existingTenant = ManagedEnvironment::query()
->withTrashed() ->withTrashed()
->where('tenant_id', $entraTenantId) ->where('slug', $entraTenantId)
->first(); ->first();
if ($existingTenant instanceof Tenant && (int) $existingTenant->workspace_id !== (int) $this->workspace->getKey()) { if ($existingTenant instanceof ManagedEnvironment && (int) $existingTenant->workspace_id !== (int) $this->workspace->getKey()) {
abort(404); abort(404);
} }
if ($existingTenant instanceof Tenant && (int) $existingTenant->workspace_id === (int) $this->workspace->getKey()) { if ($existingTenant instanceof ManagedEnvironment && (int) $existingTenant->workspace_id === (int) $this->workspace->getKey()) {
$tenant = $existingTenant; $tenant = $existingTenant;
} else { } else {
throw $exception; throw $exception;
@ -3459,13 +3459,13 @@ public function identifyManagedTenant(array $data): void
source: 'manual', source: 'manual',
); );
$ownerCount = TenantMembership::query() $ownerCount = ManagedEnvironmentMembership::query()
->where('tenant_id', $tenant->getKey()) ->where('managed_environment_id', $tenant->getKey())
->where('role', 'owner') ->where('role', 'owner')
->count(); ->count();
if ($ownerCount === 0) { if ($ownerCount === 0) {
throw new RuntimeException('Tenant must have at least one owner.'); throw new RuntimeException('ManagedEnvironment must have at least one owner.');
} }
$this->selectedProviderConnectionId ??= $this->resolveDefaultProviderConnectionId($tenant); $this->selectedProviderConnectionId ??= $this->resolveDefaultProviderConnectionId($tenant);
@ -3477,7 +3477,7 @@ public function identifyManagedTenant(array $data): void
preferredDraft: $this->onboardingSession, preferredDraft: $this->onboardingSession,
expectedVersion: $this->expectedDraftVersion(), expectedVersion: $this->expectedDraftVersion(),
mutator: function (TenantOnboardingSession $draft) use ($tenant, $entraTenantId, $tenantName, $environment, $primaryDomain, $notes): void { mutator: function (TenantOnboardingSession $draft) use ($tenant, $entraTenantId, $tenantName, $environment, $primaryDomain, $notes): void {
$draft->tenant_id = (int) $tenant->getKey(); $draft->managed_environment_id = (int) $tenant->getKey();
$draft->current_step = 'identify'; $draft->current_step = 'identify';
$draft->state = array_merge($draft->state ?? [], [ $draft->state = array_merge($draft->state ?? [], [
'entra_tenant_id' => $entraTenantId, 'entra_tenant_id' => $entraTenantId,
@ -3571,7 +3571,7 @@ public function selectProviderConnection(int $providerConnectionId): void
$connection = ProviderConnection::query() $connection = ProviderConnection::query()
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->first(); ->first();
@ -3651,7 +3651,7 @@ public function createProviderConnection(array $data): void
$tenant = $this->trustedManagedTenantForUser($user)->fresh(); $tenant = $this->trustedManagedTenantForUser($user)->fresh();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -3675,10 +3675,10 @@ public function createProviderConnection(array $data): void
$targetScope = app(ProviderConnectionTargetScopeNormalizer::class)->normalizeInput( $targetScope = app(ProviderConnectionTargetScopeNormalizer::class)->normalizeInput(
provider: 'microsoft', provider: 'microsoft',
scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT, scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT,
scopeIdentifier: (string) $tenant->tenant_id, scopeIdentifier: (string) $tenant->managed_environment_id,
scopeDisplayName: $displayName, scopeDisplayName: $displayName,
providerSpecificIdentity: [ providerSpecificIdentity: [
'microsoft_tenant_id' => (string) $tenant->tenant_id, 'microsoft_tenant_id' => (string) $tenant->managed_environment_id,
], ],
); );
@ -3702,17 +3702,17 @@ public function createProviderConnection(array $data): void
/** @var ProviderConnection $connection */ /** @var ProviderConnection $connection */
$connection = DB::transaction(function () use ($tenant, $displayName, $clientId, $clientSecret, $makeDefault, $usesDedicatedCredential, &$wasExistingConnection, &$previousConnectionType): ProviderConnection { $connection = DB::transaction(function () use ($tenant, $displayName, $clientId, $clientSecret, $makeDefault, $usesDedicatedCredential, &$wasExistingConnection, &$previousConnectionType): ProviderConnection {
$connection = ProviderConnection::query() $connection = ProviderConnection::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->where('provider', 'microsoft') ->where('provider', 'microsoft')
->where('entra_tenant_id', (string) $tenant->tenant_id) ->where('entra_tenant_id', (string) $tenant->managed_environment_id)
->first(); ->first();
if (! $connection instanceof ProviderConnection) { if (! $connection instanceof ProviderConnection) {
$connection = ProviderConnection::query()->create([ $connection = ProviderConnection::query()->create([
'workspace_id' => (int) $tenant->workspace_id, 'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => (int) $tenant->getKey(), 'managed_environment_id' => (int) $tenant->getKey(),
'provider' => 'microsoft', 'provider' => 'microsoft',
'entra_tenant_id' => (string) $tenant->tenant_id, 'entra_tenant_id' => (string) $tenant->managed_environment_id,
'display_name' => $displayName, 'display_name' => $displayName,
'is_enabled' => true, 'is_enabled' => true,
'connection_type' => ProviderConnectionType::Platform->value, 'connection_type' => ProviderConnectionType::Platform->value,
@ -3894,7 +3894,7 @@ public function startVerification(): void
return; return;
} }
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -4075,7 +4075,7 @@ public function startBootstrap(array $operationTypes): void
$tenant = $this->trustedManagedTenantForUser($user)->fresh(); $tenant = $this->trustedManagedTenantForUser($user)->fresh();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -4503,7 +4503,7 @@ private function verificationIsBlocked(): bool
private function canCompleteOnboarding(): bool private function canCompleteOnboarding(): bool
{ {
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
return false; return false;
} }
@ -4669,7 +4669,7 @@ private function completionSummaryTenantLine(): string
{ {
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '—'; return '—';
} }
@ -4683,7 +4683,7 @@ private function completionSummaryConnectionLabel(): string
{ {
$tenant = $this->currentManagedTenantRecord(); $tenant = $this->currentManagedTenantRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '—'; return '—';
} }
@ -4706,7 +4706,7 @@ private function completionSummaryConnectionLabel(): string
private function completionSummaryConnectionDetail(): string private function completionSummaryConnectionDetail(): string
{ {
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
return ''; return '';
} }
@ -5043,7 +5043,7 @@ public function completeOnboarding(): void
$tenant = $tenant->fresh(); $tenant = $tenant->fresh();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -5064,7 +5064,7 @@ public function completeOnboarding(): void
try { try {
DB::transaction(function () use ($tenant, $user): void { DB::transaction(function () use ($tenant, $user): void {
$tenant->update(['status' => Tenant::STATUS_ACTIVE]); $tenant->update(['status' => ManagedEnvironment::STATUS_ACTIVE]);
$this->setOnboardingSession($this->mutationService()->mutate( $this->setOnboardingSession($this->mutationService()->mutate(
draft: $this->onboardingSession, draft: $this->onboardingSession,
@ -5080,8 +5080,8 @@ public function completeOnboarding(): void
} catch (OnboardingDraftConflictException) { } catch (OnboardingDraftConflictException) {
$tenant->refresh(); $tenant->refresh();
if ($tenant->status === Tenant::STATUS_ACTIVE) { if ($tenant->status === ManagedEnvironment::STATUS_ACTIVE) {
$tenant->update(['status' => Tenant::STATUS_ONBOARDING]); $tenant->update(['status' => ManagedEnvironment::STATUS_ONBOARDING]);
} }
$this->handleDraftConflict('Completing onboarding was blocked because the onboarding draft changed.'); $this->handleDraftConflict('Completing onboarding was blocked because the onboarding draft changed.');
@ -5090,8 +5090,8 @@ public function completeOnboarding(): void
} catch (OnboardingDraftImmutableException) { } catch (OnboardingDraftImmutableException) {
$tenant->refresh(); $tenant->refresh();
if ($tenant->status === Tenant::STATUS_ACTIVE) { if ($tenant->status === ManagedEnvironment::STATUS_ACTIVE) {
$tenant->update(['status' => Tenant::STATUS_ONBOARDING]); $tenant->update(['status' => ManagedEnvironment::STATUS_ONBOARDING]);
} }
$this->handleImmutableDraft('Completing onboarding was blocked because the onboarding draft is no longer editable.'); $this->handleImmutableDraft('Completing onboarding was blocked because the onboarding draft is no longer editable.');
@ -5203,7 +5203,7 @@ private function verificationAssistVisibility(): array
$user = $this->currentUser(); $user = $this->currentUser();
$run = $this->verificationRun(); $run = $this->verificationRun();
if (! $tenant instanceof Tenant || ! $user instanceof User || ! $user->canAccessTenant($tenant)) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || ! $user->canAccessTenant($tenant)) {
return $this->hiddenVerificationAssistVisibility(); return $this->hiddenVerificationAssistVisibility();
} }
@ -5244,7 +5244,7 @@ private function verificationAssistViewModel(): array
$user = $this->currentUser(); $user = $this->currentUser();
$run = $this->verificationRun(); $run = $this->verificationRun();
if (! $tenant instanceof Tenant || ! $user instanceof User || ! $user->canAccessTenant($tenant)) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || ! $user->canAccessTenant($tenant)) {
abort(404); abort(404);
} }
@ -5336,14 +5336,14 @@ private function inlineEditSelectedConnectionFill(int $providerConnectionId): ar
$this->authorizeWorkspaceMutation($user, Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE); $this->authorizeWorkspaceMutation($user, Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE);
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
$connection = ProviderConnection::query() $connection = ProviderConnection::query()
->with('credential') ->with('credential')
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $this->managedTenant->getKey()) ->where('managed_environment_id', (int) $this->managedTenant->getKey())
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->first(); ->first();
@ -5375,14 +5375,14 @@ public function updateSelectedProviderConnectionInline(int $providerConnectionId
$this->authorizeWorkspaceMutation($user, Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE); $this->authorizeWorkspaceMutation($user, Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE);
if (! $this->managedTenant instanceof Tenant) { if (! $this->managedTenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
$connection = ProviderConnection::query() $connection = ProviderConnection::query()
->with('credential') ->with('credential')
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $this->managedTenant->getKey()) ->where('managed_environment_id', (int) $this->managedTenant->getKey())
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->first(); ->first();
@ -5570,11 +5570,11 @@ private function bootstrapOperationOptions(): array
->all(); ->all();
} }
private function resolveDefaultProviderConnectionId(Tenant $tenant): ?int private function resolveDefaultProviderConnectionId(ManagedEnvironment $tenant): ?int
{ {
$id = ProviderConnection::query() $id = ProviderConnection::query()
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->where('is_default', true) ->where('is_default', true)
->orderByDesc('id') ->orderByDesc('id')
->value('id'); ->value('id');
@ -5585,14 +5585,14 @@ private function resolveDefaultProviderConnectionId(Tenant $tenant): ?int
$fallback = ProviderConnection::query() $fallback = ProviderConnection::query()
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->orderByDesc('id') ->orderByDesc('id')
->value('id'); ->value('id');
return is_int($fallback) ? $fallback : null; return is_int($fallback) ? $fallback : null;
} }
private function resolveSelectedProviderConnection(Tenant $tenant): ?ProviderConnection private function resolveSelectedProviderConnection(ManagedEnvironment $tenant): ?ProviderConnection
{ {
$providerConnectionId = $this->selectedProviderConnectionId; $providerConnectionId = $this->selectedProviderConnectionId;
@ -5611,7 +5611,7 @@ private function resolveSelectedProviderConnection(Tenant $tenant): ?ProviderCon
return ProviderConnection::query() return ProviderConnection::query()
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->first(); ->first();
} }
@ -5629,7 +5629,7 @@ private function resolvePersistedProviderConnectionId(mixed $providerConnectionI
$tenantId = $this->managedTenant?->getKey(); $tenantId = $this->managedTenant?->getKey();
if (! is_int($tenantId) && $this->onboardingSession instanceof TenantOnboardingSession) { if (! is_int($tenantId) && $this->onboardingSession instanceof TenantOnboardingSession) {
$tenantId = is_numeric($this->onboardingSession->tenant_id) ? (int) $this->onboardingSession->tenant_id : null; $tenantId = is_numeric($this->onboardingSession->managed_environment_id) ? (int) $this->onboardingSession->managed_environment_id : null;
} }
if (! is_int($tenantId)) { if (! is_int($tenantId)) {
@ -5639,7 +5639,7 @@ private function resolvePersistedProviderConnectionId(mixed $providerConnectionI
$exists = ProviderConnection::query() $exists = ProviderConnection::query()
->whereKey($providerConnectionId) ->whereKey($providerConnectionId)
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->where('tenant_id', $tenantId) ->where('managed_environment_id', $tenantId)
->exists(); ->exists();
return $exists ? $providerConnectionId : null; return $exists ? $providerConnectionId : null;

View File

@ -6,7 +6,7 @@
use App\Filament\Pages\ChooseTenant; use App\Filament\Pages\ChooseTenant;
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Tenants\TenantOperabilityService; use App\Services\Tenants\TenantOperabilityService;
@ -48,26 +48,26 @@ public function mount(Workspace $workspace): void
} }
/** /**
* @return Collection<int, Tenant> * @return Collection<int, ManagedEnvironment>
*/ */
public function getTenants(): Collection public function getTenants(): Collection
{ {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
return Tenant::query()->whereRaw('1 = 0')->get(); return ManagedEnvironment::query()->whereRaw('1 = 0')->get();
} }
$tenantIds = $user->tenantMemberships() $tenantIds = $user->tenantMemberships()
->pluck('tenant_id'); ->pluck('managed_environment_id');
return Tenant::query() return ManagedEnvironment::query()
->withTrashed() ->withTrashed()
->whereIn('id', $tenantIds) ->whereIn('id', $tenantIds)
->where('workspace_id', $this->workspace->getKey()) ->where('workspace_id', $this->workspace->getKey())
->orderBy('name') ->orderBy('name')
->get() ->get()
->filter(function (Tenant $tenant) use ($user): bool { ->filter(function (ManagedEnvironment $tenant) use ($user): bool {
return app(TenantOperabilityService::class)->outcomeFor( return app(TenantOperabilityService::class)->outcomeFor(
tenant: $tenant, tenant: $tenant,
question: TenantOperabilityQuestion::AdministrativeDiscoverability, question: TenantOperabilityQuestion::AdministrativeDiscoverability,
@ -92,13 +92,13 @@ public function openTenant(int $tenantId): void
abort(403); abort(403);
} }
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->withTrashed() ->withTrashed()
->where('workspace_id', $this->workspace->getKey()) ->where('workspace_id', $this->workspace->getKey())
->whereKey($tenantId) ->whereKey($tenantId)
->first(); ->first();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }

View File

@ -8,7 +8,7 @@
use App\Filament\Resources\AlertDeliveryResource\Pages; use App\Filament\Resources\AlertDeliveryResource\Pages;
use App\Models\AlertDelivery; use App\Models\AlertDelivery;
use App\Models\AlertDestination; use App\Models\AlertDestination;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
@ -133,13 +133,13 @@ public static function getEloquentQuery(): Builder
->when( ->when(
$user instanceof User, $user instanceof User,
fn (Builder $query): Builder => $query->where(function (Builder $q) use ($user): void { fn (Builder $query): Builder => $query->where(function (Builder $q) use ($user): void {
$q->whereIn('tenant_id', $user->tenantMemberships()->select('tenant_id')) $q->whereIn('managed_environment_id', $user->tenantMemberships()->select('managed_environment_id'))
->orWhereNull('tenant_id'); ->orWhereNull('managed_environment_id');
}), }),
) )
->when( ->when(
$activeTenant instanceof Tenant, $activeTenant instanceof ManagedEnvironment,
fn (Builder $query): Builder => $query->where('tenant_id', (int) $activeTenant->getKey()), fn (Builder $query): Builder => $query->where('managed_environment_id', (int) $activeTenant->getKey()),
) )
->latest('id'); ->latest('id');
} }
@ -169,7 +169,7 @@ public static function infolist(Schema $schema): Schema
->formatStateUsing(fn (?string $state): string => ucfirst((string) $state)) ->formatStateUsing(fn (?string $state): string => ucfirst((string) $state))
->placeholder('—'), ->placeholder('—'),
TextEntry::make('tenant.name') TextEntry::make('tenant.name')
->label('Tenant'), ->label('ManagedEnvironment'),
TextEntry::make('rule.name') TextEntry::make('rule.name')
->label('Rule') ->label('Rule')
->placeholder('—'), ->placeholder('—'),
@ -230,7 +230,7 @@ public static function table(Table $table): Table
->since() ->since()
->sortable(), ->sortable(),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable(), ->searchable(),
TextColumn::make('event_type') TextColumn::make('event_type')
->label('Event') ->label('Event')
@ -257,12 +257,12 @@ public static function table(Table $table): Table
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
]) ])
->filters([ ->filters([
SelectFilter::make('tenant_id') SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(function (): array { ->options(function (): array {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if ($activeTenant instanceof Tenant) { if ($activeTenant instanceof ManagedEnvironment) {
return [ return [
(string) $activeTenant->getKey() => $activeTenant->getFilamentName(), (string) $activeTenant->getKey() => $activeTenant->getFilamentName(),
]; ];
@ -275,7 +275,7 @@ public static function table(Table $table): Table
} }
return collect($user->getTenants(Filament::getCurrentOrDefaultPanel())) return collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->getFilamentName(), (string) $tenant->getKey() => $tenant->getFilamentName(),
]) ])
->all(); ->all();
@ -283,7 +283,7 @@ public static function table(Table $table): Table
->default(function (): ?string { ->default(function (): ?string {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }

View File

@ -8,7 +8,7 @@
use App\Filament\Resources\AlertRuleResource\Pages; use App\Filament\Resources\AlertRuleResource\Pages;
use App\Models\AlertDestination; use App\Models\AlertDestination;
use App\Models\AlertRule; use App\Models\AlertRule;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
use App\Support\Audit\AuditActionId; use App\Support\Audit\AuditActionId;
@ -434,9 +434,9 @@ private static function tenantOptions(): array
return []; return [];
} }
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', $workspaceId) ->where('workspace_id', $workspaceId)
->where('status', 'active') ->where('lifecycle_status', ManagedEnvironment::STATUS_ACTIVE)
->orderBy('name') ->orderBy('name')
->pluck('name', 'id') ->pluck('name', 'id')
->all(); ->all();

View File

@ -9,7 +9,7 @@
use App\Filament\Resources\BackupScheduleResource\RelationManagers\BackupScheduleOperationRunsRelationManager; use App\Filament\Resources\BackupScheduleResource\RelationManagers\BackupScheduleOperationRunsRelationManager;
use App\Jobs\RunBackupScheduleJob; use App\Jobs\RunBackupScheduleJob;
use App\Models\BackupSchedule; use App\Models\BackupSchedule;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Rules\SupportedPolicyTypesRule; use App\Rules\SupportedPolicyTypesRule;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -92,7 +92,7 @@ public static function canViewAny(): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -108,7 +108,7 @@ public static function canView(Model $record): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -120,7 +120,7 @@ public static function canView(Model $record): bool
} }
if ($record instanceof BackupSchedule) { if ($record instanceof BackupSchedule) {
return (int) $record->tenant_id === (int) $tenant->getKey(); return (int) $record->managed_environment_id === (int) $tenant->getKey();
} }
return true; return true;
@ -132,7 +132,7 @@ public static function canCreate(): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -148,7 +148,7 @@ public static function canEdit(Model $record): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -164,7 +164,7 @@ public static function canDelete(Model $record): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -180,7 +180,7 @@ public static function canDeleteAny(): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -440,7 +440,7 @@ public static function table(Table $table): Table
->action(function (BackupSchedule $record, HasTable $livewire): void { ->action(function (BackupSchedule $record, HasTable $livewire): void {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
Notification::make() Notification::make()
->title('No tenant selected') ->title('No tenant selected')
->danger() ->danger()
@ -511,7 +511,7 @@ public static function table(Table $table): Table
->action(function (BackupSchedule $record, HasTable $livewire): void { ->action(function (BackupSchedule $record, HasTable $livewire): void {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
Notification::make() Notification::make()
->title('No tenant selected') ->title('No tenant selected')
->danger() ->danger()
@ -590,7 +590,7 @@ public static function table(Table $table): Table
$record->restore(); $record->restore();
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup_schedule.restored', action: 'backup_schedule.restored',
@ -633,7 +633,7 @@ public static function table(Table $table): Table
$record->delete(); $record->delete();
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup_schedule.archived', action: 'backup_schedule.archived',
@ -685,7 +685,7 @@ public static function table(Table $table): Table
return; return;
} }
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup_schedule.force_deleted', action: 'backup_schedule.force_deleted',
@ -728,7 +728,7 @@ public static function table(Table $table): Table
->action(function (Collection $records, HasTable $livewire): void { ->action(function (Collection $records, HasTable $livewire): void {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
Notification::make() Notification::make()
->title('No tenant selected') ->title('No tenant selected')
->danger() ->danger()
@ -825,7 +825,7 @@ public static function table(Table $table): Table
->action(function (Collection $records, HasTable $livewire): void { ->action(function (Collection $records, HasTable $livewire): void {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
Notification::make() Notification::make()
->title('No tenant selected') ->title('No tenant selected')
->danger() ->danger()
@ -1062,7 +1062,7 @@ public static function ensurePolicyTypes(array $data): array
public static function assignTenant(array $data): array public static function assignTenant(array $data): array
{ {
$data['tenant_id'] = static::resolveTenantContextForCurrentPanelOrFail()->getKey(); $data['managed_environment_id'] = static::resolveTenantContextForCurrentPanelOrFail()->getKey();
return $data; return $data;
} }

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\BackupScheduleResource\Pages; namespace App\Filament\Resources\BackupScheduleResource\Pages;
use App\Filament\Resources\BackupScheduleResource; use App\Filament\Resources\BackupScheduleResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\BackupHealth\TenantBackupHealthAssessment; use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\BackupHealth\TenantBackupHealthResolver; use App\Support\BackupHealth\TenantBackupHealthResolver;
use App\Support\Filament\CanonicalAdminTenantFilterState; use App\Support\Filament\CanonicalAdminTenantFilterState;

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\BackupScheduleResource\RelationManagers; namespace App\Filament\Resources\BackupScheduleResource\RelationManagers;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
use App\Support\OperationCatalog; use App\Support\OperationCatalog;
@ -37,12 +37,12 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
public function table(Table $table): Table public function table(Table $table): Table
{ {
return $table return $table
->modifyQueryUsing(fn (Builder $query) => $query->where('tenant_id', Tenant::currentOrFail()->getKey())) ->modifyQueryUsing(fn (Builder $query) => $query->where('managed_environment_id', ManagedEnvironment::currentOrFail()->getKey()))
->defaultSort('created_at', 'desc') ->defaultSort('created_at', 'desc')
->paginated(\App\Support\Filament\TablePaginationProfiles::relationManager()) ->paginated(\App\Support\Filament\TablePaginationProfiles::relationManager())
->recordUrl(function (OperationRun $record): string { ->recordUrl(function (OperationRun $record): string {
$record = $this->resolveOwnerScopedOperationRun($record); $record = $this->resolveOwnerScopedOperationRun($record);
$tenant = Tenant::currentOrFail(); $tenant = ManagedEnvironment::currentOrFail();
return OperationRunLinks::view($record, $tenant); return OperationRunLinks::view($record, $tenant);
}) })
@ -106,7 +106,7 @@ private function resolveOwnerScopedOperationRun(mixed $record): OperationRun
$resolvedRecord = $this->getOwnerRecord() $resolvedRecord = $this->getOwnerRecord()
->operationRuns() ->operationRuns()
->where('tenant_id', Tenant::currentOrFail()->getKey()) ->where('managed_environment_id', ManagedEnvironment::currentOrFail()->getKey())
->whereKey($recordId) ->whereKey($recordId)
->first(); ->first();

View File

@ -10,7 +10,7 @@
use App\Jobs\BulkBackupSetForceDeleteJob; use App\Jobs\BulkBackupSetForceDeleteJob;
use App\Jobs\BulkBackupSetRestoreJob; use App\Jobs\BulkBackupSetRestoreJob;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
@ -96,7 +96,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -112,7 +112,7 @@ public static function canCreate(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -352,7 +352,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -369,7 +369,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'backup_set.delete', type: 'backup_set.delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -422,7 +422,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -439,7 +439,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'backup_set.restore', type: 'backup_set.restore',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -507,7 +507,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -524,7 +524,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'backup_set.force_delete', type: 'backup_set.force_delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -651,7 +651,7 @@ private static function primaryRelatedEntry(BackupSet $record): ?RelatedContextE
*/ */
public static function createBackupSet(array $data): BackupSet public static function createBackupSet(array $data): BackupSet
{ {
/** @var Tenant $tenant */ /** @var ManagedEnvironment $tenant */
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
/** @var BackupService $service */ /** @var BackupService $service */
@ -846,7 +846,7 @@ private static function backupHealthContinuityAssessment(BackupSet $record): ?Te
/** @var TenantBackupHealthResolver $resolver */ /** @var TenantBackupHealthResolver $resolver */
$resolver = app(TenantBackupHealthResolver::class); $resolver = app(TenantBackupHealthResolver::class);
$assessment = $resolver->assess((int) $record->tenant_id); $assessment = $resolver->assess((int) $record->managed_environment_id);
if ($assessment->latestRelevantBackupSetId !== (int) $record->getKey()) { if ($assessment->latestRelevantBackupSetId !== (int) $record->getKey()) {
return null; return null;

View File

@ -7,7 +7,7 @@
use App\Filament\Concerns\ResolvesPanelTenantContext; use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Resources\BackupSetResource; use App\Filament\Resources\BackupSetResource;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Navigation\CrossResourceNavigationMatrix; use App\Support\Navigation\CrossResourceNavigationMatrix;
@ -72,7 +72,7 @@ private function restoreAction(): Action
$record->restore(); $record->restore();
$record->items()->withTrashed()->restore(); $record->items()->withTrashed()->restore();
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup.restored', action: 'backup.restored',
@ -113,7 +113,7 @@ private function archiveAction(): Action
$record->delete(); $record->delete();
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup.deleted', action: 'backup.deleted',
@ -162,7 +162,7 @@ private function forceDeleteAction(): Action
return; return;
} }
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$auditLogger->log( $auditLogger->log(
tenant: $record->tenant, tenant: $record->tenant,
action: 'backup.force_deleted', action: 'backup.force_deleted',

View File

@ -7,7 +7,7 @@
use App\Jobs\RemovePoliciesFromBackupSetJob; use App\Jobs\RemovePoliciesFromBackupSetJob;
use App\Models\BackupItem; use App\Models\BackupItem;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -122,12 +122,12 @@ public function table(Table $table): Table
abort(403); abort(403);
} }
$tenant = $backupSet->tenant ?? Tenant::current(); $tenant = $backupSet->tenant ?? ManagedEnvironment::current();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
if ((int) $tenant->getKey() !== (int) $backupSet->tenant_id) { if ((int) $tenant->getKey() !== (int) $backupSet->managed_environment_id) {
abort(404); abort(404);
} }
@ -201,12 +201,12 @@ public function table(Table $table): Table
abort(403); abort(403);
} }
$tenant = $backupSet->tenant ?? Tenant::current(); $tenant = $backupSet->tenant ?? ManagedEnvironment::current();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
if ((int) $tenant->getKey() !== (int) $backupSet->tenant_id) { if ((int) $tenant->getKey() !== (int) $backupSet->managed_environment_id) {
abort(404); abort(404);
} }
@ -477,7 +477,7 @@ private function backupItemInspectUrl(BackupItem $record): ?string
$resolvedRecord = $backupSet->items() $resolvedRecord = $backupSet->items()
->with(['policy', 'policyVersion', 'policyVersion.policy']) ->with(['policy', 'policyVersion', 'policyVersion.policy'])
->where('tenant_id', (int) $backupSet->tenant_id) ->where('managed_environment_id', (int) $backupSet->managed_environment_id)
->whereKey($resolvedId) ->whereKey($resolvedId)
->first(); ->first();
@ -485,9 +485,9 @@ private function backupItemInspectUrl(BackupItem $record): ?string
abort(404); abort(404);
} }
$tenant = $backupSet->tenant ?? Tenant::current(); $tenant = $backupSet->tenant ?? ManagedEnvironment::current();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -516,7 +516,7 @@ private function resolveOwnerScopedBackupItemId(BackupSet $backupSet, mixed $rec
} }
$resolvedId = $backupSet->items() $resolvedId = $backupSet->items()
->where('tenant_id', (int) $backupSet->tenant_id) ->where('managed_environment_id', (int) $backupSet->managed_environment_id)
->whereKey($recordId) ->whereKey($recordId)
->value('id'); ->value('id');
@ -545,7 +545,7 @@ private function resolveOwnerScopedBackupItemIdsFromKeys(BackupSet $backupSet, a
} }
$resolvedIds = $backupSet->items() $resolvedIds = $backupSet->items()
->where('tenant_id', (int) $backupSet->tenant_id) ->where('managed_environment_id', (int) $backupSet->managed_environment_id)
->whereIn('id', $requestedIds) ->whereIn('id', $requestedIds)
->pluck('id') ->pluck('id')
->map(fn (mixed $value): int => (int) $value) ->map(fn (mixed $value): int => (int) $value)

View File

@ -10,7 +10,7 @@
use App\Models\BaselineSnapshot; use App\Models\BaselineSnapshot;
use App\Models\BaselineTenantAssignment; use App\Models\BaselineTenantAssignment;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
@ -968,7 +968,7 @@ private static function hasEligibleCompareTarget(BaselineProfile $profile): bool
$tenantIds = BaselineTenantAssignment::query() $tenantIds = BaselineTenantAssignment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->where('baseline_profile_id', (int) $profile->getKey()) ->where('baseline_profile_id', (int) $profile->getKey())
->pluck('tenant_id') ->pluck('managed_environment_id')
->all(); ->all();
if ($tenantIds === []) { if ($tenantIds === []) {
@ -977,11 +977,11 @@ private static function hasEligibleCompareTarget(BaselineProfile $profile): bool
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->whereIn('id', $tenantIds) ->whereIn('id', $tenantIds)
->get(['id']) ->get(['id'])
->contains(fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_SYNC)); ->contains(fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_SYNC));
} }
/** /**

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\BaselineProfileResource; use App\Filament\Resources\BaselineProfileResource;
use App\Models\BaselineProfile; use App\Models\BaselineProfile;
use App\Models\BaselineTenantAssignment; use App\Models\BaselineTenantAssignment;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
@ -77,7 +77,7 @@ private function captureAction(): Action
->modalDescription($modalDescription) ->modalDescription($modalDescription)
->form([ ->form([
Select::make('source_tenant_id') Select::make('source_tenant_id')
->label('Source Tenant') ->label('Source ManagedEnvironment')
->options(fn (): array => $this->getWorkspaceTenantOptions()) ->options(fn (): array => $this->getWorkspaceTenantOptions())
->required() ->required()
->searchable(), ->searchable(),
@ -91,9 +91,9 @@ private function captureAction(): Action
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */
$profile = $this->getRecord(); $profile = $this->getRecord();
$sourceTenant = Tenant::query()->find((int) $data['source_tenant_id']); $sourceTenant = ManagedEnvironment::query()->find((int) $data['source_tenant_id']);
if (! $sourceTenant instanceof Tenant) { if (! $sourceTenant instanceof ManagedEnvironment) {
Notification::make() Notification::make()
->title('Source tenant not found') ->title('Source tenant not found')
->danger() ->danger()
@ -188,7 +188,7 @@ private function compareNowAction(): Action
->modalDescription($modalDescription) ->modalDescription($modalDescription)
->form([ ->form([
Select::make('target_tenant_id') Select::make('target_tenant_id')
->label('Target Tenant') ->label('Target ManagedEnvironment')
->options(fn (): array => $this->getEligibleCompareTenantOptions()) ->options(fn (): array => $this->getEligibleCompareTenantOptions())
->required() ->required()
->searchable(), ->searchable(),
@ -204,9 +204,9 @@ private function compareNowAction(): Action
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */
$profile = $this->getRecord(); $profile = $this->getRecord();
$targetTenant = Tenant::query()->find((int) $data['target_tenant_id']); $targetTenant = ManagedEnvironment::query()->find((int) $data['target_tenant_id']);
if (! $targetTenant instanceof Tenant || (int) $targetTenant->workspace_id !== (int) $profile->workspace_id) { if (! $targetTenant instanceof ManagedEnvironment || (int) $targetTenant->workspace_id !== (int) $profile->workspace_id) {
Notification::make() Notification::make()
->title('Target tenant not found') ->title('Target tenant not found')
->danger() ->danger()
@ -217,13 +217,13 @@ private function compareNowAction(): Action
$assignment = BaselineTenantAssignment::query() $assignment = BaselineTenantAssignment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->where('tenant_id', (int) $targetTenant->getKey()) ->where('managed_environment_id', (int) $targetTenant->getKey())
->where('baseline_profile_id', (int) $profile->getKey()) ->where('baseline_profile_id', (int) $profile->getKey())
->first(); ->first();
if (! $assignment instanceof BaselineTenantAssignment) { if (! $assignment instanceof BaselineTenantAssignment) {
Notification::make() Notification::make()
->title('Tenant not assigned') ->title('ManagedEnvironment not assigned')
->body('This tenant is not assigned to this baseline profile.') ->body('This tenant is not assigned to this baseline profile.')
->warning() ->warning()
->send(); ->send();
@ -384,7 +384,7 @@ private function getWorkspaceTenantOptions(): array
return []; return [];
} }
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', $workspaceId) ->where('workspace_id', $workspaceId)
->orderBy('name') ->orderBy('name')
->pluck('name', 'id') ->pluck('name', 'id')
@ -408,7 +408,7 @@ private function getEligibleCompareTenantOptions(): array
$tenantIds = BaselineTenantAssignment::query() $tenantIds = BaselineTenantAssignment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->where('baseline_profile_id', (int) $profile->getKey()) ->where('baseline_profile_id', (int) $profile->getKey())
->pluck('tenant_id') ->pluck('managed_environment_id')
->all(); ->all();
if ($tenantIds === []) { if ($tenantIds === []) {
@ -419,14 +419,14 @@ private function getEligibleCompareTenantOptions(): array
$options = []; $options = [];
$tenants = Tenant::query() $tenants = ManagedEnvironment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->whereIn('id', $tenantIds) ->whereIn('id', $tenantIds)
->orderBy('name') ->orderBy('name')
->get(['id', 'name']); ->get(['id', 'name']);
foreach ($tenants as $tenant) { foreach ($tenants as $tenant) {
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
continue; continue;
} }
@ -510,7 +510,7 @@ private function visibleAssignedTenantCount(BaselineProfile $profile): int
$tenantIds = BaselineTenantAssignment::query() $tenantIds = BaselineTenantAssignment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->where('baseline_profile_id', (int) $profile->getKey()) ->where('baseline_profile_id', (int) $profile->getKey())
->pluck('tenant_id') ->pluck('managed_environment_id')
->all(); ->all();
if ($tenantIds === []) { if ($tenantIds === []) {
@ -519,11 +519,11 @@ private function visibleAssignedTenantCount(BaselineProfile $profile): int
$resolver = app(CapabilityResolver::class); $resolver = app(CapabilityResolver::class);
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->whereIn('id', $tenantIds) ->whereIn('id', $tenantIds)
->get(['id']) ->get(['id'])
->filter(fn (Tenant $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_VIEW)) ->filter(fn (ManagedEnvironment $tenant): bool => $resolver->can($user, $tenant, Capabilities::TENANT_VIEW))
->count(); ->count();
} }
} }

View File

@ -6,7 +6,7 @@
use App\Models\BaselineProfile; use App\Models\BaselineProfile;
use App\Models\BaselineTenantAssignment; use App\Models\BaselineTenantAssignment;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
@ -27,7 +27,7 @@ class BaselineTenantAssignmentsRelationManager extends RelationManager
{ {
protected static string $relationship = 'tenantAssignments'; protected static string $relationship = 'tenantAssignments';
protected static ?string $title = 'Tenant assignments'; protected static ?string $title = 'ManagedEnvironment assignments';
/** /**
* @var array<int, array{baseline_profile_id:int, baseline_profile_name:string}>|null * @var array<int, array{baseline_profile_id:int, baseline_profile_name:string}>|null
@ -51,7 +51,7 @@ public function table(Table $table): Table
->paginated(\App\Support\Filament\TablePaginationProfiles::relationManager()) ->paginated(\App\Support\Filament\TablePaginationProfiles::relationManager())
->columns([ ->columns([
Tables\Columns\TextColumn::make('tenant.name') Tables\Columns\TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('assignedByUser.name') Tables\Columns\TextColumn::make('assignedByUser.name')
->label('Assigned by') ->label('Assigned by')
@ -78,12 +78,12 @@ public function table(Table $table): Table
private function assignTenantAction(): Action private function assignTenantAction(): Action
{ {
return Action::make('assign') return Action::make('assign')
->label('Assign Tenant') ->label('Assign ManagedEnvironment')
->icon('heroicon-o-plus') ->icon('heroicon-o-plus')
->visible(fn (): bool => $this->hasManageCapability()) ->visible(fn (): bool => $this->hasManageCapability())
->form([ ->form([
Select::make('tenant_id') Select::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(fn (): array => $this->getTenantOptions()) ->options(fn (): array => $this->getTenantOptions())
->disableOptionWhen(fn (string $value): bool => array_key_exists((int) $value, $this->getTenantAssignmentSummaries())) ->disableOptionWhen(fn (string $value): bool => array_key_exists((int) $value, $this->getTenantAssignmentSummaries()))
->required() ->required()
@ -103,18 +103,18 @@ private function assignTenantAction(): Action
/** @var BaselineProfile $profile */ /** @var BaselineProfile $profile */
$profile = $this->getOwnerRecord(); $profile = $this->getOwnerRecord();
$tenantId = (int) $data['tenant_id']; $tenantId = (int) $data['managed_environment_id'];
$existing = BaselineTenantAssignment::query() $existing = BaselineTenantAssignment::query()
->where('workspace_id', $profile->workspace_id) ->where('workspace_id', $profile->workspace_id)
->where('tenant_id', $tenantId) ->where('managed_environment_id', $tenantId)
->first(); ->first();
if ($existing instanceof BaselineTenantAssignment) { if ($existing instanceof BaselineTenantAssignment) {
$assignedBaselineName = $this->getAssignedBaselineNameForTenant($tenantId); $assignedBaselineName = $this->getAssignedBaselineNameForTenant($tenantId);
Notification::make() Notification::make()
->title('Tenant already assigned') ->title('ManagedEnvironment already assigned')
->body($assignedBaselineName === null ->body($assignedBaselineName === null
? 'This tenant already has a baseline assignment in this workspace.' ? 'This tenant already has a baseline assignment in this workspace.'
: "This tenant is already assigned to baseline: {$assignedBaselineName}.") : "This tenant is already assigned to baseline: {$assignedBaselineName}.")
@ -126,7 +126,7 @@ private function assignTenantAction(): Action
$assignment = BaselineTenantAssignment::create([ $assignment = BaselineTenantAssignment::create([
'workspace_id' => (int) $profile->workspace_id, 'workspace_id' => (int) $profile->workspace_id,
'tenant_id' => $tenantId, 'managed_environment_id' => $tenantId,
'baseline_profile_id' => (int) $profile->getKey(), 'baseline_profile_id' => (int) $profile->getKey(),
'assigned_by_user_id' => (int) $user->getKey(), 'assigned_by_user_id' => (int) $user->getKey(),
]); ]);
@ -134,7 +134,7 @@ private function assignTenantAction(): Action
$this->auditAssignment($profile, $assignment, $user, 'created'); $this->auditAssignment($profile, $assignment, $user, 'created');
Notification::make() Notification::make()
->title('Tenant assigned') ->title('ManagedEnvironment assigned')
->success() ->success()
->send(); ->send();
@ -190,11 +190,11 @@ private function getTenantOptions(): array
$assignmentSummaries = $this->getTenantAssignmentSummaries(); $assignmentSummaries = $this->getTenantAssignmentSummaries();
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', $profile->workspace_id) ->where('workspace_id', $profile->workspace_id)
->orderBy('name') ->orderBy('name')
->get(['id', 'name']) ->get(['id', 'name'])
->mapWithKeys(function (Tenant $tenant) use ($assignmentSummaries): array { ->mapWithKeys(function (ManagedEnvironment $tenant) use ($assignmentSummaries): array {
$tenantId = (int) $tenant->getKey(); $tenantId = (int) $tenant->getKey();
$assignmentSummary = $assignmentSummaries[$tenantId] ?? null; $assignmentSummary = $assignmentSummaries[$tenantId] ?? null;
@ -220,12 +220,12 @@ private function getTenantAssignmentSummaries(): array
$this->tenantAssignmentSummaries = BaselineTenantAssignment::query() $this->tenantAssignmentSummaries = BaselineTenantAssignment::query()
->where('workspace_id', (int) $profile->workspace_id) ->where('workspace_id', (int) $profile->workspace_id)
->with('baselineProfile:id,name') ->with('baselineProfile:id,name')
->get(['tenant_id', 'baseline_profile_id']) ->get(['managed_environment_id', 'baseline_profile_id'])
->mapWithKeys(function (BaselineTenantAssignment $assignment): array { ->mapWithKeys(function (BaselineTenantAssignment $assignment): array {
$baselineProfile = $assignment->baselineProfile; $baselineProfile = $assignment->baselineProfile;
return [ return [
(int) $assignment->tenant_id => [ (int) $assignment->managed_environment_id => [
'baseline_profile_id' => (int) $assignment->baseline_profile_id, 'baseline_profile_id' => (int) $assignment->baseline_profile_id,
'baseline_profile_name' => $baselineProfile instanceof BaselineProfile 'baseline_profile_name' => $baselineProfile instanceof BaselineProfile
? (string) $baselineProfile->name ? (string) $baselineProfile->name
@ -242,7 +242,7 @@ private function getTenantAssignmentSummaries(): array
* @param array{baseline_profile_id:int, baseline_profile_name:string}|null $assignmentSummary * @param array{baseline_profile_id:int, baseline_profile_name:string}|null $assignmentSummary
*/ */
private function formatTenantOptionLabel( private function formatTenantOptionLabel(
Tenant $tenant, ManagedEnvironment $tenant,
?array $assignmentSummary, ?array $assignmentSummary,
): string { ): string {
$tenantName = (string) $tenant->name; $tenantName = (string) $tenant->name;
@ -282,7 +282,7 @@ private function auditAssignment(
return; return;
} }
$tenant = Tenant::query()->find($assignment->tenant_id); $tenant = ManagedEnvironment::query()->find($assignment->managed_environment_id);
$auditLogger = app(WorkspaceAuditLogger::class); $auditLogger = app(WorkspaceAuditLogger::class);
@ -292,8 +292,8 @@ private function auditAssignment(
context: [ context: [
'baseline_profile_id' => (int) $profile->getKey(), 'baseline_profile_id' => (int) $profile->getKey(),
'baseline_profile_name' => (string) $profile->name, 'baseline_profile_name' => (string) $profile->name,
'tenant_id' => (int) $assignment->tenant_id, 'managed_environment_id' => (int) $assignment->managed_environment_id,
'tenant_name' => $tenant instanceof Tenant ? (string) $tenant->display_name : '—', 'tenant_name' => $tenant instanceof ManagedEnvironment ? (string) $tenant->display_name : '—',
], ],
actor: $user, actor: $user,
resourceType: 'baseline_profile', resourceType: 'baseline_profile',

View File

@ -7,7 +7,7 @@
use App\Filament\Concerns\ScopesGlobalSearchToTenant; use App\Filament\Concerns\ScopesGlobalSearchToTenant;
use App\Filament\Resources\EntraGroupResource\Pages; use App\Filament\Resources\EntraGroupResource\Pages;
use App\Models\EntraGroup; use App\Models\EntraGroup;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
use App\Support\Filament\TablePaginationProfiles; use App\Support\Filament\TablePaginationProfiles;
@ -204,7 +204,7 @@ public static function resolveScopedRecordOrFail(int|string $key): Model
public static function getGlobalSearchResultUrl(Model $record): string public static function getGlobalSearchResultUrl(Model $record): string
{ {
$tenant = $record instanceof EntraGroup && $record->tenant instanceof Tenant $tenant = $record instanceof EntraGroup && $record->tenant instanceof ManagedEnvironment
? $record->tenant ? $record->tenant
: static::panelTenantContext(); : static::panelTenantContext();
@ -225,7 +225,7 @@ public static function getPages(): array
public static function scopedUrl( public static function scopedUrl(
string $page = 'index', string $page = 'index',
array $parameters = [], array $parameters = [],
?Tenant $tenant = null, ?ManagedEnvironment $tenant = null,
?string $panel = null, ?string $panel = null,
): string { ): string {
$panelId = $panel ?? Filament::getCurrentOrDefaultPanel()?->getId() ?? 'admin'; $panelId = $panel ?? Filament::getCurrentOrDefaultPanel()?->getId() ?? 'admin';

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\EntraGroupResource\Pages; namespace App\Filament\Resources\EntraGroupResource\Pages;
use App\Filament\Resources\EntraGroupResource; use App\Filament\Resources\EntraGroupResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Directory\EntraGroupSyncService; use App\Services\Directory\EntraGroupSyncService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -30,7 +30,7 @@ public function mount(): void
if ( if (
Filament::getCurrentPanel()?->getId() === 'admin' Filament::getCurrentPanel()?->getId() === 'admin'
&& ! EntraGroupResource::panelTenantContext() instanceof Tenant && ! EntraGroupResource::panelTenantContext() instanceof ManagedEnvironment
) { ) {
abort(404); abort(404);
} }
@ -47,7 +47,7 @@ protected function getHeaderActions(): array
->label('Operations') ->label('Operations')
->icon('heroicon-o-clock') ->icon('heroicon-o-clock')
->url(fn (): string => OperationRunLinks::index($tenant)) ->url(fn (): string => OperationRunLinks::index($tenant))
->visible(fn (): bool => $tenant instanceof Tenant), ->visible(fn (): bool => $tenant instanceof ManagedEnvironment),
UiEnforcement::forAction( UiEnforcement::forAction(
Action::make('sync_groups') Action::make('sync_groups')
->label('Sync Groups') ->label('Sync Groups')
@ -57,7 +57,7 @@ protected function getHeaderActions(): array
$user = auth()->user(); $user = auth()->user();
$tenant = EntraGroupResource::panelTenantContext(); $tenant = EntraGroupResource::panelTenantContext();
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
return; return;
} }

View File

@ -4,7 +4,7 @@
use App\Filament\Resources\EntraGroupResource; use App\Filament\Resources\EntraGroupResource;
use App\Models\EntraGroup; use App\Models\EntraGroup;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use Filament\Facades\Filament; use Filament\Facades\Filament;
use Filament\Resources\Pages\ViewRecord; use Filament\Resources\Pages\ViewRecord;
@ -27,16 +27,16 @@ protected function authorizeAccess(): void
if ( if (
Filament::getCurrentPanel()?->getId() === 'admin' Filament::getCurrentPanel()?->getId() === 'admin'
&& ! $tenant instanceof Tenant && ! $tenant instanceof ManagedEnvironment
) { ) {
abort(404); abort(404);
} }
if (! $user instanceof User || ! $tenant instanceof Tenant || ! $record instanceof EntraGroup) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment || ! $record instanceof EntraGroup) {
abort(404); abort(404);
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
abort(404); abort(404);
} }

View File

@ -11,7 +11,7 @@
use App\Filament\Resources\ReviewPackResource; use App\Filament\Resources\ReviewPackResource;
use App\Models\EvidenceSnapshot; use App\Models\EvidenceSnapshot;
use App\Models\EvidenceSnapshotItem; use App\Models\EvidenceSnapshotItem;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Evidence\EvidenceSnapshotService; use App\Services\Evidence\EvidenceSnapshotService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -86,7 +86,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -102,7 +102,7 @@ public static function canView(Model $record): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -111,7 +111,7 @@ public static function canView(Model $record): bool
} }
return ! $record instanceof EvidenceSnapshot return ! $record instanceof EvidenceSnapshot
|| ((int) $record->tenant_id === (int) $tenant->getKey() && (int) $record->workspace_id === (int) $tenant->workspace_id); || ((int) $record->managed_environment_id === (int) $tenant->getKey() && (int) $record->workspace_id === (int) $tenant->workspace_id);
} }
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
@ -167,7 +167,7 @@ public static function infolist(Schema $schema): Schema
->color(BadgeRenderer::color(BadgeDomain::EvidenceCompleteness)) ->color(BadgeRenderer::color(BadgeDomain::EvidenceCompleteness))
->icon(BadgeRenderer::icon(BadgeDomain::EvidenceCompleteness)) ->icon(BadgeRenderer::icon(BadgeDomain::EvidenceCompleteness))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::EvidenceCompleteness)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::EvidenceCompleteness)),
TextEntry::make('tenant.name')->label('Tenant'), TextEntry::make('tenant.name')->label('ManagedEnvironment'),
TextEntry::make('generated_at')->dateTime()->placeholder('—'), TextEntry::make('generated_at')->dateTime()->placeholder('—'),
TextEntry::make('expires_at')->dateTime()->placeholder('—'), TextEntry::make('expires_at')->dateTime()->placeholder('—'),
TextEntry::make('operationRun.id') TextEntry::make('operationRun.id')
@ -258,7 +258,7 @@ public static function relatedContextEntries(EvidenceSnapshot $record): array
->latest('created_at') ->latest('created_at')
->first(); ->first();
if ($pack instanceof \App\Models\ReviewPack && $pack->tenant instanceof Tenant) { if ($pack instanceof \App\Models\ReviewPack && $pack->tenant instanceof ManagedEnvironment) {
$packUrl = ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $pack->tenant); $packUrl = ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $pack->tenant);
if (static::isCustomerWorkspaceFlow()) { if (static::isCustomerWorkspaceFlow()) {
@ -278,7 +278,7 @@ public static function relatedContextEntries(EvidenceSnapshot $record): array
)->toArray(); )->toArray();
} }
if ($record->tenant instanceof Tenant) { if ($record->tenant instanceof ManagedEnvironment) {
$entries[] = RelatedContextEntry::available( $entries[] = RelatedContextEntry::available(
key: 'customer_review_workspace', key: 'customer_review_workspace',
label: 'Customer workspace', label: 'Customer workspace',
@ -783,7 +783,7 @@ public static function executeGeneration(array $data): void
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
Notification::make()->danger()->title('Unable to create snapshot — missing context.')->send(); Notification::make()->danger()->title('Unable to create snapshot — missing context.')->send();
return; return;

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\EvidenceSnapshotResource; use App\Filament\Resources\EvidenceSnapshotResource;
use App\Filament\Pages\Reviews\CustomerReviewWorkspace; use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Models\EvidenceSnapshot; use App\Models\EvidenceSnapshot;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\Evidence\EvidenceSnapshotService; use App\Services\Evidence\EvidenceSnapshotService;
@ -122,7 +122,7 @@ private function auditCustomerWorkspaceProofOpen(): void
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }

View File

@ -10,7 +10,7 @@
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\FindingExceptionEvidenceReference; use App\Models\FindingExceptionEvidenceReference;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Auth\WorkspaceCapabilityResolver; use App\Services\Auth\WorkspaceCapabilityResolver;
@ -82,7 +82,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -98,7 +98,7 @@ public static function canView(Model $record): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -107,7 +107,7 @@ public static function canView(Model $record): bool
} }
return ! $record instanceof FindingException return ! $record instanceof FindingException
|| ((int) $record->tenant_id === (int) $tenant->getKey() && (int) $record->workspace_id === (int) $tenant->workspace_id); || ((int) $record->managed_environment_id === (int) $tenant->getKey() && (int) $record->workspace_id === (int) $tenant->workspace_id);
} }
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
@ -134,12 +134,12 @@ public static function exceptionStatsForCurrentTenant(): array
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return ['active' => 0, 'expiring' => 0, 'expired' => 0, 'pending' => 0, 'total' => 0]; return ['active' => 0, 'expiring' => 0, 'expired' => 0, 'pending' => 0, 'total' => 0];
} }
$counts = FindingException::query() $counts = FindingException::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->where('workspace_id', (int) $tenant->workspace_id) ->where('workspace_id', (int) $tenant->workspace_id)
->selectRaw('count(*) as total') ->selectRaw('count(*) as total')
->selectRaw("count(*) filter (where status = 'active') as active") ->selectRaw("count(*) filter (where status = 'active') as active")
@ -191,7 +191,7 @@ public static function infolist(Schema $schema): Schema
->color(fn (FindingException $record): string => static::governanceWarningColor($record)) ->color(fn (FindingException $record): string => static::governanceWarningColor($record))
->columnSpanFull() ->columnSpanFull()
->visible(fn (FindingException $record): bool => static::governanceWarning($record) !== null), ->visible(fn (FindingException $record): bool => static::governanceWarning($record) !== null),
TextEntry::make('tenant.name')->label('Tenant'), TextEntry::make('tenant.name')->label('ManagedEnvironment'),
TextEntry::make('finding_summary') TextEntry::make('finding_summary')
->label('Finding') ->label('Finding')
->state(fn (FindingException $record): string => static::findingSummary($record)), ->state(fn (FindingException $record): string => static::findingSummary($record)),
@ -264,7 +264,7 @@ public static function relatedContextEntries(FindingException $record): array
{ {
$entries = []; $entries = [];
if ($record->finding && $record->tenant instanceof Tenant) { if ($record->finding && $record->tenant instanceof ManagedEnvironment) {
$entries[] = RelatedContextEntry::available( $entries[] = RelatedContextEntry::available(
key: 'finding', key: 'finding',
label: 'Finding', label: 'Finding',
@ -278,7 +278,7 @@ public static function relatedContextEntries(FindingException $record): array
)->toArray(); )->toArray();
} }
if ($record->tenant instanceof Tenant && static::canAccessApprovalQueueForTenant($record->tenant)) { if ($record->tenant instanceof ManagedEnvironment && static::canAccessApprovalQueueForTenant($record->tenant)) {
$entries[] = RelatedContextEntry::available( $entries[] = RelatedContextEntry::available(
key: 'approval_queue', key: 'approval_queue',
label: 'Approval queue', label: 'Approval queue',
@ -428,7 +428,7 @@ public static function table(Table $table): Table
->action(function (FindingException $record, array $data, FindingExceptionService $service): void { ->action(function (FindingException $record, array $data, FindingExceptionService $service): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User || ! $record->tenant instanceof Tenant) { if (! $user instanceof User || ! $record->tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -532,13 +532,13 @@ private static function tenantMemberOptions(): array
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return \App\Models\TenantMembership::query() return \App\Models\ManagedEnvironmentMembership::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->join('users', 'users.id', '=', 'tenant_memberships.user_id') ->join('users', 'users.id', '=', 'managed_environment_memberships.user_id')
->orderBy('users.name') ->orderBy('users.name')
->pluck('users.name', 'users.id') ->pluck('users.name', 'users.id')
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name]) ->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name])
@ -608,7 +608,7 @@ private static function canManageRecord(FindingException $record): bool
$user = auth()->user(); $user = auth()->user();
return $user instanceof User return $user instanceof User
&& $record->tenant instanceof Tenant && $record->tenant instanceof ManagedEnvironment
&& $user->canAccessTenant($record->tenant) && $user->canAccessTenant($record->tenant)
&& $user->can(Capabilities::FINDING_EXCEPTION_MANAGE, $record->tenant); && $user->can(Capabilities::FINDING_EXCEPTION_MANAGE, $record->tenant);
} }
@ -643,12 +643,12 @@ private static function governanceWarningColor(FindingException $record): string
return 'danger'; return 'danger';
} }
public static function canAccessApprovalQueueForTenant(?Tenant $tenant = null): bool public static function canAccessApprovalQueueForTenant(?ManagedEnvironment $tenant = null): bool
{ {
$tenant ??= static::resolveTenantContextForCurrentPanel(); $tenant ??= static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -665,11 +665,11 @@ public static function canAccessApprovalQueueForTenant(?Tenant $tenant = null):
&& $resolver->can($user, $workspace, Capabilities::FINDING_EXCEPTION_APPROVE); && $resolver->can($user, $workspace, Capabilities::FINDING_EXCEPTION_APPROVE);
} }
public static function approvalQueueUrl(?Tenant $tenant = null): ?string public static function approvalQueueUrl(?ManagedEnvironment $tenant = null): ?string
{ {
$tenant ??= static::resolveTenantContextForCurrentPanel(); $tenant ??= static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\FindingExceptionResource; use App\Filament\Resources\FindingExceptionResource;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Findings\FindingExceptionService; use App\Services\Findings\FindingExceptionService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -198,13 +198,13 @@ private function tenantMemberOptions(): array
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return \App\Models\TenantMembership::query() return \App\Models\ManagedEnvironmentMembership::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->join('users', 'users.id', '=', 'tenant_memberships.user_id') ->join('users', 'users.id', '=', 'managed_environment_memberships.user_id')
->orderBy('users.name') ->orderBy('users.name')
->pluck('users.name', 'users.id') ->pluck('users.name', 'users.id')
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name]) ->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name])
@ -217,7 +217,7 @@ private function canManageRecord(): bool
$user = auth()->user(); $user = auth()->user();
return $record instanceof FindingException return $record instanceof FindingException
&& $record->tenant instanceof Tenant && $record->tenant instanceof ManagedEnvironment
&& $user instanceof User && $user instanceof User
&& $user->canAccessTenant($record->tenant) && $user->canAccessTenant($record->tenant)
&& $user->can(Capabilities::FINDING_EXCEPTION_MANAGE, $record->tenant); && $user->can(Capabilities::FINDING_EXCEPTION_MANAGE, $record->tenant);

View File

@ -9,8 +9,8 @@
use App\Models\Finding; use App\Models\Finding;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\PolicyVersion; use App\Models\PolicyVersion;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantMembership; use App\Models\ManagedEnvironmentMembership;
use App\Models\User; use App\Models\User;
use App\Services\Drift\DriftFindingDiffBuilder; use App\Services\Drift\DriftFindingDiffBuilder;
use App\Services\Findings\FindingExceptionService; use App\Services\Findings\FindingExceptionService;
@ -110,7 +110,7 @@ public static function canViewAny(): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -127,7 +127,7 @@ public static function canView(Model $record): bool
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -140,7 +140,7 @@ public static function canView(Model $record): bool
} }
if ($record instanceof Finding) { if ($record instanceof Finding) {
return (int) $record->tenant_id === (int) $tenant->getKey() return (int) $record->managed_environment_id === (int) $tenant->getKey()
&& (int) $record->workspace_id === (int) $tenant->workspace_id; && (int) $record->workspace_id === (int) $tenant->workspace_id;
} }
@ -679,17 +679,17 @@ private static function driftDiffUnavailableMessage(Finding $record): string
/** /**
* @return array{0: ?PolicyVersion, 1: ?PolicyVersion} * @return array{0: ?PolicyVersion, 1: ?PolicyVersion}
*/ */
private static function resolveDriftDiffVersions(Finding $record, Tenant $tenant): array private static function resolveDriftDiffVersions(Finding $record, ManagedEnvironment $tenant): array
{ {
$baselineId = Arr::get($record->evidence_jsonb ?? [], 'baseline.policy_version_id'); $baselineId = Arr::get($record->evidence_jsonb ?? [], 'baseline.policy_version_id');
$currentId = Arr::get($record->evidence_jsonb ?? [], 'current.policy_version_id'); $currentId = Arr::get($record->evidence_jsonb ?? [], 'current.policy_version_id');
$baselineVersion = is_numeric($baselineId) $baselineVersion = is_numeric($baselineId)
? PolicyVersion::query()->where('tenant_id', $tenant->getKey())->find((int) $baselineId) ? PolicyVersion::query()->where('managed_environment_id', $tenant->getKey())->find((int) $baselineId)
: null; : null;
$currentVersion = is_numeric($currentId) $currentVersion = is_numeric($currentId)
? PolicyVersion::query()->where('tenant_id', $tenant->getKey())->find((int) $currentId) ? PolicyVersion::query()->where('managed_environment_id', $tenant->getKey())->find((int) $currentId)
: null; : null;
return [$baselineVersion, $currentVersion]; return [$baselineVersion, $currentVersion];
@ -974,7 +974,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -989,7 +989,7 @@ public static function table(Table $table): Table
continue; continue;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
$skippedCount++; $skippedCount++;
continue; continue;
@ -1057,7 +1057,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1076,7 +1076,7 @@ public static function table(Table $table): Table
continue; continue;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
$skippedCount++; $skippedCount++;
continue; continue;
@ -1149,7 +1149,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1166,7 +1166,7 @@ public static function table(Table $table): Table
continue; continue;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
$skippedCount++; $skippedCount++;
continue; continue;
@ -1228,7 +1228,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1245,7 +1245,7 @@ public static function table(Table $table): Table
continue; continue;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
$skippedCount++; $skippedCount++;
continue; continue;
@ -1369,9 +1369,9 @@ private static function findingRunNavigationContext(Finding $record): CanonicalN
tenantId: $tenant?->getKey(), tenantId: $tenant?->getKey(),
backLinkLabel: 'Back to finding', backLinkLabel: 'Back to finding',
backLinkUrl: static::getUrl('view', ['record' => $record], tenant: $tenant), backLinkUrl: static::getUrl('view', ['record' => $record], tenant: $tenant),
filterPayload: $tenant instanceof Tenant ? [ filterPayload: $tenant instanceof ManagedEnvironment ? [
'tableFilters' => [ 'tableFilters' => [
'tenant_id' => ['value' => (string) $tenant->getKey()], 'managed_environment_id' => ['value' => (string) $tenant->getKey()],
], ],
] : [], ] : [],
); );
@ -1418,7 +1418,7 @@ public static function triageAction(): Actions\Action
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: 'Finding triaged', successTitle: 'Finding triaged',
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->triage($finding, $tenant, $user), callback: fn (Finding $finding, ManagedEnvironment $tenant, User $user): Finding => $workflow->triage($finding, $tenant, $user),
); );
}) })
) )
@ -1442,7 +1442,7 @@ public static function startProgressAction(): Actions\Action
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: 'Finding moved to in progress', successTitle: 'Finding moved to in progress',
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->startProgress($finding, $tenant, $user), callback: fn (Finding $finding, ManagedEnvironment $tenant, User $user): Finding => $workflow->startProgress($finding, $tenant, $user),
); );
}) })
) )
@ -1514,7 +1514,7 @@ public static function resolveAction(): Actions\Action
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: $rule->successTitle, successTitle: $rule->successTitle,
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->resolve( callback: fn (Finding $finding, ManagedEnvironment $tenant, User $user): Finding => $workflow->resolve(
$finding, $finding,
$tenant, $tenant,
$user, $user,
@ -1555,7 +1555,7 @@ public static function closeAction(): Actions\Action
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: $rule->successTitle, successTitle: $rule->successTitle,
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->close( callback: fn (Finding $finding, ManagedEnvironment $tenant, User $user): Finding => $workflow->close(
$finding, $finding,
$tenant, $tenant,
$user, $user,
@ -1760,7 +1760,7 @@ public static function reopenAction(): Actions\Action
static::runWorkflowMutation( static::runWorkflowMutation(
record: $record, record: $record,
successTitle: $rule->successTitle, successTitle: $rule->successTitle,
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->reopen( callback: fn (Finding $finding, ManagedEnvironment $tenant, User $user): Finding => $workflow->reopen(
$finding, $finding,
$tenant, $tenant,
$user, $user,
@ -1776,7 +1776,7 @@ public static function reopenAction(): Actions\Action
} }
/** /**
* @param callable(Finding, Tenant, User): Finding $callback * @param callable(Finding, ManagedEnvironment, User): Finding $callback
*/ */
private static function runWorkflowMutation(Finding $record, string $successTitle, callable $callback): void private static function runWorkflowMutation(Finding $record, string $successTitle, callable $callback): void
{ {
@ -1785,11 +1785,11 @@ private static function runWorkflowMutation(Finding $record, string $successTitl
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
Notification::make() Notification::make()
->title('Finding belongs to a different tenant') ->title('Finding belongs to a different tenant')
->danger() ->danger()
@ -1837,11 +1837,11 @@ private static function runResponsibilityMutation(Finding $record, array $data,
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
Notification::make() Notification::make()
->title('Finding belongs to a different tenant') ->title('Finding belongs to a different tenant')
->danger() ->danger()
@ -1906,7 +1906,7 @@ private static function runExceptionRequestMutation(Finding $record, array $data
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1942,7 +1942,7 @@ private static function runExceptionRenewalMutation(Finding $record, array $data
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1978,7 +1978,7 @@ private static function runExceptionRevocationMutation(Finding $record, array $d
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -2074,7 +2074,7 @@ private static function resolveCurrentFindingExceptionOrFail(Finding $record): F
return $exception; return $exception;
} }
private static function findingExceptionViewUrl(\App\Models\FindingException $exception, Tenant $tenant): string private static function findingExceptionViewUrl(\App\Models\FindingException $exception, ManagedEnvironment $tenant): string
{ {
$panelId = Filament::getCurrentPanel()?->getId(); $panelId = Filament::getCurrentPanel()?->getId();
@ -2388,13 +2388,13 @@ private static function tenantMemberOptions(): array
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return TenantMembership::query() return ManagedEnvironmentMembership::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->join('users', 'users.id', '=', 'tenant_memberships.user_id') ->join('users', 'users.id', '=', 'managed_environment_memberships.user_id')
->orderBy('users.name') ->orderBy('users.name')
->pluck('users.name', 'users.id') ->pluck('users.name', 'users.id')
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name]) ->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name])
@ -2408,14 +2408,14 @@ public static function findingStatsForCurrentTenant(): array
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return ['open' => 0, 'overdue' => 0, 'high_severity' => 0, 'risk_accepted' => 0, 'total' => 0]; return ['open' => 0, 'overdue' => 0, 'high_severity' => 0, 'risk_accepted' => 0, 'total' => 0];
} }
$now = now()->toDateTimeString(); $now = now()->toDateTimeString();
$counts = Finding::query() $counts = Finding::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->selectRaw('count(*) as total') ->selectRaw('count(*) as total')
->selectRaw("sum(case when status in ('new', 'triaged', 'in_progress', 'reopened') then 1 else 0 end) as open") ->selectRaw("sum(case when status in ('new', 'triaged', 'in_progress', 'reopened') then 1 else 0 end) as open")
->selectRaw("sum(case when status in ('new', 'triaged', 'in_progress', 'reopened') and due_at is not null and due_at < ? then 1 else 0 end) as overdue", [$now]) ->selectRaw("sum(case when status in ('new', 'triaged', 'in_progress', 'reopened') and due_at is not null and due_at < ? then 1 else 0 end) as overdue", [$now])

View File

@ -7,7 +7,7 @@
use App\Filament\Widgets\Tenant\BaselineCompareCoverageBanner; use App\Filament\Widgets\Tenant\BaselineCompareCoverageBanner;
use App\Filament\Widgets\Tenant\FindingStatsOverview; use App\Filament\Widgets\Tenant\FindingStatsOverview;
use App\Models\Finding; use App\Models\Finding;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Findings\FindingWorkflowService; use App\Services\Findings\FindingWorkflowService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -152,7 +152,7 @@ protected function getHeaderActions(): array
abort(403); abort(403);
} }
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }

View File

@ -7,7 +7,7 @@
use App\Filament\Concerns\ResolvesPanelTenantContext; use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Resources\InventoryItemResource\Pages; use App\Filament\Resources\InventoryItemResource\Pages;
use App\Models\InventoryItem; use App\Models\InventoryItem;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -76,7 +76,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -91,7 +91,7 @@ public static function canView(Model $record): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -106,7 +106,7 @@ public static function canView(Model $record): bool
} }
if ($record instanceof InventoryItem) { if ($record instanceof InventoryItem) {
return (int) $record->tenant_id === (int) $tenant->getKey(); return (int) $record->managed_environment_id === (int) $tenant->getKey();
} }
return true; return true;
@ -151,7 +151,7 @@ public static function infolist(Schema $schema): Schema
$tenant = $record->tenant; $tenant = $record->tenant;
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return OperationRunLinks::view((int) $record->last_seen_operation_run_id, $tenant); return OperationRunLinks::view((int) $record->last_seen_operation_run_id, $tenant);
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Resources\InventoryItemResource; use App\Filament\Resources\InventoryItemResource;
use App\Filament\Widgets\Inventory\InventoryKpiHeader; use App\Filament\Widgets\Inventory\InventoryKpiHeader;
use App\Jobs\RunInventorySyncJob; use App\Jobs\RunInventorySyncJob;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use App\Services\Inventory\InventorySyncService; use App\Services\Inventory\InventorySyncService;
@ -49,7 +49,7 @@ public function mount(): void
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
app(WorkspaceContext::class)->rememberTenantContext($tenant, request()); app(WorkspaceContext::class)->rememberTenantContext($tenant, request());
} }
@ -128,7 +128,7 @@ protected function getHeaderActions(): array
->dehydrated() ->dehydrated()
->rules(['boolean']) ->rules(['boolean'])
->columnSpanFull(), ->columnSpanFull(),
Hidden::make('tenant_id') Hidden::make('managed_environment_id')
->default(fn (): ?string => static::resolveTenantContextForCurrentPanel()?->getKey()) ->default(fn (): ?string => static::resolveTenantContextForCurrentPanel()?->getKey())
->dehydrated(), ->dehydrated(),
]) ])
@ -139,7 +139,7 @@ protected function getHeaderActions(): array
} }
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return false; return false;
} }
@ -149,11 +149,11 @@ protected function getHeaderActions(): array
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
$requestedTenantId = $data['tenant_id'] ?? null; $requestedTenantId = $data['managed_environment_id'] ?? null;
if ($requestedTenantId !== null && (int) $requestedTenantId !== (int) $tenant->getKey()) { if ($requestedTenantId !== null && (int) $requestedTenantId !== (int) $tenant->getKey()) {
Notification::make() Notification::make()
->title('Not allowed') ->title('Not allowed')

View File

@ -4,7 +4,7 @@
use App\Filament\Concerns\ResolvesPanelTenantContext; use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Resources\InventoryItemResource; use App\Filament\Resources\InventoryItemResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
use Filament\Resources\Pages\ViewRecord; use Filament\Resources\Pages\ViewRecord;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@ -19,7 +19,7 @@ public function mount(int|string $record): void
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
app(WorkspaceContext::class)->rememberTenantContext($tenant, request()); app(WorkspaceContext::class)->rememberTenantContext($tenant, request());
} }

View File

@ -6,7 +6,7 @@
use App\Filament\Support\VerificationReportViewer; use App\Filament\Support\VerificationReportViewer;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\RestoreRun; use App\Models\RestoreRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\VerificationCheckAcknowledgement; use App\Models\VerificationCheckAcknowledgement;
use App\Support\Badges\BadgeCatalog; use App\Support\Badges\BadgeCatalog;
@ -175,8 +175,8 @@ public static function table(Table $table): Table
->description(fn (OperationRun $record): ?string => static::surfaceGuidance($record)), ->description(fn (OperationRun $record): ?string => static::surfaceGuidance($record)),
]) ])
->filters([ ->filters([
Tables\Filters\SelectFilter::make('tenant_id') Tables\Filters\SelectFilter::make('managed_environment_id')
->label('Tenant') ->label('ManagedEnvironment')
->options(function (): array { ->options(function (): array {
$user = auth()->user(); $user = auth()->user();
@ -185,7 +185,7 @@ public static function table(Table $table): Table
} }
return collect($user->getTenants(Filament::getCurrentOrDefaultPanel())) return collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
->mapWithKeys(static fn (Tenant $tenant): array => [ ->mapWithKeys(static fn (ManagedEnvironment $tenant): array => [
(string) $tenant->getKey() => $tenant->getFilamentName(), (string) $tenant->getKey() => $tenant->getFilamentName(),
]) ])
->all(); ->all();
@ -193,7 +193,7 @@ public static function table(Table $table): Table
->default(function (): ?string { ->default(function (): ?string {
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if (! $activeTenant instanceof Tenant) { if (! $activeTenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -278,7 +278,7 @@ private static function enterpriseDetailPage(OperationRun $record): \App\Support
$outcomeSpec = BadgeRenderer::spec(BadgeDomain::OperationRunOutcome, static::outcomeBadgeState($record)); $outcomeSpec = BadgeRenderer::spec(BadgeDomain::OperationRunOutcome, static::outcomeBadgeState($record));
$targetScope = static::targetScopeDisplay($record) ?? 'No target scope details were recorded for this operation.'; $targetScope = static::targetScopeDisplay($record) ?? 'No target scope details were recorded for this operation.';
$summaryLine = \App\Support\OpsUx\SummaryCountsNormalizer::renderSummaryLine(is_array($record->summary_counts) ? $record->summary_counts : []); $summaryLine = \App\Support\OpsUx\SummaryCountsNormalizer::renderSummaryLine(is_array($record->summary_counts) ? $record->summary_counts : []);
$referencedTenantLifecycle = $record->tenant instanceof Tenant $referencedTenantLifecycle = $record->tenant instanceof ManagedEnvironment
? ReferencedTenantLifecyclePresentation::forOperationRun($record->tenant) ? ReferencedTenantLifecyclePresentation::forOperationRun($record->tenant)
: null; : null;
$artifactTruth = static::artifactTruthEnvelope($record); $artifactTruth = static::artifactTruthEnvelope($record);
@ -520,7 +520,7 @@ private static function enterpriseDetailPage(OperationRun $record): \App\Support
entries: [ entries: [
$factory->keyFact('Identity hash', $record->run_identity_hash, mono: true), $factory->keyFact('Identity hash', $record->run_identity_hash, mono: true),
$factory->keyFact('Workspace scope', $record->workspace_id), $factory->keyFact('Workspace scope', $record->workspace_id),
$factory->keyFact('Tenant scope', $record->tenant_id), $factory->keyFact('ManagedEnvironment scope', $record->managed_environment_id),
], ],
description: 'Stored run context stays available for debugging without dominating the default reading path.', description: 'Stored run context stays available for debugging without dominating the default reading path.',
view: 'filament.infolists.entries.snapshot-json', view: 'filament.infolists.entries.snapshot-json',
@ -620,7 +620,7 @@ private static function supportingGroups(
$lifecycleItems = array_values(array_filter([ $lifecycleItems = array_values(array_filter([
$referencedTenantLifecycle !== null $referencedTenantLifecycle !== null
? $factory->keyFact( ? $factory->keyFact(
'Tenant lifecycle', 'ManagedEnvironment lifecycle',
$referencedTenantLifecycle->presentation->label, $referencedTenantLifecycle->presentation->label,
badge: $factory->statusBadge( badge: $factory->statusBadge(
$referencedTenantLifecycle->presentation->label, $referencedTenantLifecycle->presentation->label,
@ -631,7 +631,7 @@ private static function supportingGroups(
) )
: null, : null,
$referencedTenantLifecycle?->selectorAvailabilityMessage() !== null $referencedTenantLifecycle?->selectorAvailabilityMessage() !== null
? $factory->keyFact('Tenant selector context', $referencedTenantLifecycle->selectorAvailabilityMessage()) ? $factory->keyFact('ManagedEnvironment selector context', $referencedTenantLifecycle->selectorAvailabilityMessage())
: null, : null,
$referencedTenantLifecycle?->contextNote !== null $referencedTenantLifecycle?->contextNote !== null
? $factory->keyFact('Viewer context', $referencedTenantLifecycle->contextNote) ? $factory->keyFact('Viewer context', $referencedTenantLifecycle->contextNote)
@ -1266,13 +1266,13 @@ private static function verificationReportViewData(OperationRun $record): array
if ($changeIndicator !== null) { if ($changeIndicator !== null) {
$tenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $tenant = app(OperateHubShell::class)->activeEntitledTenant(request());
$previousRunUrl = $tenant instanceof Tenant $previousRunUrl = $tenant instanceof ManagedEnvironment
? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant) ? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant)
: OperationRunLinks::tenantlessView($changeIndicator['previous_report_id']); : OperationRunLinks::tenantlessView($changeIndicator['previous_report_id']);
} }
$acknowledgements = VerificationCheckAcknowledgement::query() $acknowledgements = VerificationCheckAcknowledgement::query()
->where('tenant_id', (int) ($record->tenant_id ?? 0)) ->where('managed_environment_id', (int) ($record->managed_environment_id ?? 0))
->where('workspace_id', (int) ($record->workspace_id ?? 0)) ->where('workspace_id', (int) ($record->workspace_id ?? 0))
->where('operation_run_id', (int) $record->getKey()) ->where('operation_run_id', (int) $record->getKey())
->with('acknowledgedByUser') ->with('acknowledgedByUser')
@ -1605,7 +1605,7 @@ public static function restoreContinuation(OperationRun $record): ?array
$attention = app(RestoreSafetyResolver::class)->resultAttentionForRun($restoreRun); $attention = app(RestoreSafetyResolver::class)->resultAttentionForRun($restoreRun);
$tenant = $record->tenant; $tenant = $record->tenant;
$user = auth()->user(); $user = auth()->user();
$canOpenRestore = $tenant instanceof Tenant $canOpenRestore = $tenant instanceof ManagedEnvironment
&& $user instanceof User && $user instanceof User
&& app(\App\Services\Auth\CapabilityResolver::class)->isMember($user, $tenant); && app(\App\Services\Auth\CapabilityResolver::class)->isMember($user, $tenant);

View File

@ -13,7 +13,7 @@
use App\Jobs\BulkPolicyUnignoreJob; use App\Jobs\BulkPolicyUnignoreJob;
use App\Jobs\SyncPoliciesJob; use App\Jobs\SyncPoliciesJob;
use App\Models\Policy; use App\Models\Policy;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\PolicyNormalizer; use App\Services\Intune\PolicyNormalizer;
@ -96,7 +96,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -132,7 +132,7 @@ public static function makeSyncAction(string $name = 'sync'): Actions\Action
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -533,7 +533,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -565,7 +565,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy.export', type: 'policy.export',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data): void { dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data): void {
@ -610,7 +610,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -722,7 +722,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -756,7 +756,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy.export', type: 'policy.export',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data, $count): void { dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data, $count): void {
@ -816,7 +816,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -889,7 +889,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -909,7 +909,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy.unignore', type: 'policy.unignore',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $user, $ids, $count): void { dispatcher: function ($operationRun) use ($tenant, $user, $ids, $count): void {
@ -985,7 +985,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1001,7 +1001,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy.delete', type: 'policy.delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $user, $ids): void { dispatcher: function ($operationRun) use ($tenant, $user, $ids): void {

View File

@ -97,7 +97,7 @@ private function makeCaptureSnapshotAction(): Action
tenant: $tenant, tenant: $tenant,
type: 'policy.capture_snapshot', type: 'policy.capture_snapshot',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $policy, $user, $includeAssignments, $includeScopeTags): void { dispatcher: function ($operationRun) use ($tenant, $policy, $user, $includeAssignments, $includeScopeTags): void {

View File

@ -7,7 +7,7 @@
use App\Filament\Resources\RestoreRunResource; use App\Filament\Resources\RestoreRunResource;
use App\Models\Policy; use App\Models\Policy;
use App\Models\PolicyVersion; use App\Models\PolicyVersion;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\RestoreService; use App\Services\Intune\RestoreService;
@ -75,7 +75,7 @@ public function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
Notification::make() Notification::make()
->title($this->text('relation.missing_context_title')) ->title($this->text('relation.missing_context_title'))
->danger() ->danger()
@ -84,7 +84,7 @@ public function table(Table $table): Table
return; return;
} }
if ($record->tenant_id !== $tenant->id) { if ($record->managed_environment_id !== $tenant->id) {
Notification::make() Notification::make()
->title($this->text('versions.different_tenant_title')) ->title($this->text('versions.different_tenant_title'))
->danger() ->danger()
@ -132,7 +132,7 @@ public function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return true; return true;
} }
@ -152,7 +152,7 @@ public function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return null; return null;
} }
@ -205,7 +205,7 @@ private function resolveOwnerScopedVersionRecord(Policy $policy, mixed $record):
} }
$resolvedRecord = $policy->versions() $resolvedRecord = $policy->versions()
->where('tenant_id', (int) $policy->tenant_id) ->where('managed_environment_id', (int) $policy->managed_environment_id)
->whereKey($recordId) ->whereKey($recordId)
->first(); ->first();

View File

@ -14,7 +14,7 @@
use App\Models\BackupItem; use App\Models\BackupItem;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\PolicyVersion; use App\Models\PolicyVersion;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
@ -94,7 +94,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -321,7 +321,7 @@ public static function table(Table $table): Table
$retentionDays = (int) ($data['retention_days'] ?? 90); $retentionDays = (int) ($data['retention_days'] ?? 90);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -342,7 +342,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy_version.prune', type: 'policy_version.prune',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids, $retentionDays): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids, $retentionDays): void {
@ -398,7 +398,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -419,7 +419,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy_version.restore', type: 'policy_version.restore',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -482,7 +482,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = $records->pluck('id')->toArray(); $ids = $records->pluck('id')->toArray();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -503,7 +503,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'policy_version.force_delete', type: 'policy_version.force_delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -607,7 +607,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -624,7 +624,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return true; return true;
} }
@ -641,7 +641,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return null; return null;
} }
@ -666,7 +666,7 @@ public static function table(Table $table): Table
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
abort(403); abort(403);
} }
@ -691,7 +691,7 @@ public static function table(Table $table): Table
return; return;
} }
if (! $tenant || $record->tenant_id !== $tenant->id) { if (! $tenant || $record->managed_environment_id !== $tenant->id) {
Notification::make() Notification::make()
->title(static::text('versions.different_tenant_title')) ->title(static::text('versions.different_tenant_title'))
->danger() ->danger()
@ -712,7 +712,7 @@ public static function table(Table $table): Table
} }
$backupSet = BackupSet::create([ $backupSet = BackupSet::create([
'tenant_id' => $tenant->id, 'managed_environment_id' => $tenant->id,
'name' => static::text('versions.backup_set_name', [ 'name' => static::text('versions.backup_set_name', [
'policy' => $policy->display_name, 'policy' => $policy->display_name,
'version' => $record->version_number, 'version' => $record->version_number,
@ -770,7 +770,7 @@ public static function table(Table $table): Table
} }
$backupItem = BackupItem::create([ $backupItem = BackupItem::create([
'tenant_id' => $tenant->id, 'managed_environment_id' => $tenant->id,
'backup_set_id' => $backupSet->id, 'backup_set_id' => $backupSet->id,
'policy_id' => $policy->id, 'policy_id' => $policy->id,
'policy_version_id' => $record->id, 'policy_version_id' => $record->id,
@ -803,7 +803,7 @@ public static function table(Table $table): Table
$user = auth()->user(); $user = auth()->user();
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
abort(403); abort(403);
} }
@ -845,7 +845,7 @@ public static function table(Table $table): Table
$user = auth()->user(); $user = auth()->user();
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
abort(403); abort(403);
} }
@ -888,7 +888,7 @@ public static function table(Table $table): Table
$user = auth()->user(); $user = auth()->user();
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
abort(403); abort(403);
} }

View File

@ -8,7 +8,7 @@
use App\Jobs\ProviderInventorySyncJob; use App\Jobs\ProviderInventorySyncJob;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
@ -99,7 +99,7 @@ public static function canCreate(): bool
$tenant = static::resolveTenantForCreate(); $tenant = static::resolveTenantForCreate();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -115,7 +115,7 @@ protected static function hasTenantCapability(string $capability): bool
$tenant = static::resolveScopedTenant(); $tenant = static::resolveScopedTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -126,7 +126,7 @@ protected static function hasTenantCapability(string $capability): bool
&& $resolver->can($user, $tenant, $capability); && $resolver->can($user, $tenant, $capability);
} }
protected static function resolveScopedTenant(): ?Tenant protected static function resolveScopedTenant(): ?ManagedEnvironment
{ {
$tenantExternalId = static::resolveRequestedTenantExternalId(); $tenantExternalId = static::resolveRequestedTenantExternalId();
@ -136,19 +136,19 @@ protected static function resolveScopedTenant(): ?Tenant
$routeTenant = request()->route('tenant'); $routeTenant = request()->route('tenant');
if ($routeTenant instanceof Tenant) { if ($routeTenant instanceof ManagedEnvironment) {
return $routeTenant; return $routeTenant;
} }
if (is_string($routeTenant) && $routeTenant !== '') { if (is_string($routeTenant) && $routeTenant !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $routeTenant) ->where('slug', $routeTenant)
->first(); ->first();
} }
$recordTenant = static::resolveTenantFromRouteRecord(); $recordTenant = static::resolveTenantFromRouteRecord();
if ($recordTenant instanceof Tenant) { if ($recordTenant instanceof ManagedEnvironment) {
return $recordTenant; return $recordTenant;
} }
@ -161,16 +161,16 @@ protected static function resolveScopedTenant(): ?Tenant
return static::resolveTenantContextForCurrentPanel(); return static::resolveTenantContextForCurrentPanel();
} }
public static function resolveTenantForRecord(?ProviderConnection $record = null): ?Tenant public static function resolveTenantForRecord(?ProviderConnection $record = null): ?ManagedEnvironment
{ {
if ($record instanceof ProviderConnection) { if ($record instanceof ProviderConnection) {
$tenant = $record->tenant; $tenant = $record->tenant;
if (! $tenant instanceof Tenant && is_numeric($record->tenant_id)) { if (! $tenant instanceof ManagedEnvironment && is_numeric($record->managed_environment_id)) {
$tenant = Tenant::query()->whereKey((int) $record->tenant_id)->first(); $tenant = ManagedEnvironment::query()->whereKey((int) $record->managed_environment_id)->first();
} }
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return $tenant; return $tenant;
} }
} }
@ -180,7 +180,7 @@ public static function resolveTenantForRecord(?ProviderConnection $record = null
public static function resolveRequestedTenantExternalId(): ?string public static function resolveRequestedTenantExternalId(): ?string
{ {
$queryTenant = request()->query('tenant_id'); $queryTenant = request()->query('managed_environment_id');
if (is_string($queryTenant) && $queryTenant !== '') { if (is_string($queryTenant) && $queryTenant !== '') {
return $queryTenant; return $queryTenant;
@ -195,26 +195,26 @@ public static function resolveContextTenantExternalId(): ?string
$contextTenantId = app(WorkspaceContext::class)->lastTenantId(request()); $contextTenantId = app(WorkspaceContext::class)->lastTenantId(request());
if ($workspaceId !== null && $contextTenantId !== null) { if ($workspaceId !== null && $contextTenantId !== null) {
$tenant = Tenant::query() $tenant = ManagedEnvironment::query()
->whereKey($contextTenantId) ->whereKey($contextTenantId)
->where('workspace_id', (int) $workspaceId) ->where('workspace_id', (int) $workspaceId)
->first(); ->first();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return (string) $tenant->external_id; return (string) $tenant->external_id;
} }
} }
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return (string) $tenant->external_id; return (string) $tenant->external_id;
} }
return null; return null;
} }
public static function resolveTenantForCreate(): ?Tenant public static function resolveTenantForCreate(): ?ManagedEnvironment
{ {
$tenantExternalId = static::resolveRequestedTenantExternalId() ?? static::resolveContextTenantExternalId(); $tenantExternalId = static::resolveRequestedTenantExternalId() ?? static::resolveContextTenantExternalId();
@ -226,7 +226,7 @@ public static function resolveTenantForCreate(): ?Tenant
$user = auth()->user(); $user = auth()->user();
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request()); $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
if (! $tenant instanceof Tenant || ! $user instanceof User || $workspaceId === null) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || $workspaceId === null) {
return null; return null;
} }
@ -277,7 +277,7 @@ private static function extractTenantExternalIdFromUrl(string $url): ?string
if (is_string($query) && $query !== '') { if (is_string($query) && $query !== '') {
parse_str($query, $queryParams); parse_str($query, $queryParams);
$tenantExternalId = $queryParams['tenant_id'] ?? null; $tenantExternalId = $queryParams['managed_environment_id'] ?? null;
if (is_string($tenantExternalId) && $tenantExternalId !== '') { if (is_string($tenantExternalId) && $tenantExternalId !== '') {
return $tenantExternalId; return $tenantExternalId;
@ -297,18 +297,18 @@ private static function extractTenantExternalIdFromUrl(string $url): ?string
return (string) $matches[1]; return (string) $matches[1];
} }
private static function resolveTenantByExternalId(?string $externalId): ?Tenant private static function resolveTenantByExternalId(?string $externalId): ?ManagedEnvironment
{ {
if (! is_string($externalId) || $externalId === '') { if (! is_string($externalId) || $externalId === '') {
return null; return null;
} }
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $externalId) ->where('slug', $externalId)
->first(); ->first();
} }
private static function resolveTenantFromRouteRecord(): ?Tenant private static function resolveTenantFromRouteRecord(): ?ManagedEnvironment
{ {
$record = request()->route('record'); $record = request()->route('record');
@ -340,7 +340,7 @@ private static function applyMembershipScope(Builder $query): Builder
if (! is_int($workspaceId)) { if (! is_int($workspaceId)) {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$workspaceId = (int) $tenant->workspace_id; $workspaceId = (int) $tenant->workspace_id;
} }
} }
@ -354,12 +354,12 @@ private static function applyMembershipScope(Builder $query): Builder
->whereExists(function ($membershipScope) use ($user, $workspaceId): void { ->whereExists(function ($membershipScope) use ($user, $workspaceId): void {
$membershipScope $membershipScope
->selectRaw('1') ->selectRaw('1')
->from('tenants as scoped_tenants') ->from('managed_environments as scoped_tenants')
->join('tenant_memberships as scoped_memberships', function (JoinClause $join) use ($user): void { ->join('managed_environment_memberships as scoped_memberships', function (JoinClause $join) use ($user): void {
$join->on('scoped_memberships.tenant_id', '=', 'scoped_tenants.id') $join->on('scoped_memberships.managed_environment_id', '=', 'scoped_tenants.id')
->where('scoped_memberships.user_id', '=', (int) $user->getKey()); ->where('scoped_memberships.user_id', '=', (int) $user->getKey());
}) })
->whereColumn('scoped_tenants.id', 'provider_connections.tenant_id') ->whereColumn('scoped_tenants.id', 'provider_connections.managed_environment_id')
->where('scoped_tenants.workspace_id', '=', $workspaceId); ->where('scoped_tenants.workspace_id', '=', $workspaceId);
}); });
} }
@ -376,16 +376,16 @@ private static function tenantFilterOptions(): array
return []; return [];
} }
return Tenant::query() return ManagedEnvironment::query()
->select(['tenants.external_id', 'tenants.name', 'tenants.environment']) ->select(['managed_environments.slug', 'managed_environments.name', 'managed_environments.kind'])
->join('tenant_memberships as filter_memberships', function (JoinClause $join) use ($user): void { ->join('managed_environment_memberships as filter_memberships', function (JoinClause $join) use ($user): void {
$join->on('filter_memberships.tenant_id', '=', 'tenants.id') $join->on('filter_memberships.managed_environment_id', '=', 'managed_environments.id')
->where('filter_memberships.user_id', '=', (int) $user->getKey()); ->where('filter_memberships.user_id', '=', (int) $user->getKey());
}) })
->where('tenants.workspace_id', $workspaceId) ->where('managed_environments.workspace_id', $workspaceId)
->orderBy('tenants.name') ->orderBy('managed_environments.name')
->get() ->get()
->mapWithKeys(function (Tenant $tenant): array { ->mapWithKeys(function (ManagedEnvironment $tenant): array {
$environment = strtoupper((string) ($tenant->environment ?? '')); $environment = strtoupper((string) ($tenant->environment ?? ''));
$label = $environment !== '' ? "{$tenant->name} ({$environment})" : (string) $tenant->name; $label = $environment !== '' ? "{$tenant->name} ({$environment})" : (string) $tenant->name;
@ -712,7 +712,7 @@ public static function table(Table $table): Table
} }
return $query->whereHas('tenant', function (Builder $tenantQuery) use ($tenantExternalId): void { return $query->whereHas('tenant', function (Builder $tenantQuery) use ($tenantExternalId): void {
$tenantQuery->where('external_id', $tenantExternalId); $tenantQuery->where('slug', $tenantExternalId);
}); });
}) })
->defaultSort('display_name') ->defaultSort('display_name')
@ -723,7 +723,7 @@ public static function table(Table $table): Table
->recordUrl(fn (ProviderConnection $record): string => static::getUrl('view', ['record' => $record])) ->recordUrl(fn (ProviderConnection $record): string => static::getUrl('view', ['record' => $record]))
->columns([ ->columns([
Tables\Columns\TextColumn::make('tenant.name') Tables\Columns\TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->description(function (ProviderConnection $record): ?string { ->description(function (ProviderConnection $record): ?string {
$environment = $record->tenant?->environment; $environment = $record->tenant?->environment;
@ -736,7 +736,7 @@ public static function table(Table $table): Table
->url(function (ProviderConnection $record): ?string { ->url(function (ProviderConnection $record): ?string {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -801,7 +801,7 @@ public static function table(Table $table): Table
]) ])
->filters([ ->filters([
SelectFilter::make('tenant') SelectFilter::make('tenant')
->label('Tenant') ->label('ManagedEnvironment')
->default(static::resolveScopedTenant()?->external_id) ->default(static::resolveScopedTenant()?->external_id)
->options(static::tenantFilterOptions()) ->options(static::tenantFilterOptions())
->query(function (Builder $query, array $data): Builder { ->query(function (Builder $query, array $data): Builder {
@ -812,7 +812,7 @@ public static function table(Table $table): Table
} }
return $query->whereHas('tenant', function (Builder $tenantQuery) use ($value): void { return $query->whereHas('tenant', function (Builder $tenantQuery) use ($value): void {
$tenantQuery->where('external_id', $value); $tenantQuery->where('slug', $value);
}); });
}), }),
SelectFilter::make('provider') SelectFilter::make('provider')
@ -952,7 +952,7 @@ public static function makeInventorySyncAction(): Actions\Action
gate: $gate, gate: $gate,
operationType: OperationRunType::InventorySync->value, operationType: OperationRunType::InventorySync->value,
blockedTitle: 'Inventory sync blocked', blockedTitle: 'Inventory sync blocked',
dispatcher: function (Tenant $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void { dispatcher: function (ManagedEnvironment $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void {
ProviderInventorySyncJob::dispatch( ProviderInventorySyncJob::dispatch(
tenantId: (int) $tenant->getKey(), tenantId: (int) $tenant->getKey(),
userId: (int) $user->getKey(), userId: (int) $user->getKey(),
@ -983,7 +983,7 @@ public static function makeComplianceSnapshotAction(): Actions\Action
gate: $gate, gate: $gate,
operationType: 'compliance.snapshot', operationType: 'compliance.snapshot',
blockedTitle: 'Compliance snapshot blocked', blockedTitle: 'Compliance snapshot blocked',
dispatcher: function (Tenant $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void { dispatcher: function (ManagedEnvironment $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void {
ProviderComplianceSnapshotJob::dispatch( ProviderComplianceSnapshotJob::dispatch(
tenantId: (int) $tenant->getKey(), tenantId: (int) $tenant->getKey(),
userId: (int) $user->getKey(), userId: (int) $user->getKey(),
@ -1012,7 +1012,7 @@ public static function makeSetDefaultAction(): Actions\Action
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void { ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1070,7 +1070,7 @@ public static function makeEnableDedicatedOverrideAction(string $source, ?string
->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void { ->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1147,7 +1147,7 @@ public static function makeRotateDedicatedCredentialAction(?string $modalDescrip
->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations): void { ->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1185,7 +1185,7 @@ public static function makeDeleteDedicatedCredentialAction(?string $modalDescrip
->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations): void { ->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1218,7 +1218,7 @@ public static function makeRevertToPlatformAction(string $source, ?string $modal
->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void { ->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1275,7 +1275,7 @@ public static function makeEnableConnectionAction(): Actions\Action
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void { ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1350,7 +1350,7 @@ public static function makeDisableConnectionAction(): Actions\Action
->action(function (ProviderConnection $record, AuditLogger $auditLogger): void { ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1398,7 +1398,7 @@ private static function recordAllowsProviderExecution(ProviderConnection $record
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
$user = auth()->user(); $user = auth()->user();
return $tenant instanceof Tenant return $tenant instanceof ManagedEnvironment
&& $user instanceof User && $user instanceof User
&& $user->canAccessTenant($tenant) && $user->canAccessTenant($tenant)
&& (bool) $record->is_enabled; && (bool) $record->is_enabled;
@ -1409,7 +1409,7 @@ private static function handleCheckConnectionAction(ProviderConnection $record,
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -1464,7 +1464,7 @@ private static function handleCheckConnectionAction(ProviderConnection $record,
} }
/** /**
* @param callable(Tenant, User, ProviderConnection, OperationRun): void $dispatcher * @param callable(ManagedEnvironment, User, ProviderConnection, OperationRun): void $dispatcher
*/ */
private static function handleProviderOperationAction( private static function handleProviderOperationAction(
ProviderConnection $record, ProviderConnection $record,
@ -1477,7 +1477,7 @@ private static function handleProviderOperationAction(
$tenant = static::resolveTenantForRecord($record); $tenant = static::resolveTenantForRecord($record);
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return; return;
} }
@ -1543,7 +1543,7 @@ public static function getPages(): array
private static function normalizeTenantExternalId(mixed $tenant): ?string private static function normalizeTenantExternalId(mixed $tenant): ?string
{ {
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return (string) $tenant->external_id; return (string) $tenant->external_id;
} }
@ -1552,9 +1552,9 @@ private static function normalizeTenantExternalId(mixed $tenant): ?string
} }
if (is_numeric($tenant)) { if (is_numeric($tenant)) {
$tenantModel = Tenant::query()->whereKey((int) $tenant)->first(); $tenantModel = ManagedEnvironment::query()->whereKey((int) $tenant)->first();
if ($tenantModel instanceof Tenant) { if ($tenantModel instanceof ManagedEnvironment) {
return (string) $tenantModel->external_id; return (string) $tenantModel->external_id;
} }
} }
@ -1575,7 +1575,7 @@ public static function getUrl(?string $name = null, array $parameters = [], bool
unset($parameters['tenant']); unset($parameters['tenant']);
} }
if ($tenantExternalId === null && $tenant instanceof Tenant) { if ($tenantExternalId === null && $tenant instanceof ManagedEnvironment) {
$tenantExternalId = (string) $tenant->external_id; $tenantExternalId = (string) $tenant->external_id;
} }
@ -1591,8 +1591,8 @@ public static function getUrl(?string $name = null, array $parameters = [], bool
$tenantExternalId = static::resolveScopedTenant()?->external_id; $tenantExternalId = static::resolveScopedTenant()?->external_id;
} }
if (! array_key_exists('tenant_id', $parameters) && is_string($tenantExternalId) && $tenantExternalId !== '') { if (! array_key_exists('managed_environment_id', $parameters) && is_string($tenantExternalId) && $tenantExternalId !== '') {
$parameters['tenant_id'] = $tenantExternalId; $parameters['managed_environment_id'] = $tenantExternalId;
} }
return parent::getUrl($name, $parameters, $isAbsolute, $panel, null, $shouldGuessMissingParameters); return parent::getUrl($name, $parameters, $isAbsolute, $panel, null, $shouldGuessMissingParameters);

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\ProviderConnectionResource\Pages; namespace App\Filament\Resources\ProviderConnectionResource\Pages;
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use App\Support\Providers\ProviderConnectionType; use App\Support\Providers\ProviderConnectionType;
@ -26,7 +26,7 @@ protected function mutateFormDataBeforeCreate(array $data): array
{ {
$tenant = $this->currentTenant(); $tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -49,7 +49,7 @@ protected function mutateFormDataBeforeCreate(array $data): array
return [ return [
'workspace_id' => (int) $tenant->workspace_id, 'workspace_id' => (int) $tenant->workspace_id,
'tenant_id' => $tenant->getKey(), 'managed_environment_id' => $tenant->getKey(),
'provider' => 'microsoft', 'provider' => 'microsoft',
'entra_tenant_id' => $data['entra_tenant_id'], 'entra_tenant_id' => $data['entra_tenant_id'],
'display_name' => $data['display_name'], 'display_name' => $data['display_name'],
@ -73,7 +73,7 @@ protected function afterCreate(): void
{ {
$tenant = $this->currentTenant(); $tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -115,11 +115,11 @@ protected function afterCreate(): void
->send(); ->send();
} }
private function currentTenant(): ?Tenant private function currentTenant(): ?ManagedEnvironment
{ {
$tenant = ProviderConnectionResource::resolveTenantForCreate(); $tenant = ProviderConnectionResource::resolveTenantForCreate();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return $tenant; return $tenant;
} }

View File

@ -7,7 +7,7 @@
use App\Jobs\ProviderInventorySyncJob; use App\Jobs\ProviderInventorySyncJob;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
@ -48,13 +48,13 @@ public function mount($record): void
? ProviderConnectionResource::resolveTenantForRecord($this->record) ? ProviderConnectionResource::resolveTenantForRecord($this->record)
: null; : null;
if ($recordTenant instanceof Tenant) { if ($recordTenant instanceof ManagedEnvironment) {
$this->scopedTenantExternalId = (string) $recordTenant->external_id; $this->scopedTenantExternalId = (string) $recordTenant->external_id;
return; return;
} }
$tenantIdFromQuery = request()->query('tenant_id'); $tenantIdFromQuery = request()->query('managed_environment_id');
if (is_string($tenantIdFromQuery) && $tenantIdFromQuery !== '') { if (is_string($tenantIdFromQuery) && $tenantIdFromQuery !== '') {
$this->scopedTenantExternalId = $tenantIdFromQuery; $this->scopedTenantExternalId = $tenantIdFromQuery;
@ -64,7 +64,7 @@ public function mount($record): void
$tenant = request()->route('tenant'); $tenant = request()->route('tenant');
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$this->scopedTenantExternalId = (string) $tenant->external_id; $this->scopedTenantExternalId = (string) $tenant->external_id;
return; return;
@ -107,7 +107,7 @@ protected function afterSave(): void
? ($record->tenant ?? $this->currentTenant()) ? ($record->tenant ?? $this->currentTenant())
: $this->currentTenant(); : $this->currentTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -182,21 +182,21 @@ protected function getHeaderActions(): array
->label('View last check run') ->label('View last check run')
->icon('heroicon-o-eye') ->icon('heroicon-o-eye')
->color('gray') ->color('gray')
->visible(fn (ProviderConnection $record): bool => $tenant instanceof Tenant ->visible(fn (ProviderConnection $record): bool => $tenant instanceof ManagedEnvironment
&& OperationRun::query() && OperationRun::query()
->where('tenant_id', $tenant->getKey()) ->where('managed_environment_id', $tenant->getKey())
->where('type', 'provider.connection.check') ->where('type', 'provider.connection.check')
->where('context->provider_connection_id', (int) $record->getKey()) ->where('context->provider_connection_id', (int) $record->getKey())
->exists()) ->exists())
->url(function (ProviderConnection $record): ?string { ->url(function (ProviderConnection $record): ?string {
$tenant = $this->currentTenant(); $tenant = $this->currentTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
$run = OperationRun::query() $run = OperationRun::query()
->where('tenant_id', $tenant->getKey()) ->where('managed_environment_id', $tenant->getKey())
->where('type', 'provider.connection.check') ->where('type', 'provider.connection.check')
->where('context->provider_connection_id', (int) $record->getKey()) ->where('context->provider_connection_id', (int) $record->getKey())
->orderByDesc('id') ->orderByDesc('id')
@ -246,7 +246,7 @@ protected function getFormActions(): array
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return [ return [
$this->getCancelFormAction(), $this->getCancelFormAction(),
]; ];
@ -271,7 +271,7 @@ protected function handleRecordUpdate(Model $record, array $data): Model
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
abort(404); abort(404);
} }
@ -288,40 +288,40 @@ protected function handleRecordUpdate(Model $record, array $data): Model
return parent::handleRecordUpdate($record, $data); return parent::handleRecordUpdate($record, $data);
} }
private function currentTenant(): ?Tenant private function currentTenant(): ?ManagedEnvironment
{ {
if (isset($this->record) && $this->record instanceof ProviderConnection) { if (isset($this->record) && $this->record instanceof ProviderConnection) {
$recordTenant = ProviderConnectionResource::resolveTenantForRecord($this->record); $recordTenant = ProviderConnectionResource::resolveTenantForRecord($this->record);
if ($recordTenant instanceof Tenant) { if ($recordTenant instanceof ManagedEnvironment) {
return $recordTenant; return $recordTenant;
} }
} }
if (is_string($this->scopedTenantExternalId) && $this->scopedTenantExternalId !== '') { if (is_string($this->scopedTenantExternalId) && $this->scopedTenantExternalId !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $this->scopedTenantExternalId) ->where('slug', $this->scopedTenantExternalId)
->first(); ->first();
} }
$tenant = request()->route('tenant'); $tenant = request()->route('tenant');
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return $tenant; return $tenant;
} }
if (is_string($tenant) && $tenant !== '') { if (is_string($tenant) && $tenant !== '') {
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $tenant) ->where('slug', $tenant)
->first(); ->first();
} }
$tenantFromCreateResolution = ProviderConnectionResource::resolveTenantForCreate(); $tenantFromCreateResolution = ProviderConnectionResource::resolveTenantForCreate();
if ($tenantFromCreateResolution instanceof Tenant) { if ($tenantFromCreateResolution instanceof ManagedEnvironment) {
return $tenantFromCreateResolution; return $tenantFromCreateResolution;
} }
return Tenant::current(); return ManagedEnvironment::current();
} }
} }

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\ProviderConnectionResource\Pages; namespace App\Filament\Resources\ProviderConnectionResource\Pages;
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -48,7 +48,7 @@ protected function getHeaderActions(): array
} }
return ProviderConnectionResource::getUrl('create', [ return ProviderConnectionResource::getUrl('create', [
'tenant_id' => $tenantExternalId, 'managed_environment_id' => $tenantExternalId,
]); ]);
}) })
->visible(function () use ($resolver): bool { ->visible(function () use ($resolver): bool {
@ -59,7 +59,7 @@ protected function getHeaderActions(): array
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return true; return true;
} }
@ -73,7 +73,7 @@ protected function getHeaderActions(): array
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return true; return true;
} }
@ -90,7 +90,7 @@ protected function getHeaderActions(): array
->tooltip(function () use ($resolver): ?string { ->tooltip(function () use ($resolver): ?string {
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'Select a tenant to create provider connections.'; return 'Select a tenant to create provider connections.';
} }
@ -114,7 +114,7 @@ protected function getHeaderActions(): array
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
return $tenant instanceof Tenant return $tenant instanceof ManagedEnvironment
&& $user instanceof User && $user instanceof User
&& $resolver->isMember($user, $tenant); && $resolver->isMember($user, $tenant);
}), }),
@ -136,14 +136,14 @@ private function makeEmptyStateCreateAction(): Actions\CreateAction
} }
return ProviderConnectionResource::getUrl('create', [ return ProviderConnectionResource::getUrl('create', [
'tenant_id' => $tenantExternalId, 'managed_environment_id' => $tenantExternalId,
]); ]);
}) })
->visible(function () use ($resolver): bool { ->visible(function () use ($resolver): bool {
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return true; return true;
} }
@ -157,7 +157,7 @@ private function makeEmptyStateCreateAction(): Actions\CreateAction
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return true; return true;
} }
@ -174,7 +174,7 @@ private function makeEmptyStateCreateAction(): Actions\CreateAction
->tooltip(function () use ($resolver): ?string { ->tooltip(function () use ($resolver): ?string {
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'Select a tenant to create provider connections.'; return 'Select a tenant to create provider connections.';
} }
@ -198,7 +198,7 @@ private function makeEmptyStateCreateAction(): Actions\CreateAction
$tenant = $this->resolveTenantForCreateAction(); $tenant = $this->resolveTenantForCreateAction();
$user = auth()->user(); $user = auth()->user();
return $tenant instanceof Tenant return $tenant instanceof ManagedEnvironment
&& $user instanceof User && $user instanceof User
&& $resolver->isMember($user, $tenant); && $resolver->isMember($user, $tenant);
}); });
@ -222,7 +222,7 @@ private function resolveTenantExternalIdForCreateAction(): ?string
return ProviderConnectionResource::resolveContextTenantExternalId(); return ProviderConnectionResource::resolveContextTenantExternalId();
} }
private function resolveTenantForCreateAction(): ?Tenant private function resolveTenantForCreateAction(): ?ManagedEnvironment
{ {
$tenantExternalId = $this->resolveTenantExternalIdForCreateAction(); $tenantExternalId = $this->resolveTenantExternalIdForCreateAction();
@ -230,8 +230,8 @@ private function resolveTenantForCreateAction(): ?Tenant
return null; return null;
} }
return Tenant::query() return ManagedEnvironment::query()
->where('external_id', $tenantExternalId) ->where('slug', $tenantExternalId)
->first(); ->first();
} }

View File

@ -4,7 +4,7 @@
use App\Filament\Resources\ProviderConnectionResource; use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Links\RequiredPermissionsLinks; use App\Support\Links\RequiredPermissionsLinks;
use App\Support\Rbac\UiEnforcement; use App\Support\Rbac\UiEnforcement;
@ -25,11 +25,11 @@ protected function getHeaderActions(): array
->label('Grant admin consent') ->label('Grant admin consent')
->icon('heroicon-o-clipboard-document') ->icon('heroicon-o-clipboard-document')
->url(function () use ($tenant): ?string { ->url(function () use ($tenant): ?string {
return $tenant instanceof Tenant return $tenant instanceof ManagedEnvironment
? RequiredPermissionsLinks::adminConsentPrimaryUrl($tenant) ? RequiredPermissionsLinks::adminConsentPrimaryUrl($tenant)
: null; : null;
}) })
->visible(fn (): bool => $tenant instanceof Tenant) ->visible(fn (): bool => $tenant instanceof ManagedEnvironment)
->openUrlInNewTab() ->openUrlInNewTab()
) )
->requireCapability(Capabilities::PROVIDER_MANAGE) ->requireCapability(Capabilities::PROVIDER_MANAGE)
@ -64,7 +64,7 @@ private function sharedConnectionActions(): array
]; ];
} }
private function currentTenant(): ?Tenant private function currentTenant(): ?ManagedEnvironment
{ {
if (! $this->record instanceof ProviderConnection) { if (! $this->record instanceof ProviderConnection) {
return null; return null;

View File

@ -16,7 +16,7 @@
use App\Models\EntraGroup; use App\Models\EntraGroup;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\RestoreRun; use App\Models\RestoreRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Models\Workspace; use App\Models\Workspace;
use App\Rules\SkipOrUuidRule; use App\Rules\SkipOrUuidRule;
@ -111,7 +111,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -127,7 +127,7 @@ public static function canCreate(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -192,7 +192,7 @@ public static function form(Schema $schema): Schema
tenant: $tenant tenant: $tenant
); );
$groupCacheQuery = EntraGroup::query()->where('tenant_id', $tenant->getKey()); $groupCacheQuery = EntraGroup::query()->where('managed_environment_id', $tenant->getKey());
$hasCachedGroups = $groupCacheQuery->exists(); $hasCachedGroups = $groupCacheQuery->exists();
$stalenessDays = (int) config('directory_groups.staleness_days', 30); $stalenessDays = (int) config('directory_groups.staleness_days', 30);
@ -505,7 +505,7 @@ public static function getWizardSteps(): array
tenant: $tenant tenant: $tenant
); );
$groupCacheQuery = EntraGroup::query()->where('tenant_id', $tenant->getKey()); $groupCacheQuery = EntraGroup::query()->where('managed_environment_id', $tenant->getKey());
$hasCachedGroups = $groupCacheQuery->exists(); $hasCachedGroups = $groupCacheQuery->exists();
$stalenessDays = (int) config('directory_groups.staleness_days', 30); $stalenessDays = (int) config('directory_groups.staleness_days', 30);
@ -630,7 +630,7 @@ public static function getWizardSteps(): array
$backupSet = BackupSet::find($backupSetId); $backupSet = BackupSet::find($backupSetId);
if (! $backupSet || $backupSet->tenant_id !== $tenant->id) { if (! $backupSet || $backupSet->managed_environment_id !== $tenant->id) {
Notification::make() Notification::make()
->title('Unable to run checks') ->title('Unable to run checks')
->body('Backup set is not available for the active tenant.') ->body('Backup set is not available for the active tenant.')
@ -749,7 +749,7 @@ public static function getWizardSteps(): array
$backupSet = BackupSet::find($backupSetId); $backupSet = BackupSet::find($backupSetId);
if (! $backupSet || $backupSet->tenant_id !== $tenant->id) { if (! $backupSet || $backupSet->managed_environment_id !== $tenant->id) {
Notification::make() Notification::make()
->title('Unable to generate preview') ->title('Unable to generate preview')
->body('Backup set is not available for the active tenant.') ->body('Backup set is not available for the active tenant.')
@ -827,7 +827,7 @@ public static function getWizardSteps(): array
->label('Environment') ->label('Environment')
->content(fn (): string => app()->environment('production') ? 'prod' : 'test'), ->content(fn (): string => app()->environment('production') ? 'prod' : 'test'),
Forms\Components\Placeholder::make('confirm_tenant_label') Forms\Components\Placeholder::make('confirm_tenant_label')
->label('Tenant hard-confirm label') ->label('ManagedEnvironment hard-confirm label')
->content(function (): string { ->content(function (): string {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
@ -835,7 +835,7 @@ public static function getWizardSteps(): array
return ''; return '';
} }
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
return (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey()); return (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
}), }),
@ -914,12 +914,12 @@ public static function getWizardSteps(): array
return []; return [];
} }
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
return [(string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey())]; return [(string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey())];
}) })
->validationMessages([ ->validationMessages([
'in' => 'Tenant hard-confirm does not match.', 'in' => 'ManagedEnvironment hard-confirm does not match.',
]) ])
->helperText(function (): string { ->helperText(function (): string {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
@ -928,7 +928,7 @@ public static function getWizardSteps(): array
return ''; return '';
} }
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
$expected = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey()); $expected = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
return "Type: {$expected}"; return "Type: {$expected}";
@ -1156,7 +1156,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = static::resolveProtectedRestoreRunIds($records); $ids = static::resolveProtectedRestoreRunIds($records);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1173,7 +1173,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'restore_run.delete', type: 'restore_run.delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($tenant, $initiator, $ids): void {
@ -1226,7 +1226,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = static::resolveProtectedRestoreRunIds($records); $ids = static::resolveProtectedRestoreRunIds($records);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1243,7 +1243,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'restore_run.restore', type: 'restore_run.restore',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($count, $tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($count, $tenant, $initiator, $ids): void {
@ -1316,7 +1316,7 @@ public static function table(Table $table): Table
$count = $records->count(); $count = $records->count();
$ids = static::resolveProtectedRestoreRunIds($records); $ids = static::resolveProtectedRestoreRunIds($records);
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -1333,7 +1333,7 @@ public static function table(Table $table): Table
tenant: $tenant, tenant: $tenant,
type: 'restore_run.force_delete', type: 'restore_run.force_delete',
targetScope: [ targetScope: [
'entra_tenant_id' => (string) ($tenant->tenant_id ?? $tenant->external_id), 'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
], ],
selectionIdentity: $selectionIdentity, selectionIdentity: $selectionIdentity,
dispatcher: function ($operationRun) use ($count, $tenant, $initiator, $ids): void { dispatcher: function ($operationRun) use ($count, $tenant, $initiator, $ids): void {
@ -1469,7 +1469,7 @@ private static function restoreItemOptionData(?int $backupSetId): array
return Cache::store('array')->rememberForever($cacheKey, function () use ($backupSetId, $tenant): array { return Cache::store('array')->rememberForever($cacheKey, function () use ($backupSetId, $tenant): array {
$items = BackupItem::query() $items = BackupItem::query()
->where('backup_set_id', $backupSetId) ->where('backup_set_id', $backupSetId)
->whereHas('backupSet', fn ($query) => $query->where('tenant_id', $tenant->getKey())) ->whereHas('backupSet', fn ($query) => $query->where('managed_environment_id', $tenant->getKey()))
->where(function ($query) { ->where(function ($query) {
$query->whereNull('policy_id') $query->whereNull('policy_id')
->orWhereDoesntHave('policy') ->orWhereDoesntHave('policy')
@ -1544,7 +1544,7 @@ private static function restoreItemGroupedOptions(?int $backupSetId): array
$items = BackupItem::query() $items = BackupItem::query()
->where('backup_set_id', $backupSetId) ->where('backup_set_id', $backupSetId)
->whereHas('backupSet', fn ($query) => $query->where('tenant_id', $tenant->getKey())) ->whereHas('backupSet', fn ($query) => $query->where('managed_environment_id', $tenant->getKey()))
->where(function ($query) { ->where(function ($query) {
$query->whereNull('policy_id') $query->whereNull('policy_id')
->orWhereDoesntHave('policy') ->orWhereDoesntHave('policy')
@ -1598,7 +1598,7 @@ private static function restoreBackupSetOptions(): array
$tenantId = static::resolveTenantContextForCurrentPanelOrFail()->getKey(); $tenantId = static::resolveTenantContextForCurrentPanelOrFail()->getKey();
return BackupSet::query() return BackupSet::query()
->where('tenant_id', $tenantId) ->where('managed_environment_id', $tenantId)
->with([ ->with([
'items' => fn ($query) => $query->select([ 'items' => fn ($query) => $query->select([
'id', 'id',
@ -1638,12 +1638,12 @@ private static function restoreBackupSetHelperText(mixed $backupSetId): string
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return $default; return $default;
} }
$backupSet = BackupSet::query() $backupSet = BackupSet::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->with([ ->with([
'items' => fn ($query) => $query->select([ 'items' => fn ($query) => $query->select([
'id', 'id',
@ -1695,7 +1695,7 @@ public static function createRestoreRun(array $data): RestoreRun
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
abort(403); abort(403);
} }
@ -1713,7 +1713,7 @@ public static function createRestoreRun(array $data): RestoreRun
/** @var BackupSet $backupSet */ /** @var BackupSet $backupSet */
$backupSet = BackupSet::findOrFail($data['backup_set_id']); $backupSet = BackupSet::findOrFail($data['backup_set_id']);
if ($backupSet->tenant_id !== $tenant->id) { if ($backupSet->managed_environment_id !== $tenant->id) {
abort(403, 'Backup set does not belong to the active tenant.'); abort(403, 'Backup set does not belong to the active tenant.');
} }
@ -1756,7 +1756,7 @@ public static function createRestoreRun(array $data): RestoreRun
$previewDiffs = $data['preview_diffs'] ?? null; $previewDiffs = $data['preview_diffs'] ?? null;
$previewRanAt = $data['preview_ran_at'] ?? null; $previewRanAt = $data['preview_ran_at'] ?? null;
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
$highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey()); $highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
if (! $isDryRun) { if (! $isDryRun) {
@ -1835,7 +1835,7 @@ public static function createRestoreRun(array $data): RestoreRun
if (! is_string($tenantConfirm) || $tenantConfirm !== $highlanderLabel) { if (! is_string($tenantConfirm) || $tenantConfirm !== $highlanderLabel) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'tenant_confirm' => 'Tenant hard-confirm does not match.', 'tenant_confirm' => 'ManagedEnvironment hard-confirm does not match.',
]); ]);
} }
} }
@ -1988,7 +1988,7 @@ public static function createRestoreRun(array $data): RestoreRun
* @return array{0: \App\Services\Providers\ProviderOperationStartResult, 1: ?RestoreRun} * @return array{0: \App\Services\Providers\ProviderOperationStartResult, 1: ?RestoreRun}
*/ */
private static function startQueuedRestoreExecution( private static function startQueuedRestoreExecution(
Tenant $tenant, ManagedEnvironment $tenant,
BackupSet $backupSet, BackupSet $backupSet,
?array $selectedItemIds, ?array $selectedItemIds,
array $preview, array $preview,
@ -2029,7 +2029,7 @@ private static function startQueuedRestoreExecution(
&$queuedRestoreRun, &$queuedRestoreRun,
): void { ): void {
$queuedRestoreRun = RestoreRun::create([ $queuedRestoreRun = RestoreRun::create([
'tenant_id' => $tenant->id, 'managed_environment_id' => $tenant->id,
'backup_set_id' => $backupSet->id, 'backup_set_id' => $backupSet->id,
'operation_run_id' => $run->getKey(), 'operation_run_id' => $run->getKey(),
'requested_by' => $actorEmail, 'requested_by' => $actorEmail,
@ -2137,7 +2137,7 @@ private static function startQueuedRestoreExecution(
* @param array<int>|null $selectedItemIds * @param array<int>|null $selectedItemIds
*/ */
private static function guardRestoreExecutionOperationalControl( private static function guardRestoreExecutionOperationalControl(
Tenant $tenant, ManagedEnvironment $tenant,
BackupSet $backupSet, BackupSet $backupSet,
?array $selectedItemIds, ?array $selectedItemIds,
?User $initiator, ?User $initiator,
@ -2241,7 +2241,7 @@ private static function wizardSafetyState(array $data): array
$previewIntegrity = $resolver->previewIntegrityFromData($data); $previewIntegrity = $resolver->previewIntegrityFromData($data);
$checksIntegrity = $resolver->checksIntegrityFromData($data); $checksIntegrity = $resolver->checksIntegrityFromData($data);
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return [ return [
'currentScope' => $scope, 'currentScope' => $scope,
'previewIntegrity' => $previewIntegrity->toArray(), 'previewIntegrity' => $previewIntegrity->toArray(),
@ -2346,7 +2346,7 @@ private static function restoreSafetyResolver(): RestoreSafetyResolver
* @param array<int>|null $selectedItemIds * @param array<int>|null $selectedItemIds
* @return array<int, array{id:string,label:string}> * @return array<int, array{id:string,label:string}>
*/ */
private static function unresolvedGroups(?int $backupSetId, ?array $selectedItemIds, Tenant $tenant): array private static function unresolvedGroups(?int $backupSetId, ?array $selectedItemIds, ManagedEnvironment $tenant): array
{ {
if (! $backupSetId) { if (! $backupSetId) {
return []; return [];
@ -2421,7 +2421,7 @@ private static function unresolvedGroups(?int $backupSetId, ?array $selectedItem
* @param array<int>|null $selectedItemIds * @param array<int>|null $selectedItemIds
* @return array<string, string|null> * @return array<string, string|null>
*/ */
private static function groupMappingPlaceholders(?int $backupSetId, string $scopeMode, ?array $selectedItemIds, ?Tenant $tenant): array private static function groupMappingPlaceholders(?int $backupSetId, string $scopeMode, ?array $selectedItemIds, ?ManagedEnvironment $tenant): array
{ {
if (! $tenant || ! $backupSetId) { if (! $tenant || ! $backupSetId) {
return []; return [];
@ -2601,7 +2601,7 @@ private static function rerunActionWithGate(): Actions\Action|BulkAction
$groupMapping = is_array($record->group_mapping) ? $record->group_mapping : []; $groupMapping = is_array($record->group_mapping) ? $record->group_mapping : [];
$actorEmail = auth()->user()?->email; $actorEmail = auth()->user()?->email;
$actorName = auth()->user()?->name; $actorName = auth()->user()?->name;
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id; $tenantIdentifier = $tenant->managed_environment_id ?? $tenant->external_id;
$highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey()); $highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
$preview = $restoreService->preview($tenant, $backupSet, $selectedItemIds); $preview = $restoreService->preview($tenant, $backupSet, $selectedItemIds);
@ -2729,7 +2729,7 @@ private static function rerunActionWithGate(): Actions\Action|BulkAction
$tenant = $record instanceof RestoreRun ? $record->tenant : static::resolveTenantContextForCurrentPanel(); $tenant = $record instanceof RestoreRun ? $record->tenant : static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return true; return true;
} }
@ -2753,8 +2753,8 @@ private static function rerunActionWithGate(): Actions\Action|BulkAction
$tenant = $record instanceof RestoreRun ? $record->tenant : static::resolveTenantContextForCurrentPanel(); $tenant = $record instanceof RestoreRun ? $record->tenant : static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return 'Tenant unavailable'; return 'ManagedEnvironment unavailable';
} }
// Check RBAC capability first // Check RBAC capability first

View File

@ -5,7 +5,7 @@
use App\Filament\Concerns\ResolvesPanelTenantContext; use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Resources\RestoreRunResource; use App\Filament\Resources\RestoreRunResource;
use App\Models\BackupSet; use App\Models\BackupSet;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -28,7 +28,7 @@ protected function authorizeAccess(): void
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
abort(404); abort(404);
} }
@ -69,7 +69,7 @@ protected function afterFill(): void
} }
$belongsToTenant = BackupSet::query() $belongsToTenant = BackupSet::query()
->where('tenant_id', $tenant->id) ->where('managed_environment_id', $tenant->id)
->whereKey($backupSetId) ->whereKey($backupSetId)
->exists(); ->exists();

View File

@ -9,7 +9,7 @@
use App\Filament\Resources\EvidenceSnapshotResource as TenantEvidenceSnapshotResource; use App\Filament\Resources\EvidenceSnapshotResource as TenantEvidenceSnapshotResource;
use App\Filament\Resources\ReviewPackResource\Pages; use App\Filament\Resources\ReviewPackResource\Pages;
use App\Models\ReviewPack; use App\Models\ReviewPack;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\ReviewPackService; use App\Services\ReviewPackService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -67,10 +67,10 @@ class ReviewPackResource extends Resource
public static function canViewAny(): bool public static function canViewAny(): bool
{ {
$tenant = Tenant::current(); $tenant = ManagedEnvironment::current();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -83,10 +83,10 @@ public static function canViewAny(): bool
public static function canView(Model $record): bool public static function canView(Model $record): bool
{ {
$tenant = Tenant::current(); $tenant = ManagedEnvironment::current();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -99,7 +99,7 @@ public static function canView(Model $record): bool
} }
if ($record instanceof ReviewPack) { if ($record instanceof ReviewPack) {
return (int) $record->tenant_id === (int) $tenant->getKey(); return (int) $record->managed_environment_id === (int) $tenant->getKey();
} }
return true; return true;
@ -142,7 +142,7 @@ public static function infolist(Schema $schema): Schema
->color(BadgeRenderer::color(BadgeDomain::ReviewPackStatus)) ->color(BadgeRenderer::color(BadgeDomain::ReviewPackStatus))
->icon(BadgeRenderer::icon(BadgeDomain::ReviewPackStatus)) ->icon(BadgeRenderer::icon(BadgeDomain::ReviewPackStatus))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::ReviewPackStatus)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ReviewPackStatus)),
TextEntry::make('tenant.name')->label('Tenant'), TextEntry::make('tenant.name')->label('ManagedEnvironment'),
TextEntry::make('generated_at')->dateTime()->placeholder('—'), TextEntry::make('generated_at')->dateTime()->placeholder('—'),
TextEntry::make('expires_at')->dateTime()->placeholder('—'), TextEntry::make('expires_at')->dateTime()->placeholder('—'),
TextEntry::make('file_size') TextEntry::make('file_size')
@ -192,7 +192,7 @@ public static function infolist(Schema $schema): Schema
->schema([ ->schema([
TextEntry::make('initiator.name')->label('Initiated by')->placeholder('—'), TextEntry::make('initiator.name')->label('Initiated by')->placeholder('—'),
TextEntry::make('tenantReview.id') TextEntry::make('tenantReview.id')
->label('Tenant review') ->label('ManagedEnvironment review')
->formatStateUsing(fn (?int $state): string => $state ? '#'.$state : '—') ->formatStateUsing(fn (?int $state): string => $state ? '#'.$state : '—')
->url(fn (ReviewPack $record): ?string => $record->tenantReview && $record->tenant ->url(fn (ReviewPack $record): ?string => $record->tenantReview && $record->tenant
? TenantReviewResource::tenantScopedUrl('view', ['record' => $record->tenantReview], $record->tenant) ? TenantReviewResource::tenantScopedUrl('view', ['record' => $record->tenantReview], $record->tenant)
@ -201,7 +201,7 @@ public static function infolist(Schema $schema): Schema
TextEntry::make('customer_workspace') TextEntry::make('customer_workspace')
->label('Customer workspace') ->label('Customer workspace')
->state(fn (): string => 'Open workspace') ->state(fn (): string => 'Open workspace')
->url(fn (ReviewPack $record): ?string => $record->tenant instanceof Tenant ->url(fn (ReviewPack $record): ?string => $record->tenant instanceof ManagedEnvironment
? CustomerReviewWorkspace::tenantPrefilterUrl($record->tenant) ? CustomerReviewWorkspace::tenantPrefilterUrl($record->tenant)
: null) : null)
->placeholder('—'), ->placeholder('—'),
@ -222,7 +222,7 @@ public static function infolist(Schema $schema): Schema
$tenant = $record->tenant; $tenant = $record->tenant;
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
return OperationRunLinks::view((int) $record->operation_run_id, $tenant); return OperationRunLinks::view((int) $record->operation_run_id, $tenant);
} }
@ -291,7 +291,7 @@ public static function table(Table $table): Table
->description(fn (ReviewPack $record): ?string => static::compressedOutcome($record)->primaryReason) ->description(fn (ReviewPack $record): ?string => static::compressedOutcome($record)->primaryReason)
->wrap(), ->wrap(),
Tables\Columns\TextColumn::make('tenant.name') Tables\Columns\TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('generated_at') Tables\Columns\TextColumn::make('generated_at')
->dateTime() ->dateTime()
@ -413,15 +413,15 @@ public static function reviewPackGenerationFormSchema(): array
public static function getEloquentQuery(): Builder public static function getEloquentQuery(): Builder
{ {
$tenant = Tenant::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant(); $tenant = ManagedEnvironment::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return parent::getEloquentQuery()->whereRaw('1 = 0'); return parent::getEloquentQuery()->whereRaw('1 = 0');
} }
return parent::getEloquentQuery() return parent::getEloquentQuery()
->with(['tenant', 'operationRun', 'evidenceSnapshot', 'tenantReview']) ->with(['tenant', 'operationRun', 'evidenceSnapshot', 'tenantReview'])
->where('tenant_id', (int) $tenant->getKey()); ->where('managed_environment_id', (int) $tenant->getKey());
} }
public static function getPages(): array public static function getPages(): array
@ -504,7 +504,7 @@ public static function executeGeneration(array $data): void
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
Notification::make()->danger()->title('Unable to generate pack — missing context.')->send(); Notification::make()->danger()->title('Unable to generate pack — missing context.')->send();
return; return;
@ -572,30 +572,30 @@ public static function executeGeneration(array $data): void
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
public static function reviewPackGenerationDecision(?Tenant $tenant = null): array public static function reviewPackGenerationDecision(?ManagedEnvironment $tenant = null): array
{ {
$tenant ??= Tenant::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant(); $tenant ??= ManagedEnvironment::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return app(ReviewPackService::class)->reviewPackGenerationDecisionForTenant($tenant); return app(ReviewPackService::class)->reviewPackGenerationDecisionForTenant($tenant);
} }
public static function currentTenantContext(): ?Tenant public static function currentTenantContext(): ?ManagedEnvironment
{ {
$tenant = Tenant::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant(); $tenant = ManagedEnvironment::current() ?? static::resolveTenantContextForCurrentPanel() ?? Filament::getTenant();
return $tenant instanceof Tenant ? $tenant : null; return $tenant instanceof ManagedEnvironment ? $tenant : null;
} }
public static function reviewPackGenerationBlocked(?Tenant $tenant = null): bool public static function reviewPackGenerationBlocked(?ManagedEnvironment $tenant = null): bool
{ {
return (bool) (static::reviewPackGenerationDecision($tenant)['is_blocked'] ?? false); return (bool) (static::reviewPackGenerationDecision($tenant)['is_blocked'] ?? false);
} }
public static function reviewPackGenerationBlockReason(?Tenant $tenant = null): ?string public static function reviewPackGenerationBlockReason(?ManagedEnvironment $tenant = null): ?string
{ {
$decision = static::reviewPackGenerationDecision($tenant); $decision = static::reviewPackGenerationDecision($tenant);
@ -608,7 +608,7 @@ public static function reviewPackGenerationBlockReason(?Tenant $tenant = null):
return is_string($reason) && $reason !== '' ? $reason : null; return is_string($reason) && $reason !== '' ? $reason : null;
} }
public static function reviewPackGenerationWarningReason(?Tenant $tenant = null): ?string public static function reviewPackGenerationWarningReason(?ManagedEnvironment $tenant = null): ?string
{ {
$decision = static::reviewPackGenerationDecision($tenant); $decision = static::reviewPackGenerationDecision($tenant);
@ -621,12 +621,12 @@ public static function reviewPackGenerationWarningReason(?Tenant $tenant = null)
return is_string($reason) && $reason !== '' ? $reason : null; return is_string($reason) && $reason !== '' ? $reason : null;
} }
public static function reviewPackGenerationActionTooltip(?Tenant $tenant = null): ?string public static function reviewPackGenerationActionTooltip(?ManagedEnvironment $tenant = null): ?string
{ {
$tenant ??= static::currentTenantContext(); $tenant ??= static::currentTenantContext();
$user = auth()->user(); $user = auth()->user();
if ($tenant instanceof Tenant && $user instanceof User && ! $user->can(Capabilities::REVIEW_PACK_MANAGE, $tenant)) { if ($tenant instanceof ManagedEnvironment && $user instanceof User && ! $user->can(Capabilities::REVIEW_PACK_MANAGE, $tenant)) {
return AuthUiTooltips::insufficientPermission(); return AuthUiTooltips::insufficientPermission();
} }

View File

@ -9,7 +9,7 @@
use App\Filament\Pages\TenantDashboard; use App\Filament\Pages\TenantDashboard;
use App\Filament\Resources\StoredReportResource\Pages; use App\Filament\Resources\StoredReportResource\Pages;
use App\Models\StoredReport; use App\Models\StoredReport;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
@ -78,7 +78,7 @@ public static function canView(Model $record): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -90,7 +90,7 @@ public static function canView(Model $record): bool
return true; return true;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey() || (int) $record->workspace_id !== (int) $tenant->workspace_id) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey() || (int) $record->workspace_id !== (int) $tenant->workspace_id) {
return false; return false;
} }
@ -133,7 +133,7 @@ public static function getEloquentQuery(): Builder
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$query->where('workspace_id', (int) $tenant->workspace_id); $query->where('workspace_id', (int) $tenant->workspace_id);
} }
@ -154,7 +154,7 @@ public static function resolveScopedRecordOrFail(int|string|null $record): Model
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if ($tenant instanceof Tenant) { if ($tenant instanceof ManagedEnvironment) {
$query->where('workspace_id', (int) $tenant->workspace_id); $query->where('workspace_id', (int) $tenant->workspace_id);
} }
@ -387,7 +387,7 @@ public static function visibleReportTypesForCurrentUser(): array
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User || ! $user->canAccessTenant($tenant)) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || ! $user->canAccessTenant($tenant)) {
return []; return [];
} }
@ -544,7 +544,7 @@ public static function highestRiskAssignmentLabel(StoredReport $report): ?string
public static function currentReportFor(StoredReport $report): ?StoredReport public static function currentReportFor(StoredReport $report): ?StoredReport
{ {
$current = StoredReport::query() $current = StoredReport::query()
->where('tenant_id', (int) $report->tenant_id) ->where('managed_environment_id', (int) $report->managed_environment_id)
->where('workspace_id', (int) $report->workspace_id) ->where('workspace_id', (int) $report->workspace_id)
->where('report_type', (string) $report->report_type) ->where('report_type', (string) $report->report_type)
->orderByDesc('created_at') ->orderByDesc('created_at')
@ -564,7 +564,7 @@ public static function currentReportUrlFor(StoredReport $report): ?string
$tenant = $current->tenant ?? static::resolveTenantContextForCurrentPanel(); $tenant = $current->tenant ?? static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return null; return null;
} }
@ -577,7 +577,7 @@ public static function scopeCurrentRecords(Builder $query): Builder
$subQuery $subQuery
->selectRaw('1') ->selectRaw('1')
->from('stored_reports as newer_stored_reports') ->from('stored_reports as newer_stored_reports')
->whereColumn('newer_stored_reports.tenant_id', 'stored_reports.tenant_id') ->whereColumn('newer_stored_reports.managed_environment_id', 'stored_reports.managed_environment_id')
->whereColumn('newer_stored_reports.workspace_id', 'stored_reports.workspace_id') ->whereColumn('newer_stored_reports.workspace_id', 'stored_reports.workspace_id')
->whereColumn('newer_stored_reports.report_type', 'stored_reports.report_type') ->whereColumn('newer_stored_reports.report_type', 'stored_reports.report_type')
->where(function ($newerQuery): void { ->where(function ($newerQuery): void {
@ -659,7 +659,7 @@ private static function tenantOverviewUrl(): string
{ {
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return '#'; return '#';
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
namespace App\Filament\Resources\TenantResource\Pages; namespace App\Filament\Resources\TenantResource\Pages;
use App\Filament\Resources\TenantResource; use App\Filament\Resources\TenantResource;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Tenants\TenantActionSurface; use App\Support\Tenants\TenantActionSurface;
use Filament\Actions; use Filament\Actions;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
@ -28,7 +28,7 @@ protected function getHeaderActions(): array
->label('Lifecycle') ->label('Lifecycle')
->icon('heroicon-o-archive-box') ->icon('heroicon-o-archive-box')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
&& in_array( && in_array(
TenantResource::lifecycleActionDescriptor($this->getRecord(), TenantActionSurface::TenantEditHeader)?->key, TenantResource::lifecycleActionDescriptor($this->getRecord(), TenantActionSurface::TenantEditHeader)?->key,
['archive', 'restore'], ['archive', 'restore'],

View File

@ -11,7 +11,7 @@ class ManageTenantMemberships extends ViewTenant
public function getSubheading(): ?string public function getSubheading(): ?string
{ {
return 'Tenant access is managed here. Use the tenant overview for provider state, verification, and operational context.'; return 'ManagedEnvironment access is managed here. Use the tenant overview for provider state, verification, and operational context.';
} }
protected function getHeaderWidgets(): array protected function getHeaderWidgets(): array

View File

@ -8,7 +8,7 @@
use App\Filament\Widgets\Tenant\TenantArchivedBanner; use App\Filament\Widgets\Tenant\TenantArchivedBanner;
use App\Filament\Widgets\Tenant\TenantVerificationReport; use App\Filament\Widgets\Tenant\TenantVerificationReport;
use App\Jobs\RefreshTenantRbacHealthJob; use App\Jobs\RefreshTenantRbacHealthJob;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Services\OperationRunService; use App\Services\OperationRunService;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
@ -62,7 +62,7 @@ protected function getHeaderActions(): array
->label('External links') ->label('External links')
->icon('heroicon-o-arrow-top-right-on-square') ->icon('heroicon-o-arrow-top-right-on-square')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
&& TenantResource::tenantViewExternalGroupVisible($this->getRecord())), && TenantResource::tenantViewExternalGroupVisible($this->getRecord())),
Actions\ActionGroup::make([ Actions\ActionGroup::make([
TenantResource::makeSyncTenantAction(), TenantResource::makeSyncTenantAction(),
@ -74,8 +74,8 @@ protected function getHeaderActions(): array
->icon('heroicon-o-arrow-path') ->icon('heroicon-o-arrow-path')
->color('primary') ->color('primary')
->requiresConfirmation() ->requiresConfirmation()
->visible(fn (Tenant $record): bool => $record->isActive()) ->visible(fn (ManagedEnvironment $record): bool => $record->isActive())
->action(function (Tenant $record): void { ->action(function (ManagedEnvironment $record): void {
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User) { if (! $user instanceof User) {
@ -93,7 +93,7 @@ protected function getHeaderActions(): array
tenant: $record, tenant: $record,
type: OperationRunType::RbacHealthCheck->value, type: OperationRunType::RbacHealthCheck->value,
inputs: [ inputs: [
'tenant_id' => (int) $record->getKey(), 'managed_environment_id' => (int) $record->getKey(),
'surface' => 'tenant_view_header', 'surface' => 'tenant_view_header',
], ],
initiator: $user, initiator: $user,
@ -139,7 +139,7 @@ protected function getHeaderActions(): array
->label('Setup') ->label('Setup')
->icon('heroicon-o-wrench-screwdriver') ->icon('heroicon-o-wrench-screwdriver')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
&& TenantResource::tenantViewSetupGroupVisible($this->getRecord())), && TenantResource::tenantViewSetupGroupVisible($this->getRecord())),
Actions\ActionGroup::make([ Actions\ActionGroup::make([
TenantResource::makeTenantViewMarkReviewedAction(), TenantResource::makeTenantViewMarkReviewedAction(),
@ -148,7 +148,7 @@ protected function getHeaderActions(): array
->label('Triage') ->label('Triage')
->icon('heroicon-o-check-circle') ->icon('heroicon-o-check-circle')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
&& TenantResource::tenantViewTriageGroupVisible($this->getRecord())), && TenantResource::tenantViewTriageGroupVisible($this->getRecord())),
Actions\ActionGroup::make([ Actions\ActionGroup::make([
TenantResource::makeRestoreTenantAction(TenantActionSurface::TenantViewHeader), TenantResource::makeRestoreTenantAction(TenantActionSurface::TenantViewHeader),
@ -157,7 +157,7 @@ protected function getHeaderActions(): array
->label('Lifecycle') ->label('Lifecycle')
->icon('heroicon-o-archive-box') ->icon('heroicon-o-archive-box')
->color('gray') ->color('gray')
->visible(fn (): bool => $this->getRecord() instanceof Tenant ->visible(fn (): bool => $this->getRecord() instanceof ManagedEnvironment
&& TenantResource::tenantViewLifecycleGroupVisible($this->getRecord())), && TenantResource::tenantViewLifecycleGroupVisible($this->getRecord())),
])); ]));
} }

View File

@ -3,8 +3,8 @@
namespace App\Filament\Resources\TenantResource\RelationManagers; namespace App\Filament\Resources\TenantResource\RelationManagers;
use App\Filament\Resources\TenantResource\Pages\ManageTenantMemberships; use App\Filament\Resources\TenantResource\Pages\ManageTenantMemberships;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantMembership; use App\Models\ManagedEnvironmentMembership;
use App\Models\User; use App\Models\User;
use App\Services\Auth\CapabilityResolver; use App\Services\Auth\CapabilityResolver;
use App\Services\Auth\TenantMembershipManager; use App\Services\Auth\TenantMembershipManager;
@ -30,7 +30,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
{ {
return ActionSurfaceDeclaration::forRelationManager(ActionSurfaceProfile::RelationManager) return ActionSurfaceDeclaration::forRelationManager(ActionSurfaceProfile::RelationManager)
->satisfy(ActionSurfaceSlot::ListHeader, 'Add member action is available in the relation header.') ->satisfy(ActionSurfaceSlot::ListHeader, 'Add member action is available in the relation header.')
->exempt(ActionSurfaceSlot::InspectAffordance, 'Tenant membership rows are managed inline and have no separate inspect destination.') ->exempt(ActionSurfaceSlot::InspectAffordance, 'ManagedEnvironment membership rows are managed inline and have no separate inspect destination.')
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Change role and remove stay direct for focused inline membership management.') ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Change role and remove stay direct for focused inline membership management.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk membership mutations are intentionally omitted.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk membership mutations are intentionally omitted.')
->exempt(ActionSurfaceSlot::ListEmptyState, 'No empty-state actions are exposed; add member remains available in the header.'); ->exempt(ActionSurfaceSlot::ListEmptyState, 'No empty-state actions are exposed; add member remains available in the header.');
@ -38,7 +38,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
{ {
if (! $ownerRecord instanceof Tenant) { if (! $ownerRecord instanceof ManagedEnvironment) {
return false; return false;
} }
@ -74,7 +74,7 @@ public function table(Table $table): Table
->searchable(), ->searchable(),
Tables\Columns\TextColumn::make('user_domain') Tables\Columns\TextColumn::make('user_domain')
->label(__('Domain')) ->label(__('Domain'))
->getStateUsing(function (TenantMembership $record): ?string { ->getStateUsing(function (ManagedEnvironmentMembership $record): ?string {
$email = $record->user?->email; $email = $record->user?->email;
if (! is_string($email) || $email === '' || ! str_contains($email, '@')) { if (! is_string($email) || $email === '' || ! str_contains($email, '@')) {
@ -124,7 +124,7 @@ public function table(Table $table): Table
->action(function (array $data, TenantMembershipManager $manager): void { ->action(function (array $data, TenantMembershipManager $manager): void {
$tenant = $this->getOwnerRecord(); $tenant = $this->getOwnerRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -184,10 +184,10 @@ public function table(Table $table): Table
'readonly' => __('Readonly'), 'readonly' => __('Readonly'),
]), ]),
]) ])
->action(function (TenantMembership $record, array $data, TenantMembershipManager $manager): void { ->action(function (ManagedEnvironmentMembership $record, array $data, TenantMembershipManager $manager): void {
$tenant = $this->getOwnerRecord(); $tenant = $this->getOwnerRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }
@ -228,10 +228,10 @@ public function table(Table $table): Table
->color('danger') ->color('danger')
->icon('heroicon-o-x-mark') ->icon('heroicon-o-x-mark')
->requiresConfirmation() ->requiresConfirmation()
->action(function (TenantMembership $record, TenantMembershipManager $manager): void { ->action(function (ManagedEnvironmentMembership $record, TenantMembershipManager $manager): void {
$tenant = $this->getOwnerRecord(); $tenant = $this->getOwnerRecord();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
abort(404); abort(404);
} }

View File

@ -11,7 +11,7 @@
use App\Exceptions\Entitlements\WorkspaceEntitlementBlockedException; use App\Exceptions\Entitlements\WorkspaceEntitlementBlockedException;
use App\Models\EvidenceSnapshot; use App\Models\EvidenceSnapshot;
use App\Models\ReviewPack; use App\Models\ReviewPack;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantReview; use App\Models\TenantReview;
use App\Models\TenantReviewSection; use App\Models\TenantReviewSection;
use App\Models\User; use App\Models\User;
@ -112,7 +112,7 @@ public static function canViewAny(): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return false; return false;
} }
@ -128,7 +128,7 @@ public static function canView(Model $record): bool
$tenant = static::resolveTenantContextForCurrentPanel(); $tenant = static::resolveTenantContextForCurrentPanel();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User || ! $record instanceof TenantReview) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User || ! $record instanceof TenantReview) {
return false; return false;
} }
@ -136,7 +136,7 @@ public static function canView(Model $record): bool
return false; return false;
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
return false; return false;
} }
@ -149,7 +149,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
->satisfy(ActionSurfaceSlot::ListHeader, 'Create review is available from the review library header.') ->satisfy(ActionSurfaceSlot::ListHeader, 'Create review is available from the review library header.')
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value) ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty state includes exactly one Create first review CTA.') ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty state includes exactly one Create first review CTA.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Tenant reviews do not expose bulk actions in the first slice.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'ManagedEnvironment reviews do not expose bulk actions in the first slice.')
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Clickable-row inspection stays primary while Export executive pack remains the only inline row shortcut.') ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Clickable-row inspection stays primary while Export executive pack remains the only inline row shortcut.')
->satisfy(ActionSurfaceSlot::DetailHeader, 'Detail exposes one dominant lifecycle action, groups the remaining lifecycle actions under "More", keeps archive in a danger bucket, and renders operation/export/evidence navigation in contextual summary content.'); ->satisfy(ActionSurfaceSlot::DetailHeader, 'Detail exposes one dominant lifecycle action, groups the remaining lifecycle actions under "More", keeps archive in a danger bucket, and renders operation/export/evidence navigation in contextual summary content.');
} }
@ -404,7 +404,7 @@ public static function executeCreateReview(array $data): void
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
$user = auth()->user(); $user = auth()->user();
if (! $tenant instanceof Tenant || ! $user instanceof User) { if (! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
Notification::make()->danger()->title(__('localization.review.unable_create_missing_context'))->send(); Notification::make()->danger()->title(__('localization.review.unable_create_missing_context'))->send();
return; return;
@ -422,7 +422,7 @@ public static function executeCreateReview(array $data): void
$snapshot = is_numeric($snapshotId) $snapshot = is_numeric($snapshotId)
? EvidenceSnapshot::query() ? EvidenceSnapshot::query()
->whereKey((int) $snapshotId) ->whereKey((int) $snapshotId)
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->first() ->first()
: null; : null;
@ -474,23 +474,23 @@ public static function executeCreateReview(array $data): void
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
public static function reviewPackGenerationDecision(?Tenant $tenant = null): array public static function reviewPackGenerationDecision(?ManagedEnvironment $tenant = null): array
{ {
$tenant ??= Filament::getTenant(); $tenant ??= Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return app(ReviewPackService::class)->reviewPackGenerationDecisionForTenant($tenant); return app(ReviewPackService::class)->reviewPackGenerationDecisionForTenant($tenant);
} }
public static function reviewPackGenerationBlocked(?Tenant $tenant = null): bool public static function reviewPackGenerationBlocked(?ManagedEnvironment $tenant = null): bool
{ {
return (bool) (static::reviewPackGenerationDecision($tenant)['is_blocked'] ?? false); return (bool) (static::reviewPackGenerationDecision($tenant)['is_blocked'] ?? false);
} }
public static function reviewPackGenerationBlockReason(?Tenant $tenant = null): ?string public static function reviewPackGenerationBlockReason(?ManagedEnvironment $tenant = null): ?string
{ {
$decision = static::reviewPackGenerationDecision($tenant); $decision = static::reviewPackGenerationDecision($tenant);
@ -503,7 +503,7 @@ public static function reviewPackGenerationBlockReason(?Tenant $tenant = null):
return is_string($reason) && $reason !== '' ? $reason : null; return is_string($reason) && $reason !== '' ? $reason : null;
} }
public static function reviewPackGenerationWarningReason(?Tenant $tenant = null): ?string public static function reviewPackGenerationWarningReason(?ManagedEnvironment $tenant = null): ?string
{ {
$decision = static::reviewPackGenerationDecision($tenant); $decision = static::reviewPackGenerationDecision($tenant);
@ -516,12 +516,12 @@ public static function reviewPackGenerationWarningReason(?Tenant $tenant = null)
return is_string($reason) && $reason !== '' ? $reason : null; return is_string($reason) && $reason !== '' ? $reason : null;
} }
public static function reviewPackGenerationActionTooltip(?Tenant $tenant = null): ?string public static function reviewPackGenerationActionTooltip(?ManagedEnvironment $tenant = null): ?string
{ {
$tenant ??= static::panelTenantContext(); $tenant ??= static::panelTenantContext();
$user = auth()->user(); $user = auth()->user();
if ($tenant instanceof Tenant && $user instanceof User && ! $user->can(Capabilities::TENANT_REVIEW_MANAGE, $tenant)) { if ($tenant instanceof ManagedEnvironment && $user instanceof User && ! $user->can(Capabilities::TENANT_REVIEW_MANAGE, $tenant)) {
return AuthUiTooltips::insufficientPermission(); return AuthUiTooltips::insufficientPermission();
} }
@ -534,7 +534,7 @@ public static function executeExport(TenantReview $review): void
$review->loadMissing(['tenant', 'currentExportReviewPack']); $review->loadMissing(['tenant', 'currentExportReviewPack']);
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User || ! $review->tenant instanceof Tenant) { if (! $user instanceof User || ! $review->tenant instanceof ManagedEnvironment) {
Notification::make()->danger()->title(__('localization.review.unable_export_missing_context'))->send(); Notification::make()->danger()->title(__('localization.review.unable_export_missing_context'))->send();
return; return;
@ -602,7 +602,7 @@ public static function executeExport(TenantReview $review): void
public static function tenantScopedUrl( public static function tenantScopedUrl(
string $page = 'index', string $page = 'index',
array $parameters = [], array $parameters = [],
?Tenant $tenant = null, ?ManagedEnvironment $tenant = null,
?string $panel = null, ?string $panel = null,
): string { ): string {
$panelId = $panel ?? 'tenant'; $panelId = $panel ?? 'tenant';
@ -617,12 +617,12 @@ private static function evidenceSnapshotOptions(): array
{ {
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }
return EvidenceSnapshot::query() return EvidenceSnapshot::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->whereNotNull('generated_at') ->whereNotNull('generated_at')
->orderByDesc('generated_at') ->orderByDesc('generated_at')
->orderByDesc('id') ->orderByDesc('id')
@ -728,7 +728,7 @@ private static function customerEvidenceStatusLabel(TenantReview $record): strin
return __('localization.review.evidence_pending'); return __('localization.review.evidence_pending');
} }
if (! $user instanceof User || ! $tenant instanceof Tenant || ! $user->can(Capabilities::EVIDENCE_VIEW, $tenant)) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment || ! $user->can(Capabilities::EVIDENCE_VIEW, $tenant)) {
return __('localization.review.evidence_restricted'); return __('localization.review.evidence_restricted');
} }
@ -799,7 +799,7 @@ private static function governancePackageAvailability(TenantReview $record): arr
]; ];
} }
if (! $user instanceof User || ! $tenant instanceof Tenant || ! $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant)) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment || ! $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant)) {
return [ return [
'state' => 'blocked', 'state' => 'blocked',
'label' => __('localization.review.governance_package_blocked'), 'label' => __('localization.review.governance_package_blocked'),
@ -907,7 +907,7 @@ private static function sectionPresentation(TenantReviewSection $section): array
$tenant = $section->tenant; $tenant = $section->tenant;
$links = []; $links = [];
if ($section->isControlInterpretation() && $review instanceof TenantReview && $tenant instanceof Tenant && $review->evidenceSnapshot instanceof EvidenceSnapshot) { if ($section->isControlInterpretation() && $review instanceof TenantReview && $tenant instanceof ManagedEnvironment && $review->evidenceSnapshot instanceof EvidenceSnapshot) {
$user = auth()->user(); $user = auth()->user();
if ($user instanceof User && $user->can(Capabilities::EVIDENCE_VIEW, $tenant)) { if ($user instanceof User && $user->can(Capabilities::EVIDENCE_VIEW, $tenant)) {

View File

@ -7,7 +7,7 @@
use App\Filament\Pages\Reviews\CustomerReviewWorkspace; use App\Filament\Pages\Reviews\CustomerReviewWorkspace;
use App\Filament\Resources\TenantReviewResource; use App\Filament\Resources\TenantReviewResource;
use App\Models\ReviewPack; use App\Models\ReviewPack;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantReview; use App\Models\TenantReview;
use App\Models\User; use App\Models\User;
use App\Services\ReviewPackService; use App\Services\ReviewPackService;
@ -48,11 +48,11 @@ protected function authorizeAccess(): void
$record = $this->getRecord(); $record = $this->getRecord();
$user = auth()->user(); $user = auth()->user();
if (! $user instanceof User || ! $tenant instanceof Tenant || ! $record instanceof TenantReview) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment || ! $record instanceof TenantReview) {
abort(404); abort(404);
} }
if ((int) $record->tenant_id !== (int) $tenant->getKey()) { if ((int) $record->managed_environment_id !== (int) $tenant->getKey()) {
abort(404); abort(404);
} }
@ -370,7 +370,7 @@ private function currentReviewPackDownloadUrl(): ?string
$tenant = $this->record->tenant; $tenant = $this->record->tenant;
$user = auth()->user(); $user = auth()->user();
if (! $pack instanceof ReviewPack || ! $tenant instanceof Tenant || ! $user instanceof User) { if (! $pack instanceof ReviewPack || ! $tenant instanceof ManagedEnvironment || ! $user instanceof User) {
return null; return null;
} }
@ -408,7 +408,7 @@ private function currentReviewPackUnavailableReason(): ?string
return __('localization.review.customer_review_pack_missing'); return __('localization.review.customer_review_pack_missing');
} }
if (! $user instanceof User || ! $tenant instanceof Tenant || ! $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant)) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment || ! $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant)) {
return __('localization.review.customer_review_pack_forbidden'); return __('localization.review.customer_review_pack_forbidden');
} }
@ -437,7 +437,7 @@ private function auditCustomerWorkspaceOpen(): void
$user = auth()->user(); $user = auth()->user();
$tenant = $this->record->tenant; $tenant = $this->record->tenant;
if (! $user instanceof User || ! $tenant instanceof Tenant) { if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
return; return;
} }
@ -455,7 +455,7 @@ private function auditCustomerWorkspaceOpen(): void
actor: $user, actor: $user,
resourceType: 'tenant_review', resourceType: 'tenant_review',
resourceId: (string) $this->record->getKey(), resourceId: (string) $this->record->getKey(),
targetLabel: sprintf('Tenant review #%d', (int) $this->record->getKey()), targetLabel: sprintf('ManagedEnvironment review #%d', (int) $this->record->getKey()),
tenant: $tenant, tenant: $tenant,
); );
} }

View File

@ -75,7 +75,7 @@ public static function previousRun(OperationRun $run, array $report): ?Operation
$previous = OperationRun::query() $previous = OperationRun::query()
->whereKey($previousReportId) ->whereKey($previousReportId)
->where('tenant_id', (int) $run->tenant_id) ->where('managed_environment_id', (int) $run->managed_environment_id)
->where('workspace_id', (int) $run->workspace_id) ->where('workspace_id', (int) $run->workspace_id)
->first(); ->first();

View File

@ -5,7 +5,7 @@
namespace App\Filament\System\Pages\Auth; namespace App\Filament\System\Pages\Auth;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Services\Intune\AuditLogger; use App\Services\Intune\AuditLogger;
use Filament\Auth\Http\Responses\Contracts\LoginResponse; use Filament\Auth\Http\Responses\Contracts\LoginResponse;
use Filament\Auth\Pages\Login as BaseLogin; use Filament\Auth\Pages\Login as BaseLogin;
@ -88,7 +88,7 @@ private function throttleKey(string $email): string
private function audit(string $status, string $email, ?PlatformUser $actor, ?string $reason = null): void private function audit(string $status, string $email, ?PlatformUser $actor, ?string $reason = null): void
{ {
$tenant = Tenant::query()->where('external_id', 'platform')->first(); $tenant = ManagedEnvironment::query()->where('slug', 'platform')->first();
if (! $tenant) { if (! $tenant) {
return; return;

View File

@ -5,7 +5,7 @@
namespace App\Filament\System\Pages\Directory; namespace App\Filament\System\Pages\Directory;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\Auth\PlatformCapabilities; use App\Support\Auth\PlatformCapabilities;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer; use App\Support\Badges\BadgeRenderer;
@ -41,7 +41,7 @@ public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport) return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly, ActionSurfaceType::ReadOnlyRegistryReport)
->exempt(ActionSurfaceSlot::ListHeader, 'System tenant directory stays scan-first and does not expose page header actions.') ->exempt(ActionSurfaceSlot::ListHeader, 'System tenant directory stays scan-first and does not expose page header actions.')
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value) ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Tenant directory rows navigate directly to the detail page and have no secondary actions.') ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'ManagedEnvironment directory rows navigate directly to the detail page and have no secondary actions.')
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'System tenant directory does not expose bulk actions.') ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'System tenant directory does not expose bulk actions.')
->satisfy(ActionSurfaceSlot::ListEmptyState, 'The empty state explains that tenants appear here after onboarding and inventory sync.'); ->satisfy(ActionSurfaceSlot::ListEmptyState, 'The empty state explains that tenants appear here after onboarding and inventory sync.');
} }
@ -65,7 +65,7 @@ public function table(Table $table): Table
->defaultSort('name') ->defaultSort('name')
->paginated(\App\Support\Filament\TablePaginationProfiles::customPage()) ->paginated(\App\Support\Filament\TablePaginationProfiles::customPage())
->query(function (): Builder { ->query(function (): Builder {
return Tenant::query() return ManagedEnvironment::query()
->with('workspace') ->with('workspace')
->withCount([ ->withCount([
'providerConnections as critical_provider_connections_count' => fn (Builder $query): Builder => $query 'providerConnections as critical_provider_connections_count' => fn (Builder $query): Builder => $query
@ -81,7 +81,7 @@ public function table(Table $table): Table
}) })
->columns([ ->columns([
TextColumn::make('name') TextColumn::make('name')
->label('Tenant') ->label('ManagedEnvironment')
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('workspace.name') TextColumn::make('workspace.name')
@ -96,21 +96,21 @@ public function table(Table $table): Table
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)),
TextColumn::make('health') TextColumn::make('health')
->label('Health') ->label('Health')
->state(fn (Tenant $record): string => $this->healthForTenant($record)) ->state(fn (ManagedEnvironment $record): string => $this->healthForTenant($record))
->badge() ->badge()
->formatStateUsing(BadgeRenderer::label(BadgeDomain::SystemHealth)) ->formatStateUsing(BadgeRenderer::label(BadgeDomain::SystemHealth))
->color(BadgeRenderer::color(BadgeDomain::SystemHealth)) ->color(BadgeRenderer::color(BadgeDomain::SystemHealth))
->icon(BadgeRenderer::icon(BadgeDomain::SystemHealth)) ->icon(BadgeRenderer::icon(BadgeDomain::SystemHealth))
->iconColor(BadgeRenderer::iconColor(BadgeDomain::SystemHealth)), ->iconColor(BadgeRenderer::iconColor(BadgeDomain::SystemHealth)),
]) ])
->recordUrl(fn (Tenant $record): string => SystemDirectoryLinks::tenantDetail($record)) ->recordUrl(fn (ManagedEnvironment $record): string => SystemDirectoryLinks::tenantDetail($record))
->emptyStateHeading('No tenants found') ->emptyStateHeading('No tenants found')
->emptyStateDescription('Tenants will appear here as inventory is onboarded.'); ->emptyStateDescription('Tenants will appear here as inventory is onboarded.');
} }
private function healthForTenant(Tenant $tenant): string private function healthForTenant(ManagedEnvironment $tenant): string
{ {
if ((string) $tenant->status === Tenant::STATUS_ARCHIVED) { if ((string) $tenant->status === ManagedEnvironment::STATUS_ARCHIVED) {
return 'unknown'; return 'unknown';
} }
@ -125,7 +125,7 @@ private function healthForTenant(Tenant $tenant): string
return 'warn'; return 'warn';
} }
if ((string) $tenant->status === Tenant::STATUS_ONBOARDING) { if ((string) $tenant->status === ManagedEnvironment::STATUS_ONBOARDING) {
return 'warn'; return 'warn';
} }

View File

@ -8,7 +8,7 @@
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\ProviderConnection; use App\Models\ProviderConnection;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\TenantPermission; use App\Models\TenantPermission;
use App\Support\Auth\PlatformCapabilities; use App\Support\Auth\PlatformCapabilities;
use App\Support\CustomerHealth\WorkspaceHealthSummaryQuery; use App\Support\CustomerHealth\WorkspaceHealthSummaryQuery;
@ -29,7 +29,7 @@ class ViewTenant extends Page
protected string $view = 'filament.system.pages.directory.view-tenant'; protected string $view = 'filament.system.pages.directory.view-tenant';
public Tenant $tenant; public ManagedEnvironment $tenant;
public static function canAccess(): bool public static function canAccess(): bool
{ {
@ -39,7 +39,7 @@ public static function canAccess(): bool
&& $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW); && $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
} }
public function mount(Tenant $tenant): void public function mount(ManagedEnvironment $tenant): void
{ {
$tenant->load('workspace'); $tenant->load('workspace');
@ -52,7 +52,7 @@ public function mount(Tenant $tenant): void
public function providerConnections(): Collection public function providerConnections(): Collection
{ {
return ProviderConnection::query() return ProviderConnection::query()
->where('tenant_id', (int) $this->tenant->getKey()) ->where('managed_environment_id', (int) $this->tenant->getKey())
->orderByDesc('is_default') ->orderByDesc('is_default')
->orderBy('provider') ->orderBy('provider')
->get([ ->get([
@ -74,7 +74,7 @@ public function providerConnections(): Collection
public function tenantPermissions(): Collection public function tenantPermissions(): Collection
{ {
return TenantPermission::query() return TenantPermission::query()
->where('tenant_id', (int) $this->tenant->getKey()) ->where('managed_environment_id', (int) $this->tenant->getKey())
->orderBy('permission_key') ->orderBy('permission_key')
->limit(20) ->limit(20)
->get(['id', 'permission_key', 'status', 'last_checked_at']); ->get(['id', 'permission_key', 'status', 'last_checked_at']);
@ -86,7 +86,7 @@ public function tenantPermissions(): Collection
public function recentRuns(): Collection public function recentRuns(): Collection
{ {
return OperationRun::query() return OperationRun::query()
->where('tenant_id', (int) $this->tenant->getKey()) ->where('managed_environment_id', (int) $this->tenant->getKey())
->latest('id') ->latest('id')
->limit(8) ->limit(8)
->get(['id', 'type', 'created_at']) ->get(['id', 'type', 'created_at'])

View File

@ -8,7 +8,7 @@
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\SupportAccessGrant; use App\Models\SupportAccessGrant;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\Workspace; use App\Models\Workspace;
use App\Models\WorkspaceSubscription; use App\Models\WorkspaceSubscription;
use App\Services\Auth\SupportAccessGrantManager; use App\Services\Auth\SupportAccessGrantManager;
@ -62,15 +62,15 @@ public function mount(Workspace $workspace): void
} }
/** /**
* @return Collection<int, Tenant> * @return Collection<int, ManagedEnvironment>
*/ */
public function workspaceTenants(): Collection public function workspaceTenants(): Collection
{ {
return Tenant::query() return ManagedEnvironment::query()
->where('workspace_id', (int) $this->workspace->getKey()) ->where('workspace_id', (int) $this->workspace->getKey())
->orderBy('name') ->orderBy('name')
->limit(10) ->limit(10)
->get(['id', 'name', 'status', 'workspace_id', 'external_id']); ->get(['id', 'name', 'lifecycle_status', 'workspace_id', 'slug']);
} }
/** /**

View File

@ -6,7 +6,7 @@
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\Workspace; use App\Models\Workspace;
use App\Support\Auth\PlatformCapabilities; use App\Support\Auth\PlatformCapabilities;
use App\Support\Badges\BadgeDomain; use App\Support\Badges\BadgeDomain;
@ -72,7 +72,7 @@ public function table(Table $table): Table
return Workspace::query() return Workspace::query()
->withCount([ ->withCount([
'tenants', 'tenants',
'tenants as onboarding_tenants_count' => fn (Builder $query): Builder => $query->where('status', Tenant::STATUS_ONBOARDING), 'tenants as onboarding_tenants_count' => fn (Builder $query): Builder => $query->where('lifecycle_status', ManagedEnvironment::STATUS_ONBOARDING),
]); ]);
}) })
->columns([ ->columns([

View File

@ -7,7 +7,7 @@
use App\Models\AuditLog; use App\Models\AuditLog;
use App\Models\OperationalControlActivation; use App\Models\OperationalControlActivation;
use App\Models\PlatformUser; use App\Models\PlatformUser;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\Workspace; use App\Models\Workspace;
use App\Services\Audit\AuditRecorder; use App\Services\Audit\AuditRecorder;
use App\Services\Audit\WorkspaceAuditLogger; use App\Services\Audit\WorkspaceAuditLogger;
@ -148,9 +148,9 @@ public function scopeImpactPreview(string $controlKey, string $scopeType, ?int $
]; ];
} }
$tenantCount = Tenant::query() $tenantCount = ManagedEnvironment::query()
->where('workspace_id', (int) $workspace->getKey()) ->where('workspace_id', (int) $workspace->getKey())
->where('external_id', '!=', 'platform') ->where('slug', '!=', 'platform')
->count(); ->count();
return [ return [
@ -163,12 +163,12 @@ public function scopeImpactPreview(string $controlKey, string $scopeType, ?int $
]; ];
} }
$tenantCount = Tenant::query() $tenantCount = ManagedEnvironment::query()
->where('external_id', '!=', 'platform') ->where('slug', '!=', 'platform')
->count(); ->count();
$workspaceCount = Tenant::query() $workspaceCount = ManagedEnvironment::query()
->where('external_id', '!=', 'platform') ->where('slug', '!=', 'platform')
->distinct('workspace_id') ->distinct('workspace_id')
->count('workspace_id'); ->count('workspace_id');

View File

@ -162,7 +162,7 @@ public function table(Table $table): Table
->label('Workspace') ->label('Workspace')
->toggleable(), ->toggleable(),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless') ->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
->toggleable(), ->toggleable(),
TextColumn::make('created_at')->label('Started')->since(), TextColumn::make('created_at')->label('Started')->since(),

View File

@ -143,7 +143,7 @@ public function table(Table $table): Table
->label('Workspace') ->label('Workspace')
->toggleable(), ->toggleable(),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless') ->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
->toggleable(), ->toggleable(),
TextColumn::make('initiator_name')->label('Initiator'), TextColumn::make('initiator_name')->label('Initiator'),

View File

@ -146,7 +146,7 @@ public function table(Table $table): Table
->label('Workspace') ->label('Workspace')
->toggleable(), ->toggleable(),
TextColumn::make('tenant.name') TextColumn::make('tenant.name')
->label('Tenant') ->label('ManagedEnvironment')
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless') ->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
->toggleable(), ->toggleable(),
TextColumn::make('created_at')->label('Started')->since(), TextColumn::make('created_at')->label('Started')->since(),

View File

@ -5,7 +5,7 @@
namespace App\Filament\System\Widgets; namespace App\Filament\System\Widgets;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\Workspace; use App\Models\Workspace;
use App\Support\OperationCatalog; use App\Support\OperationCatalog;
use App\Support\OperationRunOutcome; use App\Support\OperationRunOutcome;
@ -35,11 +35,11 @@ protected function getViewData(): array
/** @var Collection<int, OperationRun> $grouped */ /** @var Collection<int, OperationRun> $grouped */
$grouped = OperationRun::query() $grouped = OperationRun::query()
->selectRaw('workspace_id, tenant_id, type, COUNT(*) AS failed_count') ->selectRaw('workspace_id, managed_environment_id, type, COUNT(*) AS failed_count')
->where('created_at', '>=', $start) ->where('created_at', '>=', $start)
->where('status', OperationRunStatus::Completed->value) ->where('status', OperationRunStatus::Completed->value)
->where('outcome', OperationRunOutcome::Failed->value) ->where('outcome', OperationRunOutcome::Failed->value)
->groupBy('workspace_id', 'tenant_id', 'type') ->groupBy('workspace_id', 'managed_environment_id', 'type')
->orderByDesc('failed_count') ->orderByDesc('failed_count')
->limit(10) ->limit(10)
->get(); ->get();
@ -53,7 +53,7 @@ protected function getViewData(): array
->all(); ->all();
$tenantIds = $grouped $tenantIds = $grouped
->pluck('tenant_id') ->pluck('managed_environment_id')
->filter(fn ($value): bool => is_numeric($value)) ->filter(fn ($value): bool => is_numeric($value))
->map(fn ($value): int => (int) $value) ->map(fn ($value): int => (int) $value)
->unique() ->unique()
@ -65,7 +65,7 @@ protected function getViewData(): array
->pluck('name', 'id') ->pluck('name', 'id')
->all(); ->all();
$tenantNames = Tenant::query() $tenantNames = ManagedEnvironment::query()
->whereIn('id', $tenantIds) ->whereIn('id', $tenantIds)
->pluck('name', 'id') ->pluck('name', 'id')
->all(); ->all();
@ -74,14 +74,14 @@ protected function getViewData(): array
'windowLabel' => SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours', 'windowLabel' => SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours',
'offenders' => $grouped->map(function (OperationRun $record) use ($workspaceNames, $tenantNames): array { 'offenders' => $grouped->map(function (OperationRun $record) use ($workspaceNames, $tenantNames): array {
$workspaceId = is_numeric($record->workspace_id) ? (int) $record->workspace_id : null; $workspaceId = is_numeric($record->workspace_id) ? (int) $record->workspace_id : null;
$tenantId = is_numeric($record->tenant_id) ? (int) $record->tenant_id : null; $tenantId = is_numeric($record->managed_environment_id) ? (int) $record->managed_environment_id : null;
return [ return [
'workspace_label' => $workspaceId !== null 'workspace_label' => $workspaceId !== null
? ($workspaceNames[$workspaceId] ?? ('Workspace #'.$workspaceId)) ? ($workspaceNames[$workspaceId] ?? ('Workspace #'.$workspaceId))
: 'Unknown workspace', : 'Unknown workspace',
'tenant_label' => $tenantId !== null 'tenant_label' => $tenantId !== null
? ($tenantNames[$tenantId] ?? ('Tenant #'.$tenantId)) ? ($tenantNames[$tenantId] ?? ('ManagedEnvironment #'.$tenantId))
: 'Tenantless', : 'Tenantless',
'operation_label' => OperationCatalog::label((string) $record->type), 'operation_label' => OperationCatalog::label((string) $record->type),
'failed_count' => (int) $record->getAttribute('failed_count'), 'failed_count' => (int) $record->getAttribute('failed_count'),

View File

@ -10,7 +10,7 @@
use App\Models\AlertDelivery; use App\Models\AlertDelivery;
use App\Models\AlertDestination; use App\Models\AlertDestination;
use App\Models\AlertRule; use App\Models\AlertRule;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Support\OperateHub\OperateHubShell; use App\Support\OperateHub\OperateHubShell;
use App\Support\Workspaces\WorkspaceContext; use App\Support\Workspaces\WorkspaceContext;
@ -94,12 +94,12 @@ private function deliveriesQueryForViewer(User $user, int $workspaceId): Builder
{ {
$query = AlertDelivery::query() $query = AlertDelivery::query()
->where('workspace_id', $workspaceId) ->where('workspace_id', $workspaceId)
->whereIn('tenant_id', $user->tenantMemberships()->select('tenant_id')); ->whereIn('managed_environment_id', $user->tenantMemberships()->select('managed_environment_id'));
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request()); $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
if ($activeTenant instanceof Tenant) { if ($activeTenant instanceof ManagedEnvironment) {
$query->where('tenant_id', (int) $activeTenant->getKey()); $query->where('managed_environment_id', (int) $activeTenant->getKey());
} }
return $query; return $query;

View File

@ -8,7 +8,7 @@
use App\Filament\Resources\FindingResource; use App\Filament\Resources\FindingResource;
use App\Models\FindingException; use App\Models\FindingException;
use App\Models\OperationRun; use App\Models\OperationRun;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Models\User; use App\Models\User;
use App\Support\Auth\Capabilities; use App\Support\Auth\Capabilities;
use App\Support\Baselines\BaselineCompareSummaryAssessment; use App\Support\Baselines\BaselineCompareSummaryAssessment;
@ -43,7 +43,7 @@ protected function getViewData(): array
'summaryAssessment' => null, 'summaryAssessment' => null,
]; ];
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return $empty; return $empty;
} }
@ -55,7 +55,7 @@ protected function getViewData(): array
$tenantLandingUrl = BaselineCompareLanding::getUrl(panel: 'tenant', tenant: $tenant); $tenantLandingUrl = BaselineCompareLanding::getUrl(panel: 'tenant', tenant: $tenant);
$operationsFollowUpCount = (int) OperationRun::query() $operationsFollowUpCount = (int) OperationRun::query()
->where('tenant_id', (int) $tenant->getKey()) ->where('managed_environment_id', (int) $tenant->getKey())
->dashboardNeedsFollowUp() ->dashboardNeedsFollowUp()
->count(); ->count();
$summaryAssessment = $this->dashboardSummaryAssessment($aggregate, $operationsFollowUpCount); $summaryAssessment = $this->dashboardSummaryAssessment($aggregate, $operationsFollowUpCount);
@ -133,7 +133,7 @@ private function dashboardSummaryAssessment(TenantGovernanceAggregate $aggregate
return $summaryAssessment; return $summaryAssessment;
} }
private function runUrl(Tenant $tenant, TenantGovernanceAggregate $aggregate): ?string private function runUrl(ManagedEnvironment $tenant, TenantGovernanceAggregate $aggregate): ?string
{ {
$runId = $aggregate->stats->operationRunId; $runId = $aggregate->stats->operationRunId;
@ -150,7 +150,7 @@ private function runUrl(Tenant $tenant, TenantGovernanceAggregate $aggregate): ?
return OperationRunLinks::view($run, $tenant); return OperationRunLinks::view($run, $tenant);
} }
private function findingsUrl(Tenant $tenant, TenantGovernanceAggregate $aggregate): ?string private function findingsUrl(ManagedEnvironment $tenant, TenantGovernanceAggregate $aggregate): ?string
{ {
if (! $this->canOpenFindings($tenant)) { if (! $this->canOpenFindings($tenant)) {
return null; return null;
@ -182,7 +182,7 @@ private function findingsUrl(Tenant $tenant, TenantGovernanceAggregate $aggregat
return FindingResource::getUrl('index', $parameters, panel: 'tenant', tenant: $tenant); return FindingResource::getUrl('index', $parameters, panel: 'tenant', tenant: $tenant);
} }
private function canOpenFindings(Tenant $tenant): bool private function canOpenFindings(ManagedEnvironment $tenant): bool
{ {
$user = auth()->user(); $user = auth()->user();
@ -198,7 +198,7 @@ private function canOpenRun(OperationRun $run): bool
return $user instanceof User && $user->can('view', $run); return $user instanceof User && $user->can('view', $run);
} }
private function governanceAggregate(Tenant $tenant): TenantGovernanceAggregate private function governanceAggregate(ManagedEnvironment $tenant): TenantGovernanceAggregate
{ {
/** @var TenantGovernanceAggregateResolver $resolver */ /** @var TenantGovernanceAggregateResolver $resolver */
$resolver = app(TenantGovernanceAggregateResolver::class); $resolver = app(TenantGovernanceAggregateResolver::class);

View File

@ -4,7 +4,7 @@
namespace App\Filament\Widgets\Dashboard; namespace App\Filament\Widgets\Dashboard;
use App\Models\Tenant; use App\Models\ManagedEnvironment;
use App\Support\OpsUx\ActiveRuns; use App\Support\OpsUx\ActiveRuns;
use App\Support\TenantDashboard\TenantDashboardSummaryBuilder; use App\Support\TenantDashboard\TenantDashboardSummaryBuilder;
use Filament\Facades\Filament; use Filament\Facades\Filament;
@ -28,7 +28,7 @@ protected function getStats(): array
{ {
$tenant = Filament::getTenant(); $tenant = Filament::getTenant();
if (! $tenant instanceof Tenant) { if (! $tenant instanceof ManagedEnvironment) {
return []; return [];
} }

Some files were not shown because too many files have changed in this diff Show More