TenantAtlas/app/Jobs/TenantOnboardingVerifyJob.php
2026-02-01 12:20:09 +01:00

123 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Jobs\Middleware\TrackOperationRun;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\TenantOnboardingSession;
use App\Models\User;
use App\Services\Intune\TenantPermissionService;
use App\Services\OperationRunService;
use App\Services\TenantOnboardingAuditService;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use RuntimeException;
class TenantOnboardingVerifyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public ?OperationRun $operationRun = null;
public function __construct(
public int $tenantId,
public int $userId,
?OperationRun $operationRun = null,
) {
$this->operationRun = $operationRun;
}
/**
* @return array<int, object>
*/
public function middleware(): array
{
return [new TrackOperationRun];
}
public function handle(
TenantPermissionService $permissions,
OperationRunService $runs,
TenantOnboardingAuditService $audit,
): void {
$tenant = Tenant::query()->find($this->tenantId);
if (! $tenant instanceof Tenant) {
throw new RuntimeException('Tenant not found.');
}
$user = User::query()->find($this->userId);
if (! $user instanceof User) {
throw new RuntimeException('User not found.');
}
$result = $permissions->compare(
tenant: $tenant,
grantedStatuses: null,
persist: true,
liveCheck: true,
useConfiguredStub: false,
);
$overall = (string) ($result['overall_status'] ?? 'error');
$tenant->forceFill([
'rbac_last_checked_at' => now(),
'rbac_last_warnings' => $overall === 'granted' ? [] : ['permissions_not_granted'],
])->save();
if (! $this->operationRun instanceof OperationRun) {
return;
}
if ($overall === 'granted') {
$runs->updateRun(
$this->operationRun,
status: OperationRunStatus::Completed->value,
outcome: OperationRunOutcome::Succeeded->value,
);
$tenant->forceFill([
'onboarding_status' => 'completed',
'onboarding_completed_at' => now(),
])->save();
TenantOnboardingSession::query()
->where('tenant_id', $tenant->getKey())
->where('status', 'active')
->update([
'status' => 'completed',
'current_step' => 'verification',
'completed_at' => now(),
]);
$audit->onboardingCompleted(
tenant: $tenant,
actor: $user,
context: [
'operation_run_id' => (int) $this->operationRun->getKey(),
],
);
return;
}
$runs->updateRun(
$this->operationRun,
status: OperationRunStatus::Completed->value,
outcome: OperationRunOutcome::Failed->value,
failures: [[
'code' => 'tenant.rbac.verify.not_granted',
'message' => 'Permissions are missing or could not be verified.',
]],
);
}
}