TenantAtlas/apps/platform/app/Http/Controllers/TenantOnboardingController.php
ahmido 1655cc481e Spec 188: canonical provider connection state cleanup (#219)
## Summary
- migrate provider connections to the canonical three-dimension state model: lifecycle via `is_enabled`, consent via `consent_status`, and verification via `verification_status`
- remove legacy provider status and health badge paths, update admin and system directory surfaces, and align onboarding, consent callback, verification, resolver, and mutation flows with the new model
- add the Spec 188 artifact set, schema migrations, guard coverage, and expanded provider-state tests across admin, system, onboarding, verification, and rendering paths

## Verification
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Auth/SystemPanelAuthTest.php tests/Feature/Filament/TenantGlobalSearchLifecycleScopeTest.php tests/Feature/ProviderConnections/ProviderConnectionEnableDisableTest.php tests/Feature/ProviderConnections/ProviderConnectionTruthCleanupSpec179Test.php`
- integrated browser smoke: validated admin provider list/detail/edit, tenant provider summary, system directory tenant detail, provider-connection search exclusion, and cleaned up the temporary smoke record afterward

## Filament / implementation notes
- Livewire v4.0+ compliance: preserved; this change targets Filament v5 on Livewire v4 and does not introduce older APIs
- Provider registration location: unchanged; Laravel 11+ panel providers remain registered in `bootstrap/providers.php`
- Globally searchable resources: `ProviderConnectionResource` remains intentionally excluded from global search; tenant global search remains enabled and continues to resolve to view pages
- Destructive actions: no new destructive action surface was introduced without confirmation or authorization; existing capability checks continue to gate provider mutations
- Asset strategy: unchanged; no new Filament assets were added, so deploy behavior for `php artisan filament:assets` remains unchanged
- Testing plan covered: system auth, tenant global search, provider lifecycle enable/disable behavior, and provider truth cleanup cutover behavior

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #219
2026-04-10 11:22:56 +00:00

136 lines
5.2 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Services\Intune\AuditLogger;
use App\Services\Providers\AdminConsentUrlFactory;
use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderConsentStatus;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;
class TenantOnboardingController extends Controller
{
public function __invoke(
Request $request,
AdminConsentUrlFactory $consentUrlFactory,
AuditLogger $auditLogger,
): RedirectResponse {
$tenantIdentifier = $request->string('tenant')->toString();
abort_if($tenantIdentifier === '', ResponseAlias::HTTP_NOT_FOUND);
$state = Str::uuid()->toString();
$request->session()->put('tenant_onboard_state', $state);
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);
if ($workspaceId !== null) {
$request->session()->put('tenant_onboard_workspace_id', (int) $workspaceId);
}
$tenant = $this->resolveTenant($tenantIdentifier, is_numeric($workspaceId) ? (int) $workspaceId : null);
$connection = $this->upsertPlatformConnection($tenant);
$url = $consentUrlFactory->make($connection, $state);
$auditLogger->log(
tenant: $tenant,
action: 'provider_connection.consent_started',
context: [
'metadata' => [
'source' => 'admin.consent.start',
'workspace_id' => (int) $connection->workspace_id,
'provider_connection_id' => (int) $connection->getKey(),
'provider' => (string) $connection->provider,
'entra_tenant_id' => (string) $connection->entra_tenant_id,
'connection_type' => $connection->connection_type->value,
'effective_client_id' => trim((string) config('graph.client_id')),
'state' => $state,
],
],
actorId: auth()->id(),
actorEmail: auth()->user()?->email,
actorName: auth()->user()?->name,
resourceType: 'provider_connection',
resourceId: (string) $connection->getKey(),
status: 'success',
);
return redirect()->away($url);
}
private function resolveTenant(string $tenantIdentifier, ?int $workspaceId): Tenant
{
$tenant = Tenant::query()
->where(function ($query) use ($tenantIdentifier): void {
$query->where('tenant_id', $tenantIdentifier)
->orWhere('external_id', $tenantIdentifier);
})
->first();
if ($tenant instanceof Tenant) {
if ($tenant->workspace_id === null && $workspaceId !== null) {
$tenant->forceFill(['workspace_id' => $workspaceId])->save();
}
return $tenant;
}
abort_if($workspaceId === null, ResponseAlias::HTTP_FORBIDDEN, 'Missing workspace context');
return Tenant::create([
'tenant_id' => $tenantIdentifier,
'name' => 'New Tenant',
'workspace_id' => $workspaceId,
]);
}
private function upsertPlatformConnection(Tenant $tenant): ProviderConnection
{
$hasDefault = ProviderConnection::query()
->where('tenant_id', (int) $tenant->getKey())
->where('provider', 'microsoft')
->where('is_default', true)
->exists();
$connection = ProviderConnection::query()->updateOrCreate(
[
'tenant_id' => (int) $tenant->getKey(),
'provider' => 'microsoft',
'entra_tenant_id' => (string) ($tenant->graphTenantId() ?? $tenant->tenant_id ?? $tenant->external_id),
],
[
'workspace_id' => (int) $tenant->workspace_id,
'display_name' => (string) ($tenant->name ?? 'Microsoft Connection'),
'is_enabled' => true,
'connection_type' => ProviderConnectionType::Platform->value,
'consent_status' => ProviderConsentStatus::Required->value,
'consent_granted_at' => null,
'consent_last_checked_at' => null,
'consent_error_code' => null,
'consent_error_message' => null,
'verification_status' => ProviderVerificationStatus::Unknown->value,
'migration_review_required' => false,
'migration_reviewed_at' => null,
'last_error_reason_code' => ProviderReasonCodes::ProviderConsentMissing,
'last_error_message' => null,
'is_default' => $hasDefault ? false : true,
],
);
$connection->credential()->delete();
if (! $hasDefault && ! $connection->is_default) {
$connection->makeDefault();
}
return $connection->fresh();
}
}