TenantAtlas/app/Services/Baselines/BaselineCaptureService.php
ahmido fdfb781144 feat(115): baseline operability + alerts (#140)
Implements Spec 115 (Baseline Operability & Alert Integration).

Key changes
- Baseline compare: safe auto-close of stale baseline findings (gated on successful/complete compares)
- Baseline alerts: `baseline_high_drift` + `baseline_compare_failed` with dedupe/cooldown semantics
- Workspace settings: baseline severity mapping + minimum severity threshold + auto-close toggle
- Baseline Compare UX: shared stats layer + landing/widget consistency

Notes
- Livewire v4 / Filament v5 compatible.
- Destructive-like actions require confirmation (no new destructive actions added here).

Tests
- `vendor/bin/sail artisan test --compact tests/Feature/Baselines/ tests/Feature/Alerts/`

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #140
2026-03-01 02:26:47 +00:00

81 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services\Baselines;
use App\Jobs\CaptureBaselineSnapshotJob;
use App\Models\BaselineProfile;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineReasonCodes;
use App\Support\Baselines\BaselineScope;
use App\Support\OperationRunType;
final class BaselineCaptureService
{
public function __construct(
private readonly OperationRunService $runs,
) {}
/**
* @return array{ok: bool, run?: OperationRun, reason_code?: string}
*/
public function startCapture(
BaselineProfile $profile,
Tenant $sourceTenant,
User $initiator,
): array {
$precondition = $this->validatePreconditions($profile, $sourceTenant);
if ($precondition !== null) {
return ['ok' => false, 'reason_code' => $precondition];
}
$effectiveScope = BaselineScope::fromJsonb(
is_array($profile->scope_jsonb) ? $profile->scope_jsonb : null,
);
$context = [
'baseline_profile_id' => (int) $profile->getKey(),
'source_tenant_id' => (int) $sourceTenant->getKey(),
'effective_scope' => $effectiveScope->toJsonb(),
];
$run = $this->runs->ensureRunWithIdentity(
tenant: $sourceTenant,
type: OperationRunType::BaselineCapture->value,
identityInputs: [
'baseline_profile_id' => (int) $profile->getKey(),
],
context: $context,
initiator: $initiator,
);
if ($run->wasRecentlyCreated) {
CaptureBaselineSnapshotJob::dispatch($run);
}
return ['ok' => true, 'run' => $run];
}
private function validatePreconditions(BaselineProfile $profile, Tenant $sourceTenant): ?string
{
if ($profile->status !== BaselineProfile::STATUS_ACTIVE) {
return BaselineReasonCodes::CAPTURE_PROFILE_NOT_ACTIVE;
}
if ($sourceTenant->workspace_id === null) {
return BaselineReasonCodes::CAPTURE_MISSING_SOURCE_TENANT;
}
if ((int) $sourceTenant->workspace_id !== (int) $profile->workspace_id) {
return BaselineReasonCodes::CAPTURE_MISSING_SOURCE_TENANT;
}
return null;
}
}