where('workspace_id', $tenant->workspace_id) ->where('tenant_id', $tenant->getKey()) ->first(); if (! $assignment instanceof BaselineTenantAssignment) { return ['ok' => false, 'reason_code' => BaselineReasonCodes::COMPARE_NO_ASSIGNMENT]; } $profile = BaselineProfile::query()->find($assignment->baseline_profile_id); if (! $profile instanceof BaselineProfile) { return ['ok' => false, 'reason_code' => BaselineReasonCodes::COMPARE_PROFILE_NOT_ACTIVE]; } $precondition = $this->validatePreconditions($profile); if ($precondition !== null) { return ['ok' => false, 'reason_code' => $precondition]; } $snapshotId = (int) $profile->active_snapshot_id; $profileScope = BaselineScope::fromJsonb( is_array($profile->scope_jsonb) ? $profile->scope_jsonb : null, ); $overrideScope = $assignment->override_scope_jsonb !== null ? BaselineScope::fromJsonb(is_array($assignment->override_scope_jsonb) ? $assignment->override_scope_jsonb : null) : null; $effectiveScope = BaselineScope::effective($profileScope, $overrideScope); $context = [ 'baseline_profile_id' => (int) $profile->getKey(), 'baseline_snapshot_id' => $snapshotId, 'effective_scope' => $effectiveScope->toJsonb(), ]; $run = $this->runs->ensureRunWithIdentity( tenant: $tenant, type: 'baseline_compare', identityInputs: [ 'baseline_profile_id' => (int) $profile->getKey(), ], context: $context, initiator: $initiator, ); if ($run->wasRecentlyCreated) { CompareBaselineToTenantJob::dispatch($run); } return ['ok' => true, 'run' => $run]; } private function validatePreconditions(BaselineProfile $profile): ?string { if ($profile->status !== BaselineProfile::STATUS_ACTIVE) { return BaselineReasonCodes::COMPARE_PROFILE_NOT_ACTIVE; } if ($profile->active_snapshot_id === null) { return BaselineReasonCodes::COMPARE_NO_ACTIVE_SNAPSHOT; } return null; } }