operationRun = $operationRun; } /** * @return array */ public function middleware(): array { return [new TrackOperationRun]; } public function handle( OnboardingEvidenceWriter $evidence, OperationRunService $runs, ): 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.'); } $session = OnboardingSession::query() ->where('tenant_id', $tenant->getKey()) ->find($this->onboardingSessionId); if (! $session instanceof OnboardingSession) { throw new RuntimeException('OnboardingSession not found.'); } $connection = ProviderConnection::query() ->where('tenant_id', $tenant->getKey()) ->find($this->providerConnectionId); if (! $connection instanceof ProviderConnection) { throw new RuntimeException('ProviderConnection not found.'); } $status = (string) ($connection->status ?? 'unknown'); $evidenceStatus = match ($status) { 'connected' => 'ok', 'needs_consent' => 'blocked', default => 'error', }; $message = match ($status) { 'connected' => 'Consent appears granted (connection is connected).', 'needs_consent' => 'Consent is missing or credentials are not authorized yet.', default => 'Unable to determine consent status.', }; $evidence->record( tenant: $tenant, taskType: OnboardingTaskType::ConsentStatus, status: $evidenceStatus, reasonCode: $status === 'needs_consent' ? 'consent.missing' : null, message: $message, payload: [ 'provider_connection_status' => $status, 'provider_connection_health_status' => $connection->health_status, ], session: $session, providerConnection: $connection, operationRun: $this->operationRun, recordedBy: $user, ); if (! $this->operationRun instanceof OperationRun) { return; } if ($evidenceStatus === 'ok') { $runs->updateRun( $this->operationRun, status: OperationRunStatus::Completed->value, outcome: OperationRunOutcome::Succeeded->value, ); return; } $runs->updateRun( $this->operationRun, status: OperationRunStatus::Completed->value, outcome: OperationRunOutcome::Failed->value, failures: [[ 'code' => 'onboarding.consent.status.failed', 'reason_code' => $status === 'needs_consent' ? 'consent.missing' : 'consent.status.error', 'message' => $message, ]], ); } }