merge: agent session work
Some checks failed
PR Fast Feedback / fast-feedback (pull_request) Failing after 4m4s
Some checks failed
PR Fast Feedback / fast-feedback (pull_request) Failing after 4m4s
This commit is contained in:
commit
c007f42d1f
9
.github/agents/copilot-instructions.md
vendored
9
.github/agents/copilot-instructions.md
vendored
@ -230,6 +230,8 @@ ## Active Technologies
|
||||
- PostgreSQL via existing `findings`, `tenants`, `tenant_memberships`, and workspace context session state; no schema changes planned (221-findings-operator-inbox)
|
||||
- PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin pages/tables/actions/notifications, `Finding`, `FindingResource`, `FindingWorkflowService`, `FindingPolicy`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, `CanonicalNavigationContext`, `WorkspaceContext`, and `UiEnforcement` (222-findings-intake-team-queue)
|
||||
- PostgreSQL via existing `findings`, `tenants`, `tenant_memberships`, `audit_logs`, and workspace session context; no schema changes planned (222-findings-intake-team-queue)
|
||||
- PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Laravel notifications (`database` channel), Filament database notifications, `Finding`, `FindingWorkflowService`, `FindingSlaPolicy`, `AlertRule`, `AlertDelivery`, `AlertDispatchService`, `EvaluateAlertsJob`, `CapabilityResolver`, `WorkspaceContext`, `TenantMembership`, `FindingResource` (224-findings-notifications-escalation)
|
||||
- PostgreSQL via existing `findings`, `alert_rules`, `alert_deliveries`, `notifications`, `tenant_memberships`, and `audit_logs`; no schema changes planned (224-findings-notifications-escalation)
|
||||
|
||||
- PHP 8.4.15 (feat/005-bulk-operations)
|
||||
|
||||
@ -264,14 +266,9 @@ ## Code Style
|
||||
PHP 8.4.15: Follow standard conventions
|
||||
|
||||
## Recent Changes
|
||||
- 224-findings-notifications-escalation: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Laravel notifications (`database` channel), Filament database notifications, `Finding`, `FindingWorkflowService`, `FindingSlaPolicy`, `AlertRule`, `AlertDelivery`, `AlertDispatchService`, `EvaluateAlertsJob`, `CapabilityResolver`, `WorkspaceContext`, `TenantMembership`, `FindingResource`
|
||||
- 222-findings-intake-team-queue: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin pages/tables/actions/notifications, `Finding`, `FindingResource`, `FindingWorkflowService`, `FindingPolicy`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, `CanonicalNavigationContext`, `WorkspaceContext`, and `UiEnforcement`
|
||||
- 221-findings-operator-inbox: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament admin panel pages, `Finding`, `FindingResource`, `WorkspaceOverviewBuilder`, `WorkspaceContext`, `WorkspaceCapabilityResolver`, `CapabilityResolver`, `CanonicalAdminTenantFilterState`, and `CanonicalNavigationContext`
|
||||
- 220-governance-run-summaries: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade + Filament v5, Livewire v4, Pest v4, Laravel Sail, `TenantlessOperationRunViewer`, `OperationRunResource`, `ArtifactTruthPresenter`, `OperatorExplanationBuilder`, `ReasonPresenter`, `OperationUxPresenter`, `SummaryCountsNormalizer`, and the existing enterprise-detail builders
|
||||
- 219-finding-ownership-semantics: Added PHP 8.4.15 / Laravel 12 + Filament v5, Livewire v4.0+, Pest v4, Tailwind CSS v4
|
||||
- 218-homepage-hero: Added Astro 6.0.0 templates + TypeScript 5.9.x + Astro 6, Tailwind CSS v4, existing Astro content modules and section primitives, Playwright browser smoke tests
|
||||
- 217-homepage-structure: Added Astro 6.0.0 templates + TypeScript 5.9.x + Astro 6, Tailwind CSS v4, local Astro layout/section primitives, Astro content collections, Playwright browser smoke tests
|
||||
- 216-provider-dispatch-gate: Added PHP 8.4.15, Laravel 12, Filament v5, Livewire v4 + Filament Resources/Pages/Actions, Livewire 4, Pest 4, `ProviderOperationStartGate`, `ProviderOperationRegistry`, `ProviderConnectionResolver`, `OperationRunService`, `ProviderNextStepsRegistry`, `ReasonPresenter`, `OperationUxPresenter`, `OperationRunLinks`
|
||||
- 215-website-core-pages: Added Astro 6.0.0 templates + TypeScript 5.9 strict + Astro 6, Tailwind CSS v4 via `@tailwindcss/vite`, Astro content collections, local Astro layout/primitive/content helpers, Playwright smoke tests
|
||||
<!-- MANUAL ADDITIONS START -->
|
||||
|
||||
### Pre-production compatibility check
|
||||
|
||||
@ -234,7 +234,8 @@ public static function table(Table $table): Table
|
||||
->searchable(),
|
||||
TextColumn::make('event_type')
|
||||
->label('Event')
|
||||
->badge(),
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => AlertRuleResource::eventTypeLabel((string) $state)),
|
||||
TextColumn::make('severity')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => ucfirst((string) $state))
|
||||
|
||||
@ -380,6 +380,10 @@ public static function eventTypeOptions(): array
|
||||
AlertRule::EVENT_SLA_DUE => 'SLA due',
|
||||
AlertRule::EVENT_PERMISSION_MISSING => 'Permission missing',
|
||||
AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH => 'Entra admin roles (high privilege)',
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => 'Finding assigned',
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => 'Finding reopened',
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON => 'Finding due soon',
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => 'Finding overdue',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@ -9,6 +9,7 @@
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Alerts\AlertDispatchService;
|
||||
use App\Services\Findings\FindingNotificationService;
|
||||
use App\Services\OperationRunService;
|
||||
use App\Services\Settings\SettingsResolver;
|
||||
use App\Support\OperationRunOutcome;
|
||||
@ -21,6 +22,7 @@
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use Throwable;
|
||||
|
||||
class EvaluateAlertsJob implements ShouldQueue
|
||||
@ -32,7 +34,11 @@ public function __construct(
|
||||
public ?int $operationRunId = null,
|
||||
) {}
|
||||
|
||||
public function handle(AlertDispatchService $dispatchService, OperationRunService $operationRuns): void
|
||||
public function handle(
|
||||
AlertDispatchService $dispatchService,
|
||||
OperationRunService $operationRuns,
|
||||
FindingNotificationService $findingNotificationService,
|
||||
): void
|
||||
{
|
||||
$workspace = Workspace::query()->whereKey($this->workspaceId)->first();
|
||||
|
||||
@ -67,6 +73,8 @@ public function handle(AlertDispatchService $dispatchService, OperationRunServic
|
||||
...$this->permissionMissingEvents((int) $workspace->getKey(), $windowStart),
|
||||
...$this->entraAdminRolesHighEvents((int) $workspace->getKey(), $windowStart),
|
||||
];
|
||||
$dueSoonFindings = $this->dueSoonFindings((int) $workspace->getKey());
|
||||
$overdueFindings = $this->overdueFindings((int) $workspace->getKey());
|
||||
|
||||
$createdDeliveries = 0;
|
||||
|
||||
@ -74,13 +82,33 @@ public function handle(AlertDispatchService $dispatchService, OperationRunServic
|
||||
$createdDeliveries += $dispatchService->dispatchEvent($workspace, $event);
|
||||
}
|
||||
|
||||
foreach ($dueSoonFindings as $finding) {
|
||||
$result = $findingNotificationService->dispatch($finding, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
$createdDeliveries += $result['external_delivery_count'];
|
||||
|
||||
if ($result['direct_delivery_status'] === 'sent') {
|
||||
$createdDeliveries++;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($overdueFindings as $finding) {
|
||||
$result = $findingNotificationService->dispatch($finding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
$createdDeliveries += $result['external_delivery_count'];
|
||||
|
||||
if ($result['direct_delivery_status'] === 'sent') {
|
||||
$createdDeliveries++;
|
||||
}
|
||||
}
|
||||
|
||||
$processedEventCount = count($events) + $dueSoonFindings->count() + $overdueFindings->count();
|
||||
|
||||
$operationRuns->updateRun(
|
||||
$operationRun,
|
||||
status: OperationRunStatus::Completed->value,
|
||||
outcome: OperationRunOutcome::Succeeded->value,
|
||||
summaryCounts: [
|
||||
'total' => count($events),
|
||||
'processed' => count($events),
|
||||
'total' => $processedEventCount,
|
||||
'processed' => $processedEventCount,
|
||||
'created' => $createdDeliveries,
|
||||
],
|
||||
);
|
||||
@ -101,6 +129,45 @@ public function handle(AlertDispatchService $dispatchService, OperationRunServic
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Finding>
|
||||
*/
|
||||
private function dueSoonFindings(int $workspaceId): Collection
|
||||
{
|
||||
$now = CarbonImmutable::now('UTC');
|
||||
|
||||
return Finding::query()
|
||||
->with('tenant')
|
||||
->withSubjectDisplayName()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->openWorkflow()
|
||||
->whereNotNull('due_at')
|
||||
->where('due_at', '>', $now)
|
||||
->where('due_at', '<=', $now->addHours(24))
|
||||
->orderBy('due_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Finding>
|
||||
*/
|
||||
private function overdueFindings(int $workspaceId): Collection
|
||||
{
|
||||
$now = CarbonImmutable::now('UTC');
|
||||
|
||||
return Finding::query()
|
||||
->with('tenant')
|
||||
->withSubjectDisplayName()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->openWorkflow()
|
||||
->whereNotNull('due_at')
|
||||
->where('due_at', '<', $now)
|
||||
->orderBy('due_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
private function resolveOperationRun(Workspace $workspace, OperationRunService $operationRuns): ?OperationRun
|
||||
{
|
||||
if (is_int($this->operationRunId) && $this->operationRunId > 0) {
|
||||
|
||||
@ -28,6 +28,14 @@ class AlertRule extends Model
|
||||
|
||||
public const string EVENT_ENTRA_ADMIN_ROLES_HIGH = 'entra.admin_roles.high';
|
||||
|
||||
public const string EVENT_FINDINGS_ASSIGNED = 'findings.assigned';
|
||||
|
||||
public const string EVENT_FINDINGS_REOPENED = 'findings.reopened';
|
||||
|
||||
public const string EVENT_FINDINGS_DUE_SOON = 'findings.due_soon';
|
||||
|
||||
public const string EVENT_FINDINGS_OVERDUE = 'findings.overdue';
|
||||
|
||||
public const string TENANT_SCOPE_ALL = 'all';
|
||||
|
||||
public const string TENANT_SCOPE_ALLOWLIST = 'allowlist';
|
||||
|
||||
@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Notifications\Findings;
|
||||
|
||||
use App\Filament\Resources\FindingResource;
|
||||
use App\Models\Finding;
|
||||
use App\Models\Tenant;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification as FilamentNotification;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Notifications\Notification;
|
||||
|
||||
final class FindingEventNotification extends Notification
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $event
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly Finding $finding,
|
||||
private readonly Tenant $tenant,
|
||||
private readonly array $event,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['database'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toDatabase(object $notifiable): array
|
||||
{
|
||||
$message = FilamentNotification::make()
|
||||
->title($this->title())
|
||||
->body($this->body())
|
||||
->actions([
|
||||
Action::make('open_finding')
|
||||
->label('Open finding')
|
||||
->url(FindingResource::getUrl(
|
||||
'view',
|
||||
['record' => $this->finding],
|
||||
panel: 'tenant',
|
||||
tenant: $this->tenant,
|
||||
)),
|
||||
])
|
||||
->getDatabaseMessage();
|
||||
|
||||
$message['finding_event'] = [
|
||||
'event_type' => (string) ($this->event['event_type'] ?? ''),
|
||||
'finding_id' => (int) $this->finding->getKey(),
|
||||
'recipient_reason' => data_get($this->event, 'metadata.recipient_reason'),
|
||||
'fingerprint_key' => (string) ($this->event['fingerprint_key'] ?? ''),
|
||||
'due_cycle_key' => $this->event['due_cycle_key'] ?? null,
|
||||
'tenant_name' => $this->tenant->getFilamentName(),
|
||||
'severity' => (string) ($this->event['severity'] ?? ''),
|
||||
];
|
||||
|
||||
return $message;
|
||||
}
|
||||
|
||||
private function title(): string
|
||||
{
|
||||
$title = trim((string) ($this->event['title'] ?? 'Finding update'));
|
||||
|
||||
return $title !== '' ? $title : 'Finding update';
|
||||
}
|
||||
|
||||
private function body(): string
|
||||
{
|
||||
$body = trim((string) ($this->event['body'] ?? 'A finding needs follow-up.'));
|
||||
$recipientReason = $this->recipientReasonCopy((string) data_get($this->event, 'metadata.recipient_reason', ''));
|
||||
|
||||
return trim($body.' '.$recipientReason);
|
||||
}
|
||||
|
||||
private function recipientReasonCopy(string $reason): string
|
||||
{
|
||||
return match ($reason) {
|
||||
'new_assignee' => 'You are the new assignee.',
|
||||
'current_assignee' => 'You are the current assignee.',
|
||||
'current_owner' => 'You are the accountable owner.',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -186,6 +186,8 @@ private function buildPayload(array $event): array
|
||||
return [
|
||||
'title' => $title,
|
||||
'body' => $body,
|
||||
'event_type' => trim((string) ($event['event_type'] ?? '')),
|
||||
'fingerprint_key' => trim((string) ($event['fingerprint_key'] ?? '')),
|
||||
'metadata' => $metadata,
|
||||
];
|
||||
}
|
||||
|
||||
@ -0,0 +1,389 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Findings;
|
||||
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Finding;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Notifications\Findings\FindingEventNotification;
|
||||
use App\Services\Alerts\AlertDispatchService;
|
||||
use App\Services\Auth\CapabilityResolver;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use Carbon\CarbonInterface;
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class FindingNotificationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AlertDispatchService $alertDispatchService,
|
||||
private readonly CapabilityResolver $capabilityResolver,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @return array{
|
||||
* event_type: string,
|
||||
* fingerprint_key: string,
|
||||
* direct_delivery_status: 'sent'|'suppressed'|'deduped'|'no_recipient',
|
||||
* external_delivery_count: int
|
||||
* }
|
||||
*/
|
||||
public function dispatch(Finding $finding, string $eventType, array $context = []): array
|
||||
{
|
||||
$finding = $this->reloadFinding($finding);
|
||||
$tenant = $finding->tenant;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $this->dispatchResult(
|
||||
eventType: $eventType,
|
||||
fingerprintKey: '',
|
||||
directDeliveryStatus: 'no_recipient',
|
||||
externalDeliveryCount: 0,
|
||||
);
|
||||
}
|
||||
|
||||
if ($this->shouldSuppressEvent($finding, $eventType, $context)) {
|
||||
return $this->dispatchResult(
|
||||
eventType: $eventType,
|
||||
fingerprintKey: $this->fingerprintFor($finding, $eventType, $context),
|
||||
directDeliveryStatus: 'suppressed',
|
||||
externalDeliveryCount: 0,
|
||||
);
|
||||
}
|
||||
|
||||
$resolution = $this->resolveRecipient($finding, $eventType, $context);
|
||||
$event = $this->buildEventEnvelope($finding, $tenant, $eventType, $resolution['reason'], $context);
|
||||
|
||||
$directDeliveryStatus = $this->dispatchDirectNotification($finding, $tenant, $event, $resolution['user_id']);
|
||||
$externalDeliveryCount = $this->dispatchExternalCopies($finding, $event);
|
||||
|
||||
return $this->dispatchResult(
|
||||
eventType: $eventType,
|
||||
fingerprintKey: (string) $event['fingerprint_key'],
|
||||
directDeliveryStatus: $directDeliveryStatus,
|
||||
externalDeliveryCount: $externalDeliveryCount,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @return array{user_id: ?int, reason: ?string}
|
||||
*/
|
||||
private function resolveRecipient(Finding $finding, string $eventType, array $context): array
|
||||
{
|
||||
return match ($eventType) {
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => [
|
||||
'user_id' => $this->normalizeId($context['assignee_user_id'] ?? $finding->assignee_user_id),
|
||||
'reason' => 'new_assignee',
|
||||
],
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => $this->preferredRecipient(
|
||||
preferredUserId: $this->normalizeId($finding->assignee_user_id),
|
||||
preferredReason: 'current_assignee',
|
||||
fallbackUserId: $this->normalizeId($finding->owner_user_id),
|
||||
fallbackReason: 'current_owner',
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON => $this->preferredRecipient(
|
||||
preferredUserId: $this->normalizeId($finding->assignee_user_id),
|
||||
preferredReason: 'current_assignee',
|
||||
fallbackUserId: $this->normalizeId($finding->owner_user_id),
|
||||
fallbackReason: 'current_owner',
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => $this->preferredRecipient(
|
||||
preferredUserId: $this->normalizeId($finding->owner_user_id),
|
||||
preferredReason: 'current_owner',
|
||||
fallbackUserId: $this->normalizeId($finding->assignee_user_id),
|
||||
fallbackReason: 'current_assignee',
|
||||
),
|
||||
default => throw new InvalidArgumentException(sprintf('Unsupported finding notification event [%s].', $eventType)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function buildEventEnvelope(
|
||||
Finding $finding,
|
||||
Tenant $tenant,
|
||||
string $eventType,
|
||||
?string $recipientReason,
|
||||
array $context,
|
||||
): array {
|
||||
$severity = strtolower(trim((string) $finding->severity));
|
||||
$summary = $finding->resolvedSubjectDisplayName() ?? 'Finding #'.(int) $finding->getKey();
|
||||
$title = $this->eventLabel($eventType);
|
||||
$fingerprintKey = $this->fingerprintFor($finding, $eventType, $context);
|
||||
$dueCycleKey = $this->dueCycleKey($finding, $eventType);
|
||||
|
||||
return [
|
||||
'event_type' => $eventType,
|
||||
'workspace_id' => (int) $finding->workspace_id,
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'finding_id' => (int) $finding->getKey(),
|
||||
'severity' => $severity,
|
||||
'title' => $title,
|
||||
'body' => $this->eventBody($eventType, $tenant, $summary, ucfirst($severity)),
|
||||
'fingerprint_key' => $fingerprintKey,
|
||||
'due_cycle_key' => $dueCycleKey,
|
||||
'metadata' => [
|
||||
'tenant_name' => $tenant->getFilamentName(),
|
||||
'summary' => $summary,
|
||||
'recipient_reason' => $recipientReason,
|
||||
'owner_user_id' => $this->normalizeId($finding->owner_user_id),
|
||||
'assignee_user_id' => $this->normalizeId($finding->assignee_user_id),
|
||||
'due_at' => $this->optionalIso8601($finding->due_at),
|
||||
'reopened_at' => $this->optionalIso8601($finding->reopened_at),
|
||||
'severity_label' => ucfirst($severity),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $event
|
||||
*/
|
||||
private function dispatchDirectNotification(Finding $finding, Tenant $tenant, array $event, ?int $userId): string
|
||||
{
|
||||
if (! is_int($userId) || $userId <= 0) {
|
||||
return 'no_recipient';
|
||||
}
|
||||
|
||||
$user = User::query()->find($userId);
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return 'no_recipient';
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
return 'suppressed';
|
||||
}
|
||||
|
||||
if (! $this->capabilityResolver->can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW)) {
|
||||
return 'suppressed';
|
||||
}
|
||||
|
||||
if ($this->alreadySentDirectNotification($user, (string) $event['fingerprint_key'])) {
|
||||
return 'deduped';
|
||||
}
|
||||
|
||||
$user->notify(new FindingEventNotification($finding, $tenant, $event));
|
||||
|
||||
return 'sent';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $event
|
||||
*/
|
||||
private function dispatchExternalCopies(Finding $finding, array $event): int
|
||||
{
|
||||
$workspace = Workspace::query()->whereKey((int) $finding->workspace_id)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->alertDispatchService->dispatchEvent($workspace, $event);
|
||||
}
|
||||
|
||||
private function alreadySentDirectNotification(User $user, string $fingerprintKey): bool
|
||||
{
|
||||
if ($fingerprintKey === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->where('data->finding_event->fingerprint_key', $fingerprintKey)
|
||||
->exists();
|
||||
}
|
||||
|
||||
private function reloadFinding(Finding $finding): Finding
|
||||
{
|
||||
$fresh = Finding::query()
|
||||
->with('tenant')
|
||||
->withSubjectDisplayName()
|
||||
->find($finding->getKey());
|
||||
|
||||
if ($fresh instanceof Finding) {
|
||||
return $fresh;
|
||||
}
|
||||
|
||||
$finding->loadMissing('tenant');
|
||||
|
||||
return $finding;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function shouldSuppressEvent(Finding $finding, string $eventType, array $context): bool
|
||||
{
|
||||
return match ($eventType) {
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => ! $finding->hasOpenStatus()
|
||||
|| $this->normalizeId($context['assignee_user_id'] ?? $finding->assignee_user_id) === null,
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON, AlertRule::EVENT_FINDINGS_OVERDUE => ! $finding->hasOpenStatus()
|
||||
|| ! $finding->due_at instanceof CarbonInterface,
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function fingerprintFor(Finding $finding, string $eventType, array $context): string
|
||||
{
|
||||
$findingId = (int) $finding->getKey();
|
||||
|
||||
return match ($eventType) {
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => sprintf(
|
||||
'finding:%d:%s:assignee:%d:updated:%s',
|
||||
$findingId,
|
||||
$eventType,
|
||||
$this->normalizeId($context['assignee_user_id'] ?? $finding->assignee_user_id) ?? 0,
|
||||
$this->optionalIso8601($finding->updated_at) ?? 'none',
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => sprintf(
|
||||
'finding:%d:%s:reopened:%s',
|
||||
$findingId,
|
||||
$eventType,
|
||||
$this->optionalIso8601($finding->reopened_at) ?? 'none',
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON,
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => sprintf(
|
||||
'finding:%d:%s:due:%s',
|
||||
$findingId,
|
||||
$eventType,
|
||||
$this->dueCycleKey($finding, $eventType) ?? 'none',
|
||||
),
|
||||
default => throw new InvalidArgumentException(sprintf('Unsupported finding notification event [%s].', $eventType)),
|
||||
};
|
||||
}
|
||||
|
||||
private function dueCycleKey(Finding $finding, string $eventType): ?string
|
||||
{
|
||||
if (! in_array($eventType, [
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON,
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE,
|
||||
], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->optionalIso8601($finding->due_at);
|
||||
}
|
||||
|
||||
private function eventLabel(string $eventType): string
|
||||
{
|
||||
return match ($eventType) {
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => 'Finding assigned',
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => 'Finding reopened',
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON => 'Finding due soon',
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => 'Finding overdue',
|
||||
default => throw new InvalidArgumentException(sprintf('Unsupported finding notification event [%s].', $eventType)),
|
||||
};
|
||||
}
|
||||
|
||||
private function eventBody(string $eventType, Tenant $tenant, string $summary, string $severityLabel): string
|
||||
{
|
||||
return match ($eventType) {
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => sprintf(
|
||||
'%s in %s was assigned. %s severity.',
|
||||
$summary,
|
||||
$tenant->getFilamentName(),
|
||||
$severityLabel,
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => sprintf(
|
||||
'%s in %s reopened and needs follow-up. %s severity.',
|
||||
$summary,
|
||||
$tenant->getFilamentName(),
|
||||
$severityLabel,
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON => sprintf(
|
||||
'%s in %s is due within 24 hours. %s severity.',
|
||||
$summary,
|
||||
$tenant->getFilamentName(),
|
||||
$severityLabel,
|
||||
),
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => sprintf(
|
||||
'%s in %s is overdue. %s severity.',
|
||||
$summary,
|
||||
$tenant->getFilamentName(),
|
||||
$severityLabel,
|
||||
),
|
||||
default => throw new InvalidArgumentException(sprintf('Unsupported finding notification event [%s].', $eventType)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{user_id: ?int, reason: ?string}
|
||||
*/
|
||||
private function preferredRecipient(
|
||||
?int $preferredUserId,
|
||||
string $preferredReason,
|
||||
?int $fallbackUserId,
|
||||
string $fallbackReason,
|
||||
): array {
|
||||
if (is_int($preferredUserId) && $preferredUserId > 0) {
|
||||
return [
|
||||
'user_id' => $preferredUserId,
|
||||
'reason' => $preferredReason,
|
||||
];
|
||||
}
|
||||
|
||||
if (is_int($fallbackUserId) && $fallbackUserId > 0) {
|
||||
return [
|
||||
'user_id' => $fallbackUserId,
|
||||
'reason' => $fallbackReason,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'user_id' => null,
|
||||
'reason' => null,
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeId(mixed $value): ?int
|
||||
{
|
||||
if (! is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalized = (int) $value;
|
||||
|
||||
return $normalized > 0 ? $normalized : null;
|
||||
}
|
||||
|
||||
private function optionalIso8601(mixed $value): ?string
|
||||
{
|
||||
if (! $value instanceof CarbonInterface) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $value->toIso8601String();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* event_type: string,
|
||||
* fingerprint_key: string,
|
||||
* direct_delivery_status: 'sent'|'suppressed'|'deduped'|'no_recipient',
|
||||
* external_delivery_count: int
|
||||
* }
|
||||
*/
|
||||
private function dispatchResult(
|
||||
string $eventType,
|
||||
string $fingerprintKey,
|
||||
string $directDeliveryStatus,
|
||||
int $externalDeliveryCount,
|
||||
): array {
|
||||
return [
|
||||
'event_type' => $eventType,
|
||||
'fingerprint_key' => $fingerprintKey,
|
||||
'direct_delivery_status' => $directDeliveryStatus,
|
||||
'external_delivery_count' => $externalDeliveryCount,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -5,6 +5,7 @@
|
||||
namespace App\Services\Findings;
|
||||
|
||||
use App\Models\Finding;
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantMembership;
|
||||
use App\Models\User;
|
||||
@ -26,6 +27,7 @@ public function __construct(
|
||||
private readonly FindingSlaPolicy $slaPolicy,
|
||||
private readonly AuditLogger $auditLogger,
|
||||
private readonly CapabilityResolver $capabilityResolver,
|
||||
private readonly FindingNotificationService $findingNotificationService,
|
||||
) {}
|
||||
|
||||
public function triage(Finding $finding, Tenant $tenant, User $actor): Finding
|
||||
@ -108,6 +110,7 @@ public function assign(
|
||||
throw new InvalidArgumentException('Only open findings can be assigned.');
|
||||
}
|
||||
|
||||
$beforeAssigneeUserId = is_numeric($finding->assignee_user_id) ? (int) $finding->assignee_user_id : null;
|
||||
$this->assertTenantMemberOrNull($tenant, $assigneeUserId, 'assignee_user_id');
|
||||
$this->assertTenantMemberOrNull($tenant, $ownerUserId, 'owner_user_id');
|
||||
|
||||
@ -124,7 +127,7 @@ public function assign(
|
||||
afterAssigneeUserId: $assigneeUserId,
|
||||
);
|
||||
|
||||
return $this->mutateAndAudit(
|
||||
$updatedFinding = $this->mutateAndAudit(
|
||||
finding: $finding,
|
||||
tenant: $tenant,
|
||||
actor: $actor,
|
||||
@ -142,6 +145,16 @@ public function assign(
|
||||
$record->owner_user_id = $ownerUserId;
|
||||
},
|
||||
);
|
||||
|
||||
if ($assigneeUserId !== null && $assigneeUserId !== $beforeAssigneeUserId) {
|
||||
$this->findingNotificationService->dispatch(
|
||||
$updatedFinding,
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED,
|
||||
['assignee_user_id' => $assigneeUserId],
|
||||
);
|
||||
}
|
||||
|
||||
return $updatedFinding;
|
||||
}
|
||||
|
||||
public function claim(Finding $finding, Tenant $tenant, User $actor): Finding
|
||||
@ -441,7 +454,7 @@ public function reopenBySystem(
|
||||
$slaDays = $this->slaPolicy->daysForFinding($finding, $tenant);
|
||||
$dueAt = $this->slaPolicy->dueAtForSeverity((string) $finding->severity, $tenant, $reopenedAt);
|
||||
|
||||
return $this->mutateAndAudit(
|
||||
$reopenedFinding = $this->mutateAndAudit(
|
||||
finding: $finding,
|
||||
tenant: $tenant,
|
||||
actor: null,
|
||||
@ -472,6 +485,10 @@ public function reopenBySystem(
|
||||
actorType: AuditActorType::System,
|
||||
operationRunId: $operationRunId,
|
||||
);
|
||||
|
||||
$this->findingNotificationService->dispatch($reopenedFinding, AlertRule::EVENT_FINDINGS_REOPENED);
|
||||
|
||||
return $reopenedFinding;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -140,6 +140,34 @@ public function reopened(): static
|
||||
]);
|
||||
}
|
||||
|
||||
public function ownedBy(?int $userId): static
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'owner_user_id' => $userId,
|
||||
]);
|
||||
}
|
||||
|
||||
public function assignedTo(?int $userId): static
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'assignee_user_id' => $userId,
|
||||
]);
|
||||
}
|
||||
|
||||
public function dueWithinHours(int $hours): static
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'due_at' => now()->addHours($hours),
|
||||
]);
|
||||
}
|
||||
|
||||
public function overdueByHours(int $hours = 1): static
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'due_at' => now()->subHours($hours),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* State for closed findings.
|
||||
*/
|
||||
|
||||
@ -0,0 +1,284 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use App\Filament\Resources\AlertDeliveryResource\Pages\ListAlertDeliveries;
|
||||
use App\Filament\Resources\AlertRuleResource;
|
||||
use App\Models\AlertDelivery;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Finding;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Notifications\Findings\FindingEventNotification;
|
||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
||||
use App\Services\Findings\FindingNotificationService;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Facades\Filament;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('exposes the four finding notification events in the existing alert rule options', function (): void {
|
||||
expect(AlertRuleResource::eventTypeOptions())->toMatchArray([
|
||||
AlertRule::EVENT_FINDINGS_ASSIGNED => 'Finding assigned',
|
||||
AlertRule::EVENT_FINDINGS_REOPENED => 'Finding reopened',
|
||||
AlertRule::EVENT_FINDINGS_DUE_SOON => 'Finding due soon',
|
||||
AlertRule::EVENT_FINDINGS_OVERDUE => 'Finding overdue',
|
||||
]);
|
||||
});
|
||||
|
||||
it('delivers a direct finding notification without requiring a matching alert rule', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Assigned Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('sent')
|
||||
->and($result['external_delivery_count'])->toBe(0)
|
||||
->and($assignee->notifications()->where('type', FindingEventNotification::class)->count())->toBe(1)
|
||||
->and(AlertDelivery::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('fans out matching external copies through the existing alert delivery pipeline', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$workspaceId = (int) $tenant->workspace_id;
|
||||
|
||||
$destination = AlertDestination::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
|
||||
$rule = AlertRule::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'event_type' => AlertRule::EVENT_FINDINGS_OVERDUE,
|
||||
'minimum_severity' => Finding::SEVERITY_MEDIUM,
|
||||
'is_enabled' => true,
|
||||
'cooldown_seconds' => 0,
|
||||
]);
|
||||
|
||||
$rule->destinations()->attach($destination->getKey(), [
|
||||
'workspace_id' => $workspaceId,
|
||||
]);
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => null,
|
||||
'severity' => Finding::SEVERITY_HIGH,
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
$delivery = AlertDelivery::query()->latest('id')->first();
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('sent')
|
||||
->and($result['external_delivery_count'])->toBe(1)
|
||||
->and($delivery)->not->toBeNull()
|
||||
->and($delivery?->event_type)->toBe(AlertRule::EVENT_FINDINGS_OVERDUE)
|
||||
->and(data_get($delivery?->payload, 'title'))->toBe('Finding overdue');
|
||||
});
|
||||
|
||||
it('inherits minimum severity tenant scoping and cooldown suppression for finding alert copies', function (): void {
|
||||
[$ownerA, $tenantA] = createUserWithTenant(role: 'owner');
|
||||
$workspaceId = (int) $tenantA->workspace_id;
|
||||
|
||||
$tenantB = Tenant::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
]);
|
||||
[$ownerB] = createUserWithTenant(tenant: $tenantB, role: 'owner');
|
||||
|
||||
$destination = AlertDestination::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
|
||||
$rule = AlertRule::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'event_type' => AlertRule::EVENT_FINDINGS_OVERDUE,
|
||||
'minimum_severity' => Finding::SEVERITY_HIGH,
|
||||
'tenant_scope_mode' => AlertRule::TENANT_SCOPE_ALLOWLIST,
|
||||
'tenant_allowlist' => [(int) $tenantA->getKey()],
|
||||
'is_enabled' => true,
|
||||
'cooldown_seconds' => 3600,
|
||||
]);
|
||||
|
||||
$rule->destinations()->attach($destination->getKey(), [
|
||||
'workspace_id' => $workspaceId,
|
||||
]);
|
||||
|
||||
$mediumFinding = Finding::factory()->for($tenantA)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $ownerA->getKey(),
|
||||
'severity' => Finding::SEVERITY_MEDIUM,
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
$scopedOutFinding = Finding::factory()->for($tenantB)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $ownerB->getKey(),
|
||||
'severity' => Finding::SEVERITY_CRITICAL,
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
$trackedFinding = Finding::factory()->for($tenantA)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $ownerA->getKey(),
|
||||
'severity' => Finding::SEVERITY_HIGH,
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
expect(app(FindingNotificationService::class)->dispatch($mediumFinding, AlertRule::EVENT_FINDINGS_OVERDUE)['external_delivery_count'])->toBe(0)
|
||||
->and(app(FindingNotificationService::class)->dispatch($scopedOutFinding, AlertRule::EVENT_FINDINGS_OVERDUE)['external_delivery_count'])->toBe(0);
|
||||
|
||||
app(FindingNotificationService::class)->dispatch($trackedFinding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
app(FindingNotificationService::class)->dispatch($trackedFinding->fresh(), AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
$deliveries = AlertDelivery::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('event_type', AlertRule::EVENT_FINDINGS_OVERDUE)
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
expect($deliveries)->toHaveCount(2)
|
||||
->and($deliveries[0]->status)->toBe(AlertDelivery::STATUS_QUEUED)
|
||||
->and($deliveries[1]->status)->toBe(AlertDelivery::STATUS_SUPPRESSED);
|
||||
});
|
||||
|
||||
it('inherits quiet hours deferral for finding alert copies', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$workspaceId = (int) $tenant->workspace_id;
|
||||
|
||||
$destination = AlertDestination::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
|
||||
$rule = AlertRule::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'event_type' => AlertRule::EVENT_FINDINGS_ASSIGNED,
|
||||
'minimum_severity' => Finding::SEVERITY_LOW,
|
||||
'is_enabled' => true,
|
||||
'cooldown_seconds' => 0,
|
||||
'quiet_hours_enabled' => true,
|
||||
'quiet_hours_start' => '00:00',
|
||||
'quiet_hours_end' => '23:59',
|
||||
'quiet_hours_timezone' => 'UTC',
|
||||
]);
|
||||
|
||||
$rule->destinations()->attach($destination->getKey(), [
|
||||
'workspace_id' => $workspaceId,
|
||||
]);
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $owner->getKey(),
|
||||
'severity' => Finding::SEVERITY_LOW,
|
||||
]);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
$delivery = AlertDelivery::query()->latest('id')->first();
|
||||
|
||||
expect($result['external_delivery_count'])->toBe(1)
|
||||
->and($delivery)->not->toBeNull()
|
||||
->and($delivery?->status)->toBe(AlertDelivery::STATUS_DEFERRED);
|
||||
});
|
||||
|
||||
it('renders finding event labels and filters in the existing alert deliveries viewer', function (): void {
|
||||
$tenant = Tenant::factory()->create();
|
||||
[$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');
|
||||
$workspaceId = (int) $tenant->workspace_id;
|
||||
|
||||
$rule = AlertRule::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'event_type' => AlertRule::EVENT_FINDINGS_OVERDUE,
|
||||
]);
|
||||
|
||||
$destination = AlertDestination::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
|
||||
$delivery = AlertDelivery::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'alert_rule_id' => (int) $rule->getKey(),
|
||||
'alert_destination_id' => (int) $destination->getKey(),
|
||||
'event_type' => AlertRule::EVENT_FINDINGS_OVERDUE,
|
||||
'payload' => [
|
||||
'title' => 'Finding overdue',
|
||||
'body' => 'A finding is overdue and needs follow-up.',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
Filament::setTenant($tenant, true);
|
||||
|
||||
Livewire::test(ListAlertDeliveries::class)
|
||||
->filterTable('event_type', AlertRule::EVENT_FINDINGS_OVERDUE)
|
||||
->assertCanSeeTableRecords([$delivery])
|
||||
->assertSee('Finding overdue');
|
||||
|
||||
expect(AlertRuleResource::eventTypeLabel(AlertRule::EVENT_FINDINGS_OVERDUE))->toBe('Finding overdue');
|
||||
});
|
||||
|
||||
it('preserves alerts read and mutation boundaries for the existing admin surfaces', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$viewer = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $viewer->getKey(),
|
||||
'role' => 'readonly',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($viewer)
|
||||
->get(AlertRuleResource::getUrl(panel: 'admin'))
|
||||
->assertOk();
|
||||
|
||||
$this->actingAs($viewer)
|
||||
->get(AlertDeliveryResource::getUrl(panel: 'admin'))
|
||||
->assertOk();
|
||||
|
||||
$this->actingAs($viewer)
|
||||
->get(AlertRuleResource::getUrl('create', panel: 'admin'))
|
||||
->assertForbidden();
|
||||
|
||||
$resolver = \Mockery::mock(WorkspaceCapabilityResolver::class);
|
||||
$resolver->shouldReceive('isMember')->andReturnTrue();
|
||||
$resolver->shouldReceive('can')->andReturnFalse();
|
||||
app()->instance(WorkspaceCapabilityResolver::class, $resolver);
|
||||
|
||||
$this->actingAs($viewer)
|
||||
->get(AlertRuleResource::getUrl(panel: 'admin'))
|
||||
->assertForbidden();
|
||||
|
||||
$this->actingAs($viewer)
|
||||
->get(AlertDeliveryResource::getUrl(panel: 'admin'))
|
||||
->assertForbidden();
|
||||
|
||||
$outsider = User::factory()->create();
|
||||
app()->forgetInstance(WorkspaceCapabilityResolver::class);
|
||||
|
||||
$this->actingAs($outsider)
|
||||
->get(AlertRuleResource::getUrl(panel: 'admin'))
|
||||
->assertNotFound();
|
||||
});
|
||||
@ -194,3 +194,41 @@ function invokeSlaDueEvents(int $workspaceId, CarbonImmutable $windowStart): arr
|
||||
->and($first[0]['fingerprint_key'])->toBe($second[0]['fingerprint_key'])
|
||||
->and($first[0]['fingerprint_key'])->not->toBe($third[0]['fingerprint_key']);
|
||||
});
|
||||
|
||||
it('keeps aggregate sla due alerts separate from finding-level due soon reminders', function (): void {
|
||||
$now = CarbonImmutable::parse('2026-04-22T12:00:00Z');
|
||||
CarbonImmutable::setTestNow($now);
|
||||
|
||||
[$user, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$workspaceId = (int) session()->get(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
Finding::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => $tenant->getKey(),
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'severity' => Finding::SEVERITY_HIGH,
|
||||
'due_at' => $now->subHour(),
|
||||
]);
|
||||
|
||||
Finding::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => $tenant->getKey(),
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'severity' => Finding::SEVERITY_CRITICAL,
|
||||
'due_at' => $now->addHours(6),
|
||||
]);
|
||||
|
||||
$events = invokeSlaDueEvents($workspaceId, $now->subDay());
|
||||
|
||||
expect($events)->toHaveCount(1)
|
||||
->and($events[0]['event_type'])->toBe(AlertRule::EVENT_SLA_DUE)
|
||||
->and($events[0]['metadata'])->toMatchArray([
|
||||
'overdue_total' => 1,
|
||||
'overdue_by_severity' => [
|
||||
'critical' => 0,
|
||||
'high' => 1,
|
||||
'medium' => 0,
|
||||
'low' => 0,
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
@ -0,0 +1,215 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Finding;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\User;
|
||||
use App\Notifications\Findings\FindingEventNotification;
|
||||
use App\Services\Findings\FindingNotificationService;
|
||||
use App\Services\Findings\FindingWorkflowService;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
afterEach(function (): void {
|
||||
CarbonImmutable::setTestNow();
|
||||
});
|
||||
|
||||
function latestFindingNotificationFor(User $user): ?\Illuminate\Notifications\DatabaseNotification
|
||||
{
|
||||
return $user->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->latest('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
function findingNotificationCountFor(User $user, string $eventType): int
|
||||
{
|
||||
return $user->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->get()
|
||||
->filter(fn ($notification): bool => data_get($notification->data, 'finding_event.event_type') === $eventType)
|
||||
->count();
|
||||
}
|
||||
|
||||
function runEvaluateAlertsForWorkspace(int $workspaceId): void
|
||||
{
|
||||
$operationRun = OperationRun::factory()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => null,
|
||||
'type' => 'alerts.evaluate',
|
||||
'status' => OperationRunStatus::Queued->value,
|
||||
'outcome' => OperationRunOutcome::Pending->value,
|
||||
]);
|
||||
|
||||
$job = new \App\Jobs\Alerts\EvaluateAlertsJob($workspaceId, (int) $operationRun->getKey());
|
||||
$job->handle(
|
||||
app(\App\Services\Alerts\AlertDispatchService::class),
|
||||
app(\App\Services\OperationRunService::class),
|
||||
app(FindingNotificationService::class),
|
||||
);
|
||||
}
|
||||
|
||||
it('emits assignment notifications only when a new assignee is committed', function (): void {
|
||||
[$owner, $tenant] = $this->actingAsFindingOperator();
|
||||
$firstAssignee = User::factory()->create(['name' => 'First Assignee']);
|
||||
createUserWithTenant(tenant: $tenant, user: $firstAssignee, role: 'operator');
|
||||
|
||||
$secondAssignee = User::factory()->create(['name' => 'Second Assignee']);
|
||||
createUserWithTenant(tenant: $tenant, user: $secondAssignee, role: 'operator');
|
||||
|
||||
$finding = $this->makeFindingForWorkflow($tenant, Finding::STATUS_TRIAGED, [
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
]);
|
||||
|
||||
$workflow = app(FindingWorkflowService::class);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding,
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: (int) $firstAssignee->getKey(),
|
||||
ownerUserId: (int) $owner->getKey(),
|
||||
);
|
||||
|
||||
$firstNotification = latestFindingNotificationFor($firstAssignee);
|
||||
|
||||
expect($firstNotification)->not->toBeNull()
|
||||
->and(data_get($firstNotification?->data, 'title'))->toBe('Finding assigned')
|
||||
->and(data_get($firstNotification?->data, 'finding_event.event_type'))->toBe(AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding->fresh(),
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: (int) $firstAssignee->getKey(),
|
||||
ownerUserId: (int) $secondAssignee->getKey(),
|
||||
);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding->fresh(),
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: null,
|
||||
ownerUserId: (int) $secondAssignee->getKey(),
|
||||
);
|
||||
|
||||
expect(findingNotificationCountFor($firstAssignee, AlertRule::EVENT_FINDINGS_ASSIGNED))->toBe(1);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding->fresh(),
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: (int) $secondAssignee->getKey(),
|
||||
ownerUserId: (int) $secondAssignee->getKey(),
|
||||
);
|
||||
|
||||
$secondNotification = latestFindingNotificationFor($secondAssignee);
|
||||
|
||||
expect($secondNotification)->not->toBeNull()
|
||||
->and(data_get($secondNotification?->data, 'finding_event.event_type'))->toBe(AlertRule::EVENT_FINDINGS_ASSIGNED)
|
||||
->and(findingNotificationCountFor($secondAssignee, AlertRule::EVENT_FINDINGS_ASSIGNED))->toBe(1);
|
||||
});
|
||||
|
||||
it('dedupes repeated reopen dispatches for the same reopen occurrence', function (): void {
|
||||
$now = CarbonImmutable::parse('2026-04-22T09:30:00Z');
|
||||
CarbonImmutable::setTestNow($now);
|
||||
|
||||
[$owner, $tenant] = $this->actingAsFindingOperator();
|
||||
$assignee = User::factory()->create(['name' => 'Assigned Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = $this->makeFindingForWorkflow($tenant, Finding::STATUS_RESOLVED, [
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
$reopened = app(FindingWorkflowService::class)->reopenBySystem(
|
||||
finding: $finding,
|
||||
tenant: $tenant,
|
||||
reopenedAt: $now,
|
||||
);
|
||||
|
||||
expect(findingNotificationCountFor($assignee, AlertRule::EVENT_FINDINGS_REOPENED))->toBe(1);
|
||||
|
||||
app(FindingNotificationService::class)->dispatch($reopened->fresh(), AlertRule::EVENT_FINDINGS_REOPENED);
|
||||
|
||||
expect(findingNotificationCountFor($assignee, AlertRule::EVENT_FINDINGS_REOPENED))->toBe(1);
|
||||
});
|
||||
|
||||
it('sends due soon and overdue notifications once per due cycle and resets when due_at changes', function (): void {
|
||||
$now = CarbonImmutable::parse('2026-04-22T10:00:00Z');
|
||||
CarbonImmutable::setTestNow($now);
|
||||
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$workspaceId = (int) $tenant->workspace_id;
|
||||
Filament::setTenant($tenant, true);
|
||||
$this->actingAs($owner);
|
||||
|
||||
$assignee = User::factory()->create(['name' => 'Due Soon Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$dueSoonFinding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
'due_at' => $now->addHours(6),
|
||||
]);
|
||||
|
||||
$overdueFinding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => null,
|
||||
'due_at' => $now->subHours(2),
|
||||
]);
|
||||
|
||||
$closedFinding = Finding::factory()->for($tenant)->closed()->create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
'due_at' => $now->subHours(1),
|
||||
]);
|
||||
|
||||
runEvaluateAlertsForWorkspace($workspaceId);
|
||||
runEvaluateAlertsForWorkspace($workspaceId);
|
||||
|
||||
expect(findingNotificationCountFor($assignee, AlertRule::EVENT_FINDINGS_DUE_SOON))->toBe(1)
|
||||
->and(findingNotificationCountFor($owner, AlertRule::EVENT_FINDINGS_OVERDUE))->toBe(1);
|
||||
|
||||
expect($assignee->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->get()
|
||||
->contains(fn ($notification): bool => (int) data_get($notification->data, 'finding_event.finding_id') === (int) $closedFinding->getKey()))
|
||||
->toBeFalse();
|
||||
|
||||
$dueSoonFinding->forceFill([
|
||||
'due_at' => $now->addHours(12),
|
||||
])->save();
|
||||
|
||||
$overdueFinding->forceFill([
|
||||
'due_at' => $now->addDay()->subHour(),
|
||||
])->save();
|
||||
|
||||
runEvaluateAlertsForWorkspace($workspaceId);
|
||||
|
||||
expect(findingNotificationCountFor($assignee, AlertRule::EVENT_FINDINGS_DUE_SOON))->toBe(2)
|
||||
->and(findingNotificationCountFor($owner, AlertRule::EVENT_FINDINGS_OVERDUE))->toBe(1);
|
||||
|
||||
$dueSoonFinding->forceFill([
|
||||
'due_at' => $now->addDays(5),
|
||||
])->save();
|
||||
|
||||
CarbonImmutable::setTestNow($now->addDays(2));
|
||||
$overdueFinding->forceFill([
|
||||
'due_at' => CarbonImmutable::now('UTC')->subHour(),
|
||||
])->save();
|
||||
|
||||
runEvaluateAlertsForWorkspace($workspaceId);
|
||||
|
||||
expect(findingNotificationCountFor($owner, AlertRule::EVENT_FINDINGS_OVERDUE))->toBe(2);
|
||||
});
|
||||
@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Finding;
|
||||
use App\Models\TenantMembership;
|
||||
use App\Models\User;
|
||||
use App\Notifications\Findings\FindingEventNotification;
|
||||
use App\Services\Auth\CapabilityResolver;
|
||||
use App\Services\Findings\FindingNotificationService;
|
||||
use App\Services\Findings\FindingWorkflowService;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
afterEach(function (): void {
|
||||
CarbonImmutable::setTestNow();
|
||||
});
|
||||
|
||||
function dispatchedFindingNotificationsFor(User $user): \Illuminate\Support\Collection
|
||||
{
|
||||
return $user->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
it('uses the documented recipient precedence for assignment reopen due soon and overdue', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$service = app(FindingNotificationService::class);
|
||||
|
||||
$assignee = User::factory()->create(['name' => 'Assignee']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
'due_at' => now()->addHours(6),
|
||||
]);
|
||||
|
||||
$service->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
$service->dispatch($finding, AlertRule::EVENT_FINDINGS_REOPENED);
|
||||
$service->dispatch($finding, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
$service->dispatch($finding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
expect(dispatchedFindingNotificationsFor($assignee)
|
||||
->pluck('data.finding_event.event_type')
|
||||
->all())
|
||||
->toContain(AlertRule::EVENT_FINDINGS_ASSIGNED, AlertRule::EVENT_FINDINGS_REOPENED, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
|
||||
expect(dispatchedFindingNotificationsFor($owner)
|
||||
->pluck('data.finding_event.event_type')
|
||||
->all())
|
||||
->toContain(AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
$fallbackFinding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_REOPENED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => null,
|
||||
'due_at' => now()->addHours(2),
|
||||
]);
|
||||
|
||||
$service->dispatch($fallbackFinding, AlertRule::EVENT_FINDINGS_REOPENED);
|
||||
$service->dispatch($fallbackFinding, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
|
||||
$ownerEventTypes = dispatchedFindingNotificationsFor($owner)
|
||||
->pluck('data.finding_event.event_type')
|
||||
->all();
|
||||
|
||||
expect($ownerEventTypes)->toContain(AlertRule::EVENT_FINDINGS_REOPENED, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
});
|
||||
|
||||
it('suppresses direct delivery when the preferred recipient loses tenant access', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Removed Assignee']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_REOPENED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
TenantMembership::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('user_id', (int) $assignee->getKey())
|
||||
->delete();
|
||||
|
||||
app(CapabilityResolver::class)->clearCache();
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_REOPENED);
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('suppressed')
|
||||
->and(dispatchedFindingNotificationsFor($assignee))->toHaveCount(0)
|
||||
->and(dispatchedFindingNotificationsFor($owner))->toHaveCount(0);
|
||||
});
|
||||
|
||||
it('does not broaden delivery to the owner when the assignee is present but no longer entitled', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Current Assignee']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
'due_at' => now()->addHours(3),
|
||||
]);
|
||||
|
||||
$resolver = \Mockery::mock(CapabilityResolver::class);
|
||||
$resolver->shouldReceive('isMember')->andReturnTrue();
|
||||
$resolver->shouldReceive('can')
|
||||
->andReturnUsing(function (User $user): bool {
|
||||
return $user->name !== 'Current Assignee';
|
||||
});
|
||||
app()->instance(CapabilityResolver::class, $resolver);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_DUE_SOON);
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('suppressed')
|
||||
->and(dispatchedFindingNotificationsFor($assignee))->toHaveCount(0)
|
||||
->and(dispatchedFindingNotificationsFor($owner))->toHaveCount(0);
|
||||
});
|
||||
|
||||
it('suppresses owner-only assignment edits and assignee clears from creating direct notifications', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Assigned Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$replacementOwner = User::factory()->create(['name' => 'Replacement Owner']);
|
||||
createUserWithTenant(tenant: $tenant, user: $replacementOwner, role: 'manager');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
$workflow = app(FindingWorkflowService::class);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding,
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: (int) $assignee->getKey(),
|
||||
ownerUserId: (int) $replacementOwner->getKey(),
|
||||
);
|
||||
|
||||
$workflow->assign(
|
||||
finding: $finding->fresh(),
|
||||
tenant: $tenant,
|
||||
actor: $owner,
|
||||
assigneeUserId: null,
|
||||
ownerUserId: (int) $replacementOwner->getKey(),
|
||||
);
|
||||
|
||||
expect(dispatchedFindingNotificationsFor($assignee))->toHaveCount(0)
|
||||
->and(dispatchedFindingNotificationsFor($owner))->toHaveCount(0)
|
||||
->and(dispatchedFindingNotificationsFor($replacementOwner))->toHaveCount(0);
|
||||
});
|
||||
|
||||
it('suppresses due notifications for terminal findings', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->closed()->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $owner->getKey(),
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('suppressed')
|
||||
->and(dispatchedFindingNotificationsFor($owner))->toHaveCount(0);
|
||||
});
|
||||
|
||||
it('sends one direct notification when owner and assignee are the same entitled user', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_IN_PROGRESS,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $owner->getKey(),
|
||||
'due_at' => now()->subHour(),
|
||||
]);
|
||||
|
||||
$result = app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_OVERDUE);
|
||||
|
||||
expect($result['direct_delivery_status'])->toBe('sent')
|
||||
->and(dispatchedFindingNotificationsFor($owner))->toHaveCount(1)
|
||||
->and(data_get(dispatchedFindingNotificationsFor($owner)->first(), 'data.finding_event.recipient_reason'))->toBe('current_owner');
|
||||
});
|
||||
@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Resources\FindingResource;
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Finding;
|
||||
use App\Models\TenantMembership;
|
||||
use App\Models\User;
|
||||
use App\Notifications\Findings\FindingEventNotification;
|
||||
use App\Services\Auth\CapabilityResolver;
|
||||
use App\Services\Findings\FindingNotificationService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
it('stores a filament payload with one tenant finding deep link and recipient reason copy', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Assigned Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
|
||||
$notification = $assignee->notifications()
|
||||
->where('type', FindingEventNotification::class)
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
expect($notification)->not->toBeNull()
|
||||
->and(data_get($notification?->data, 'format'))->toBe('filament')
|
||||
->and(data_get($notification?->data, 'title'))->toBe('Finding assigned')
|
||||
->and(data_get($notification?->data, 'actions.0.label'))->toBe('Open finding')
|
||||
->and(data_get($notification?->data, 'actions.0.url'))
|
||||
->toBe(FindingResource::getUrl('view', ['record' => $finding], panel: 'tenant', tenant: $tenant))
|
||||
->and(data_get($notification?->data, 'finding_event.event_type'))->toBe(AlertRule::EVENT_FINDINGS_ASSIGNED)
|
||||
->and(data_get($notification?->data, 'finding_event.recipient_reason'))->toBe('new_assignee');
|
||||
});
|
||||
|
||||
it('returns 404 when a finding notification link is opened after tenant access is removed', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Removed Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
|
||||
$url = data_get($assignee->notifications()->latest('id')->first(), 'data.actions.0.url');
|
||||
|
||||
TenantMembership::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('user_id', (int) $assignee->getKey())
|
||||
->delete();
|
||||
|
||||
app(CapabilityResolver::class)->clearCache();
|
||||
|
||||
$this->actingAs($assignee)
|
||||
->get($url)
|
||||
->assertNotFound();
|
||||
});
|
||||
|
||||
it('returns 403 when a finding notification link is opened by an in-scope member without findings view capability', function (): void {
|
||||
[$owner, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$assignee = User::factory()->create(['name' => 'Scoped Operator']);
|
||||
createUserWithTenant(tenant: $tenant, user: $assignee, role: 'operator');
|
||||
|
||||
$finding = Finding::factory()->for($tenant)->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'status' => Finding::STATUS_TRIAGED,
|
||||
'owner_user_id' => (int) $owner->getKey(),
|
||||
'assignee_user_id' => (int) $assignee->getKey(),
|
||||
]);
|
||||
|
||||
app(FindingNotificationService::class)->dispatch($finding, AlertRule::EVENT_FINDINGS_ASSIGNED);
|
||||
|
||||
$url = data_get($assignee->notifications()->latest('id')->first(), 'data.actions.0.url');
|
||||
|
||||
Gate::define(Capabilities::TENANT_FINDINGS_VIEW, fn (): bool => false);
|
||||
|
||||
$this->actingAs($assignee);
|
||||
Filament::setTenant($tenant, true);
|
||||
|
||||
$this->get($url)->assertForbidden();
|
||||
});
|
||||
@ -5,7 +5,7 @@ # Spec Candidates
|
||||
>
|
||||
> **Flow**: Inbox → Qualified → Planned → Spec created → moved to `Promoted to Spec`
|
||||
|
||||
**Last reviewed**: 2026-04-21 (added `My Work` candidate family and aligned it with existing promoted work)
|
||||
**Last reviewed**: 2026-04-22 (promoted `Findings Notifications & Escalation v1` to Spec 224 and aligned the list)
|
||||
|
||||
---
|
||||
|
||||
@ -46,6 +46,7 @@ ## Promoted to Spec
|
||||
- Humanized Diagnostic Summaries for Governance Operations → Spec 220 (`governance-run-summaries`)
|
||||
- Findings Operator Inbox v1 → Spec 221 (`findings-operator-inbox`)
|
||||
- Findings Intake & Team Queue v1 -> Spec 222 (`findings-intake-team-queue`)
|
||||
- Findings Notifications & Escalation v1 → Spec 224 (`findings-notifications-escalation`)
|
||||
- Provider-Backed Action Preflight and Dispatch Gate Unification → Spec 216 (`provider-dispatch-gate`)
|
||||
- Record Page Header Discipline & Contextual Navigation → Spec 192 (`record-header-discipline`)
|
||||
- Monitoring Surface Action Hierarchy & Workbench Semantics → Spec 193 (`monitoring-action-hierarchy`)
|
||||
@ -361,18 +362,6 @@ ### Tenant Operational Readiness & Status Truth Hierarchy
|
||||
|
||||
> Findings execution layer cluster: complementary to existing Spec 154 (`finding-risk-acceptance`). Keep these split so prioritization can pull workflow semantics, operator work surfaces, alerts, external handoff, and later portfolio operating slices independently instead of collapsing them into one oversized "Findings v2" spec.
|
||||
|
||||
### Findings Notifications & Escalation v1
|
||||
- **Type**: alerts / workflow execution
|
||||
- **Source**: findings execution layer candidate pack 2026-04-17; gap between assignment metadata and actionable control loop
|
||||
- **Problem**: Assignment, reopen, due, and overdue states currently risk becoming silent metadata unless operators keep polling findings views.
|
||||
- **Why it matters**: Due dates without reminders or escalation are visibility, not control. Existing alert foundations only create operator value if findings workflow emits actionable events.
|
||||
- **Proposed direction**: Add notifications for assignment, system-driven reopen, due-soon, and overdue states; introduce minimal escalation to owner or a defined role; explicitly consume the existing alert and notification infrastructure rather than building a findings-specific delivery system.
|
||||
- **Explicit non-goals**: Multi-stage escalation chains, a large notification-preference center, and bidirectional ticket synchronization.
|
||||
- **Dependencies**: Ownership semantics, operator inbox/intake surfaces, due/SLA logic, alert plumbing.
|
||||
- **Roadmap fit**: Findings workflow hardening on top of the existing alerting foundation.
|
||||
- **Strategic sequencing**: After inbox and intake exist so notifications land on meaningful destinations.
|
||||
- **Priority**: high
|
||||
|
||||
### Assignment Hygiene & Stale Work Detection
|
||||
- **Type**: workflow hardening / operations hygiene
|
||||
- **Source**: findings execution layer candidate pack 2026-04-17; assignment lifecycle hygiene gap analysis
|
||||
|
||||
@ -1,199 +0,0 @@
|
||||
# Implementation Plan: Finding Ownership Semantics Clarification
|
||||
|
||||
**Branch**: `001-finding-ownership-semantics` | **Date**: 2026-04-20 | **Spec**: [spec.md](./spec.md)
|
||||
**Input**: Feature specification from `/specs/001-finding-ownership-semantics/spec.md`
|
||||
|
||||
**Note**: The setup script reported a numeric-prefix collision with `001-rbac-onboarding`, but it still resolved the active branch and plan path correctly to this feature directory. Planning continues against the current branch path.
|
||||
|
||||
## Summary
|
||||
|
||||
Clarify the meaning of finding owner versus finding assignee across the existing tenant findings list, detail surface, responsibility-update flows, and exception-request context without adding new persistence, capabilities, or workflow services. The implementation will reuse the existing `owner_user_id` and `assignee_user_id` fields, add a derived responsibility-state presentation layer on top of current data, tighten operator-facing copy and audit/feedback wording, preserve tenant-safe Filament behavior, and extend focused Pest + Livewire coverage for list/detail semantics, responsibility updates, and exception-owner boundary cases.
|
||||
|
||||
## Technical Context
|
||||
|
||||
**Language/Version**: PHP 8.4.15 / Laravel 12
|
||||
**Primary Dependencies**: Filament v5, Livewire v4.0+, Pest v4, Tailwind CSS v4
|
||||
**Storage**: PostgreSQL via Sail; existing `findings.owner_user_id`, `findings.assignee_user_id`, and `finding_exceptions.owner_user_id` fields; no schema changes planned
|
||||
**Testing**: Pest v4 feature and Livewire component tests via `./vendor/bin/sail artisan test --compact`
|
||||
**Validation Lanes**: fast-feedback, confidence
|
||||
**Target Platform**: Laravel monolith in Sail/Docker locally; Dokploy-hosted Linux deployment for staging/production
|
||||
**Project Type**: Laravel monolith / Filament admin application
|
||||
**Performance Goals**: No new remote calls, no new queued work, no material list/detail query growth beyond current eager loading of owner, assignee, and exception-owner relations
|
||||
**Constraints**: Keep responsibility state derived rather than persisted; preserve existing tenant membership validation; preserve deny-as-not-found tenant isolation; do not split capabilities or add new abstractions; keep destructive-action confirmations unchanged
|
||||
**Scale/Scope**: 1 primary Filament resource, 1 model helper or equivalent derived-state mapping, 1 workflow/audit wording touchpoint, 1 exception-owner wording boundary, and 2 focused new/expanded feature test families
|
||||
|
||||
## UI / Surface Guardrail Plan
|
||||
|
||||
- **Guardrail scope**: changed surfaces
|
||||
- **Native vs custom classification summary**: native
|
||||
- **Shared-family relevance**: existing tenant findings resource and exception-context surfaces only
|
||||
- **State layers in scope**: page, detail, URL-query
|
||||
- **Handling modes by drift class or surface**: review-mandatory
|
||||
- **Repository-signal treatment**: review-mandatory
|
||||
- **Special surface test profiles**: standard-native-filament
|
||||
- **Required tests or manual smoke**: functional-core, state-contract
|
||||
- **Exception path and spread control**: none; the feature reuses existing resource/table/infolist/action primitives and keeps exception-owner semantics local to the finding context
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
|
||||
## Constitution Check
|
||||
|
||||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
- Inventory-first: PASS. The feature only clarifies operator semantics on tenant-owned findings and exception artifacts; it does not change observed-state or snapshot truth.
|
||||
- Read/write separation: PASS. Responsibility updates remain TenantPilot-only writes on existing finding records; no Microsoft tenant mutation is introduced. Existing destructive-like actions keep their current confirmation rules.
|
||||
- Graph contract path: PASS / N/A. No Graph calls or contract-registry changes are involved.
|
||||
- Deterministic capabilities: PASS. Existing canonical findings capabilities remain the source of truth; no new capability split is introduced.
|
||||
- RBAC-UX: PASS. Tenant-context membership remains the isolation boundary. Non-members remain 404 and in-scope members missing `TENANT_FINDINGS_ASSIGN` remain 403 for responsibility mutations.
|
||||
- Workspace isolation: PASS. The feature remains inside tenant-context findings flows and preserves existing workspace-context stabilization patterns.
|
||||
- Global search: PASS. `FindingResource` already has a `view` page, so any existing global-search participation remains compliant. This feature does not add or remove global search.
|
||||
- Tenant isolation: PASS. All reads and writes remain tenant-scoped and continue to restrict owner/assignee selections to current tenant members.
|
||||
- Run observability / Ops-UX: PASS / N/A. No new long-running, queued, or remote work is introduced and no `OperationRun` behavior changes.
|
||||
- Automation / data minimization: PASS / N/A. No new background automation or payload persistence is introduced.
|
||||
- Test governance (TEST-GOV-001): PASS. The narrowest proving surface is feature-level Filament + workflow coverage with low fixture cost and no heavy-family expansion.
|
||||
- Proportionality / no premature abstraction / persisted truth / behavioral state: PASS. Responsibility state remains derived from existing fields and does not create a persisted enum, new abstraction, or new table.
|
||||
- UI semantics / few layers: PASS. The plan uses direct domain-to-UI mapping on `FindingResource` and an optional local helper on `Finding` rather than a new presenter or taxonomy layer.
|
||||
- Badge semantics (BADGE-001): PASS with restraint. If a new responsibility badge or label is added, it stays local to findings semantics unless multiple consumers later prove centralization is necessary.
|
||||
- Filament-native UI / action surface contract / UX-001: PASS. Existing native Filament tables, infolists, filters, selects, grouped actions, and modals remain the implementation path; the finding remains the sole primary inspect/open model and row click remains the canonical inspect affordance.
|
||||
|
||||
**Post-Phase-1 re-check**: PASS. The design keeps responsibility semantics derived, tenant-safe, and local to the existing findings resource and tests.
|
||||
|
||||
## Test Governance Check
|
||||
|
||||
- **Test purpose / classification by changed surface**: Feature
|
||||
- **Affected validation lanes**: fast-feedback, confidence
|
||||
- **Why this lane mix is the narrowest sufficient proof**: The business truth is visible in Filament list/detail rendering, responsibility action behavior, and tenant-scoped audit feedback. Unit-only testing would miss the operator-facing semantics, while browser/heavy-governance coverage would add unnecessary cost.
|
||||
- **Narrowest proving command(s)**:
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Filament/Resources/FindingResourceOwnershipSemanticsTest.php`
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingAssignmentAuditSemanticsTest.php`
|
||||
- **Fixture / helper / factory / seed / context cost risks**: Low. Existing tenant/user/finding factories and tenant membership helpers are sufficient. The only explicit context risk is tenant-panel routing and admin canonical tenant state.
|
||||
- **Expensive defaults or shared helper growth introduced?**: no; tests should keep tenant context explicit rather than broadening shared fixtures.
|
||||
- **Heavy-family additions, promotions, or visibility changes**: none
|
||||
- **Surface-class relief / special coverage rule**: standard-native relief; explicit tenant-panel routing is required for authorization assertions.
|
||||
- **Closing validation and reviewer handoff**: Re-run the two focused test files plus formatter on dirty files. Reviewers should verify owner versus assignee wording on list/detail surfaces, exception-owner separation, and 404/403 semantics for out-of-scope versus in-scope unauthorized users.
|
||||
- **Budget / baseline / trend follow-up**: none
|
||||
- **Review-stop questions**: lane fit, hidden fixture cost, accidental presenter growth, tenant-context drift in tests
|
||||
- **Escalation path**: none
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
- **Why no dedicated follow-up spec is needed**: This work stays inside the existing findings responsibility contract. Only future queue/team-routing or capability-split work would justify a separate spec.
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/001-finding-ownership-semantics/
|
||||
├── plan.md
|
||||
├── spec.md
|
||||
├── research.md
|
||||
├── data-model.md
|
||||
├── quickstart.md
|
||||
├── contracts/
|
||||
│ └── finding-responsibility.openapi.yaml
|
||||
├── checklists/
|
||||
│ └── requirements.md
|
||||
└── tasks.md
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
|
||||
```text
|
||||
apps/platform/
|
||||
├── app/
|
||||
│ ├── Filament/
|
||||
│ │ └── Resources/
|
||||
│ │ └── FindingResource.php # MODIFY: list/detail labels, derived responsibility state, filters, action help text, exception-owner wording
|
||||
│ ├── Models/
|
||||
│ │ └── Finding.php # MODIFY: local derived responsibility-state helper if needed
|
||||
│ └── Services/
|
||||
│ └── Findings/
|
||||
│ ├── FindingWorkflowService.php # MODIFY: mutation feedback / audit wording for owner-only vs assignee-only changes
|
||||
│ ├── FindingExceptionService.php # MODIFY: request-exception wording if the exception-owner boundary needs alignment
|
||||
│ └── FindingRiskGovernanceResolver.php # MODIFY: next-action copy to reflect orphaned-accountability semantics
|
||||
└── tests/
|
||||
└── Feature/
|
||||
├── Filament/
|
||||
│ └── Resources/
|
||||
│ └── FindingResourceOwnershipSemanticsTest.php # NEW: list/detail rendering, filters, exception-owner distinction, tenant-safe semantics
|
||||
└── Findings/
|
||||
├── FindingAssignmentAuditSemanticsTest.php # NEW: owner-only, assignee-only, combined update feedback/audit semantics
|
||||
├── FindingWorkflowRowActionsTest.php # MODIFY: assignment form/help-text semantics and member validation coverage
|
||||
└── FindingWorkflowServiceTest.php # MODIFY: audit metadata and responsibility-mutation expectations
|
||||
```
|
||||
|
||||
**Structure Decision**: Keep all work inside the existing Laravel/Filament monolith. The implementation is a targeted semantics pass over the current findings resource and workflow tests; no new folders, packages, or service families are required.
|
||||
|
||||
## Complexity Tracking
|
||||
|
||||
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||||
|-----------|------------|-------------------------------------|
|
||||
| — | — | — |
|
||||
|
||||
## Proportionality Review
|
||||
|
||||
- **Current operator problem**: Operators cannot tell whether a finding change transferred accountability, active remediation work, or only exception ownership.
|
||||
- **Existing structure is insufficient because**: The existing fields and actions exist, but the current UI copy and derived next-step language do not establish a stable contract across list, detail, and exception flows.
|
||||
- **Narrowest correct implementation**: Reuse the existing `owner_user_id` and `assignee_user_id` fields, derive responsibility state from them, and tighten wording on existing Filament surfaces and audit feedback.
|
||||
- **Ownership cost created**: Low ongoing UI/test maintenance to keep future findings work aligned with the clarified contract.
|
||||
- **Alternative intentionally rejected**: A new ownership framework, queue model, or capability split was rejected because the current product has not yet exhausted the simpler owner-versus-assignee model.
|
||||
- **Release truth**: Current-release truth
|
||||
|
||||
## Phase 0 — Research (output: `research.md`)
|
||||
|
||||
See: [research.md](./research.md)
|
||||
|
||||
Research goals:
|
||||
- Confirm the existing source of truth for owner, assignee, and exception owner.
|
||||
- Confirm the smallest derived responsibility-state model that fits the current schema.
|
||||
- Confirm the existing findings tests and Filament routing pitfalls to avoid false negatives.
|
||||
- Confirm which operator-facing wording changes belong in resource copy versus workflow service feedback.
|
||||
|
||||
## Phase 1 — Design & Contracts (outputs: `data-model.md`, `contracts/`, `quickstart.md`)
|
||||
|
||||
See:
|
||||
- [data-model.md](./data-model.md)
|
||||
- [contracts/finding-responsibility.openapi.yaml](./contracts/finding-responsibility.openapi.yaml)
|
||||
- [quickstart.md](./quickstart.md)
|
||||
|
||||
Design focus:
|
||||
- Keep responsibility truth on existing finding and finding-exception records.
|
||||
- Model responsibility state as a derived projection over owner and assignee presence rather than a persisted enum.
|
||||
- Preserve exception owner as a separate governance concept when shown from a finding context.
|
||||
- Keep tenant membership validation and existing `FindingWorkflowService::assign()` semantics as the mutation boundary.
|
||||
|
||||
## Phase 2 — Implementation Outline (tasks created in `/speckit.tasks`)
|
||||
|
||||
### Surface semantics pass
|
||||
- Update the findings list column hierarchy so owner and assignee meaning is explicit at first scan.
|
||||
- Add a derived responsibility-state label or equivalent summary on list/detail surfaces.
|
||||
- Keep exception owner visibly separate from finding owner wherever both appear.
|
||||
|
||||
### Responsibility mutation clarity
|
||||
- Add owner/assignee help text to assignment flows.
|
||||
- Differentiate owner-only, assignee-only, and combined responsibility changes in operator feedback and audit-facing wording.
|
||||
- Keep current tenant-member validation and open-finding restrictions unchanged.
|
||||
|
||||
### Personal-work and next-action alignment
|
||||
- Add or refine personal-work filters so assignee-based work and owner-based accountability are explicitly separate.
|
||||
- Update next-action copy for owner-missing states so assignee-only findings are treated as accountability gaps.
|
||||
|
||||
### Regression protection
|
||||
- Add focused list/detail rendering tests for owner-only, assignee-only, both-set, same-user, and both-null states.
|
||||
- Add focused responsibility-update tests for owner-only, assignee-only, and combined changes.
|
||||
- Preserve tenant-context and authorization regression coverage using explicit Filament panel routing where needed.
|
||||
|
||||
### Verification
|
||||
- Run the two focused Pest files and any directly modified sibling findings tests.
|
||||
- Run Pint on dirty files through Sail.
|
||||
|
||||
## Constitution Check (Post-Design)
|
||||
|
||||
Re-check result: PASS. The design stays inside the existing findings domain, preserves tenant isolation and capability enforcement, avoids new persisted truth or semantic framework growth, and keeps responsibility state derived from current fields.
|
||||
|
||||
## Filament v5 Agent Output Contract
|
||||
|
||||
1. **Livewire v4.0+ compliance**: Yes. The feature only adjusts existing Filament v5 resources/pages/actions that already run on Livewire v4.0+.
|
||||
2. **Provider registration location**: No new panel or service providers are needed. Existing Filament providers remain registered in `apps/platform/bootstrap/providers.php`.
|
||||
3. **Global search**: `FindingResource` already has a `view` page via `getPages()`, so any existing global-search participation remains compliant. This feature does not enable new global search.
|
||||
4. **Destructive actions and authorization**: No new destructive actions are introduced. Existing destructive-like findings actions remain server-authorized and keep `->requiresConfirmation()` where already required. Responsibility updates continue to enforce tenant membership and the canonical findings capability registry.
|
||||
5. **Asset strategy**: No new frontend assets or published views. The feature uses existing Filament tables, infolists, filters, and action modals, so deployment asset handling stays unchanged and no new `filament:assets` step is added.
|
||||
6. **Testing plan**: Cover the change with focused Pest feature tests for findings resource responsibility semantics, assignment/audit wording, and existing workflow regression surfaces. No browser or heavy-governance expansion is planned.
|
||||
@ -1,204 +0,0 @@
|
||||
# Feature Specification: Finding Ownership Semantics Clarification
|
||||
|
||||
**Feature Branch**: `001-finding-ownership-semantics`
|
||||
**Created**: 2026-04-20
|
||||
**Status**: Draft
|
||||
**Input**: User description: "Finding Ownership Semantics Clarification"
|
||||
|
||||
## Spec Candidate Check *(mandatory — SPEC-GATE-001)*
|
||||
|
||||
- **Problem**: Open findings already store both an owner and an assignee, but the product does not yet state clearly which field represents accountability and which field represents active execution.
|
||||
- **Today's failure**: Operators can see or change responsibility on a finding without being sure whether they transferred accountability, execution work, or only exception ownership, which makes triage slower and audit language less trustworthy.
|
||||
- **User-visible improvement**: Findings surfaces make accountable owner, active assignee, and exception owner visibly distinct, so operators can route work faster and read ownership changes honestly.
|
||||
- **Smallest enterprise-capable version**: Clarify the existing responsibility contract on current findings list/detail/action surfaces, add explicit derived responsibility states, and align audit and filter language without creating new roles, queues, or persistence.
|
||||
- **Explicit non-goals**: No team queues, no escalation engine, no automatic reassignment hygiene, no new capability split, no new ownership framework, and no mandatory backfill before rollout.
|
||||
- **Permanent complexity imported**: One explicit product contract for finding owner versus assignee, one derived responsibility-state vocabulary, and focused acceptance tests for mixed ownership contexts.
|
||||
- **Why now**: The next findings execution slices depend on honest ownership semantics, and the ambiguity already affects triage, reassignment, and exception routing in today’s tenant workflow.
|
||||
- **Why not local**: A one-surface copy fix would leave contradictory meaning across the findings list, detail view, assignment flows, personal work cues, and exception-request language.
|
||||
- **Approval class**: Core Enterprise
|
||||
- **Red flags triggered**: None after scope cut. This spec clarifies existing fields instead of introducing a new semantics axis.
|
||||
- **Score**: Nutzen: 2 | Dringlichkeit: 2 | Scope: 2 | Komplexität: 2 | Produktnähe: 2 | Wiederverwendung: 1 | **Gesamt: 11/12**
|
||||
- **Decision**: approve
|
||||
|
||||
## Spec Scope Fields *(mandatory)*
|
||||
|
||||
- **Scope**: tenant
|
||||
- **Primary Routes**: `/admin/t/{tenant}/findings`, `/admin/t/{tenant}/findings/{finding}`
|
||||
- **Data Ownership**: Tenant-owned findings remain the source of truth; this spec also covers exception ownership only when it is shown or edited from a finding-context surface.
|
||||
- **RBAC**: Tenant membership is required for visibility. Tenant findings view permission gates read access. Tenant findings assign permission gates owner and assignee changes. Non-members or cross-tenant requests remain deny-as-not-found. Members without mutation permission receive an explicit authorization failure.
|
||||
|
||||
## UI / Surface Guardrail Impact *(mandatory when operator-facing surfaces are changed; otherwise write `N/A`)*
|
||||
|
||||
| Surface / Change | Operator-facing surface change? | Native vs Custom | Shared-Family Relevance | State Layers Touched | Exception Needed? | Low-Impact / `N/A` Note |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Tenant findings list and grouped bulk actions | yes | Native Filament + existing UI enforcement helpers | Same tenant work-queue family as other tenant resources | table, bulk-action modal, notification copy | no | Clarifies an existing resource instead of adding a new page |
|
||||
| Finding detail and single-record action modals | yes | Native Filament infolist + action modals | Same finding resource family | detail, action modal, helper copy | no | Keeps one decision flow inside the current resource |
|
||||
|
||||
## Decision-First Surface Role *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Decision Role | Human-in-the-loop Moment | Immediately Visible for First Decision | On-Demand Detail / Evidence | Why This Is Primary or Why Not | Workflow Alignment | Attention-load Reduction |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Tenant findings list and grouped bulk actions | Primary Decision Surface | A tenant operator reviews the open backlog and decides who owns the outcome and who should act next | Severity, lifecycle status, due state, owner, assignee, and derived responsibility state | Full evidence, audit trail, run metadata, and exception details | Primary because it is the queue where responsibility is routed at scale | Follows the operator’s “what needs action now?” workflow instead of raw data lineage | Removes the need to open each record just to tell who is accountable versus merely assigned |
|
||||
| Finding detail and single-record action modals | Secondary Context Surface | A tenant operator verifies one finding before reassigning work or requesting an exception | Finding summary, current owner, current assignee, exception owner when applicable, and next workflow action | Raw evidence, historical context, and additional governance details | Secondary because it resolves one case after the list has already identified the work item | Preserves the single-record decision loop without creating a separate ownership page | Avoids cross-page reconstruction when ownership and exception context must be compared together |
|
||||
|
||||
## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Action Surface Class | Surface Type | Likely Next Operator Action | Primary Inspect/Open Model | Row Click | Secondary Actions Placement | Destructive Actions Placement | Canonical Collection Route | Canonical Detail Route | Scope Signals | Canonical Noun | Critical Truth Visible by Default | Exception Type / Justification |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Tenant findings list and grouped bulk actions | List / Table / Bulk | Workflow queue / list-first resource | Open a finding or update responsibility | Finding | required | Structured `More` action group and grouped bulk actions | Existing dangerous actions remain inside grouped actions with confirmation where already required | /admin/t/{tenant}/findings | /admin/t/{tenant}/findings/{finding} | Tenant context, filters, severity, due state, workflow state | Findings / Finding | Accountable owner, active assignee, and whether the finding is assigned, owned-but-unassigned, or orphaned | none |
|
||||
| Finding detail and single-record action modals | Record / Detail / Actions | View-first operational detail | Confirm or update responsibility for one finding | Finding | N/A - detail surface | Structured header actions on the existing record page | Existing dangerous actions remain grouped and confirmed | /admin/t/{tenant}/findings | /admin/t/{tenant}/findings/{finding} | Tenant breadcrumb, lifecycle state, due state, governance context | Findings / Finding | Finding owner, finding assignee, and exception owner stay visibly distinct in the same context | none |
|
||||
|
||||
## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Primary Persona | Decision / Operator Action Supported | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Tenant findings list and grouped bulk actions | Tenant operator or tenant manager | Route responsibility on open findings and separate accountable ownership from active work | Workflow queue | Who owns this outcome, who is doing the work, and what needs reassignment now? | Severity, lifecycle state, due state, owner, assignee, derived responsibility state, and personal-work cues | Raw evidence, run identifiers, historical audit details | lifecycle, severity, governance validity, responsibility state | TenantPilot only | Open finding, Assign, Triage, Start progress | Resolve, Close, Request exception |
|
||||
| Finding detail and single-record action modals | Tenant operator or tenant manager | Verify and change responsibility for one finding without losing exception context | Detail/action surface | Is this finding owned by the right person, assigned to the right executor, and clearly separate from any exception owner? | Finding summary, owner, assignee, exception owner when present, due state, lifecycle state | Raw evidence payloads, extended audit history, related run metadata | lifecycle, governance validity, responsibility state | TenantPilot only | Assign, Start progress, Resolve | Close, Request exception |
|
||||
|
||||
## Proportionality Review *(mandatory when structural complexity is introduced)*
|
||||
|
||||
- **New source of truth?**: no
|
||||
- **New persisted entity/table/artifact?**: no
|
||||
- **New abstraction?**: no
|
||||
- **New enum/state/reason family?**: no persisted family; only derived responsibility-state rules on existing fields
|
||||
- **New cross-domain UI framework/taxonomy?**: no
|
||||
- **Current operator problem**: Operators cannot reliably distinguish accountability from active execution, which creates avoidable misrouting and weak audit interpretation.
|
||||
- **Existing structure is insufficient because**: Two existing user fields and an exception-owner concept can already appear in the same workflow, but current copy does not establish a stable product contract across list, detail, and action surfaces.
|
||||
- **Narrowest correct implementation**: Reuse the existing finding owner and assignee fields, define their meaning, and apply that meaning consistently to labels, filters, derived states, and audit copy.
|
||||
- **Ownership cost**: Focused UI copy review, acceptance tests for role combinations, and ongoing discipline to keep future findings work aligned with the same contract.
|
||||
- **Alternative intentionally rejected**: A broader ownership framework with separate role types, queues, or team routing was rejected because it adds durable complexity before the product has proven the simpler owner-versus-assignee contract.
|
||||
- **Release truth**: Current-release truth. This spec clarifies the meaning of responsibility on live findings now and becomes the contract for later execution surfaces.
|
||||
|
||||
## Testing / Lane / Runtime Impact *(mandatory for runtime behavior changes)*
|
||||
|
||||
- **Test purpose / classification**: Feature
|
||||
- **Validation lane(s)**: fast-feedback, confidence
|
||||
- **Why this classification and these lanes are sufficient**: The change is visible through tenant findings UI behavior, responsibility-state rendering, and audit-facing wording. Focused feature coverage proves the contract without introducing browser or heavy-governance breadth.
|
||||
- **New or expanded test families**: Expand tenant findings resource coverage to include responsibility rendering, personal-work cues, and mixed-context exception-owner wording. Add focused assignment-audit coverage for owner-only, assignee-only, and combined changes.
|
||||
- **Fixture / helper cost impact**: Low. Existing tenant, membership, user, and finding factories are sufficient; tests only need explicit responsibility combinations and tenant-scoped memberships.
|
||||
- **Heavy-family visibility / justification**: none
|
||||
- **Special surface test profile**: standard-native-filament
|
||||
- **Standard-native relief or required special coverage**: Ordinary feature coverage is sufficient, with explicit assertions for owner versus assignee visibility and authorization behavior.
|
||||
- **Reviewer handoff**: Reviewers should confirm that one positive and one negative authorization case exist, that list and detail surfaces use the same vocabulary, and that audit-facing feedback distinguishes owner changes from assignee changes.
|
||||
- **Budget / baseline / trend impact**: none
|
||||
- **Escalation needed**: none
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
- **Planned validation commands**:
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Filament/Resources/FindingResourceOwnershipSemanticsTest.php`
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingAssignmentAuditSemanticsTest.php`
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### User Story 1 - Route accountable ownership clearly (Priority: P1)
|
||||
|
||||
As a tenant operator, I want to tell immediately who owns a finding and who is actively assigned to it, so I can route remediation work without guessing which responsibility changed.
|
||||
|
||||
**Why this priority**: This is the smallest slice that fixes the core trust gap. Without it, every later execution surface inherits ambiguous meaning.
|
||||
|
||||
**Independent Test**: Can be tested by loading the tenant findings list and detail pages with findings in owner-only, owner-plus-assignee, and no-owner states, and verifying that the first decision is possible without opening unrelated screens.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an open finding with an owner and no assignee, **When** an operator views the findings list, **Then** the record is shown as owned but unassigned rather than fully assigned.
|
||||
2. **Given** an open finding with both an owner and an assignee, **When** an operator opens the finding detail, **Then** the accountable owner and active assignee are shown as separate roles.
|
||||
3. **Given** an open finding with no owner, **When** an operator views the finding from the list or detail page, **Then** the accountability gap is surfaced as orphaned work.
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - Reassign work without losing accountability (Priority: P2)
|
||||
|
||||
As a tenant manager, I want to change the assignee, the owner, or both in one responsibility update, so I can transfer execution work without silently transferring accountability.
|
||||
|
||||
**Why this priority**: Reassignment is the first mutation where the ambiguity causes operational mistakes and misleading audit history.
|
||||
|
||||
**Independent Test**: Can be tested by performing responsibility updates on open findings and asserting separate outcomes for owner-only, assignee-only, and combined changes.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an open finding with an existing owner and assignee, **When** an authorized operator changes only the assignee, **Then** the owner remains unchanged and the resulting feedback states that only the assignee changed.
|
||||
2. **Given** an open finding with an existing owner and assignee, **When** an authorized operator changes only the owner, **Then** the assignee remains unchanged and the resulting feedback states that only the owner changed.
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - Keep exception ownership separate (Priority: P3)
|
||||
|
||||
As a governance reviewer, I want exception ownership to remain visibly separate from finding ownership when both appear in one flow, so risk-acceptance work does not overwrite the meaning of the finding owner.
|
||||
|
||||
**Why this priority**: This is a narrower but important boundary that prevents the accepted-risk workflow from reintroducing the same ambiguity under a second owner label.
|
||||
|
||||
**Independent Test**: Can be tested by opening a finding that has, or is about to create, an exception record and verifying that finding owner and exception owner remain distinct in the same operator context.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a finding detail view that shows both finding responsibility and exception context, **When** the operator reviews ownership information, **Then** exception ownership is labeled separately from finding owner.
|
||||
2. **Given** an operator starts an exception request from a finding, **When** the request asks for exception ownership, **Then** the form language makes clear that the selected person owns the exception artifact, not the finding itself.
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- A finding may have the same user as both owner and assignee; the UI must show both roles as satisfied without implying duplication or error.
|
||||
- A finding with an assignee but no owner is still an orphaned accountability case, not a healthy assigned state.
|
||||
- Historical or imported findings may have both responsibility fields empty; they must render as orphaned without blocking rollout on a data backfill.
|
||||
- When personal-work cues are shown, assignee-based work and owner-based accountability must not collapse into one ambiguous shortcut.
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
**Constitution alignment (required):** This feature changes tenant-scoped finding workflow semantics only. It introduces no Microsoft Graph calls, no scheduled or long-running work, and no new `OperationRun`. Responsibility mutations remain audited tenant-local writes.
|
||||
|
||||
**Constitution alignment (RBAC-UX):** The affected authorization plane is tenant-context only. Cross-tenant and non-member access remain deny-as-not-found. Members without the findings assign permission continue to be blocked from responsibility mutations. The feature reuses the canonical capability registry and does not introduce raw role checks or a new capability split.
|
||||
|
||||
**Constitution alignment (UI-FIL-001 / Filament Action Surfaces / UX-001):** The feature reuses existing native Filament tables, infolist entries, filters, selects, modal actions, grouped actions, and notifications. No local badge taxonomy or custom action chrome is added. The action-surface contract remains satisfied: the finding is still the one and only primary inspect/open model, row click remains the canonical inspect affordance on the list, no redundant view action is introduced, and existing dangerous actions remain grouped and confirmed where already required.
|
||||
|
||||
**Constitution alignment (UI-NAMING-001 / UI-SEM-001 / TEST-TRUTH-001):** Direct field labels alone are insufficient because finding owner, finding assignee, and exception owner can appear in the same operator flow. This feature resolves that ambiguity by tightening the product vocabulary on the existing domain truth instead of adding a new semantic layer or presenter family. Tests prove visible business consequences rather than thin indirection.
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: The system MUST treat finding owner as the accountable user responsible for ensuring that a finding reaches a governed terminal outcome.
|
||||
- **FR-002**: The system MUST treat finding assignee as the user currently expected to perform or coordinate active remediation work, and any operator-facing use of `assigned` language MUST refer to this role only.
|
||||
- **FR-003**: Authorized users MUST be able to set, change, or clear finding owner and finding assignee independently on open findings while continuing to restrict selectable people to members of the active tenant.
|
||||
- **FR-004**: The system MUST derive responsibility state from the existing owner and assignee fields without adding a persisted lifecycle field. At minimum it MUST distinguish `owned but unassigned`, `assigned`, and `orphaned accountability`.
|
||||
- **FR-005**: Findings list, finding detail, and responsibility-update flows MUST label owner and assignee distinctly, and any mixed context that also references exception ownership MUST label that role as exception owner.
|
||||
- **FR-006**: When personal-work shortcuts or filters are shown on the tenant findings list, the system MUST expose separate, explicitly named cues for assignee-based work and owner-based accountability.
|
||||
- **FR-007**: Responsibility-update feedback and audit-facing wording MUST state whether a mutation changed the owner, the assignee, or both.
|
||||
- **FR-008**: Historical or imported findings with null or partial responsibility data MUST render using the derived responsibility contract without requiring a blocking data migration before rollout.
|
||||
- **FR-009**: Exception ownership MUST remain a separate governance concept. Creating, viewing, or editing an exception from a finding context MUST NOT silently replace the meaning of the finding owner.
|
||||
|
||||
## UI Action Matrix *(mandatory when Filament is changed)*
|
||||
|
||||
| Surface | Location | Header Actions | Inspect Affordance (List/Table) | Row Actions (max 2 visible) | Bulk Actions (grouped) | Empty-State CTA(s) | View Header Actions | Create/Edit Save+Cancel | Audit log? | Notes / Exemptions |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Tenant findings list | `/admin/t/{tenant}/findings` | None added by this feature | Full-row open into finding detail | Primary open affordance plus `More` action group with `Triage`, `Start progress`, `Assign`, `Resolve`, `Close`, and `Request exception` | Grouped actions including `Triage selected`, `Assign selected`, `Resolve selected`, and existing close/exception-safe bulk actions if already present | Existing findings empty state remains; no new CTA introduced | N/A | N/A | Yes for responsibility mutations and existing workflow mutations | Action Surface Contract satisfied. No empty groups or redundant view action introduced. |
|
||||
| Finding detail | `/admin/t/{tenant}/findings/{finding}` | Existing record-level workflow actions only | Entered from the list row click; no separate inspect action added | Structured record actions retain `Assign`, `Start progress`, `Resolve`, `Close`, and `Request exception` | N/A | N/A | Existing view header actions only | N/A | Yes for responsibility mutations and existing workflow mutations | UI-FIL-001 satisfied through existing infolist and action modal primitives. No exemption needed. |
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
|
||||
- **Finding responsibility**: The visible responsibility contract attached to an open finding, consisting of accountable ownership, active execution assignment, and a derived responsibility state.
|
||||
- **Finding owner**: The accountable person who owns the outcome of the finding and is expected to ensure it reaches a governed end state.
|
||||
- **Finding assignee**: The person currently expected to perform or coordinate the remediation work on the finding.
|
||||
- **Exception owner**: The accountable person for an exception artifact created from a finding; separate from finding owner whenever both appear in one operator context.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: In acceptance review, an authorized operator can identify owner, assignee, and responsibility state for any scripted open-finding example from the list or detail surface within 10 seconds.
|
||||
- **SC-002**: 100% of covered responsibility combinations in automated acceptance tests, including same-person, owner-only, owner-plus-assignee, assignee-only, and both-empty cases, render the correct visible labels and derived state.
|
||||
- **SC-003**: 100% of covered responsibility-update tests distinguish owner-only, assignee-only, and combined changes in operator feedback and audit-facing wording.
|
||||
- **SC-004**: When personal-work shortcuts are present, an operator can isolate assignee-based work and owner-based accountability from the findings list in one interaction each.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- Existing finding owner and assignee fields remain the single source of truth for responsibility in this slice.
|
||||
- Open findings may legitimately begin without an assignee while still needing an accountable owner.
|
||||
- Membership hygiene for users who later lose tenant access is a separate follow-up concern and not solved by this clarification slice.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Introduce team, queue, or workgroup ownership.
|
||||
- Add automatic escalation, reassignment, or inactivity timers.
|
||||
- Split authorization into separate owner-edit and assignee-edit capabilities.
|
||||
- Require a mandatory historical backfill before the clarified semantics can ship.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Spec 111, Findings Workflow + SLA, remains the lifecycle and assignment baseline that this spec clarifies.
|
||||
- Spec 154, Finding Risk Acceptance, remains the exception governance baseline whose owner semantics must stay separate from finding owner.
|
||||
@ -0,0 +1,35 @@
|
||||
# Specification Quality Checklist: Findings Notifications & Escalation v1
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2026-04-22
|
||||
**Feature**: [spec.md](../spec.md)
|
||||
|
||||
## Content Quality
|
||||
|
||||
- [x] No implementation details (languages, frameworks, APIs)
|
||||
- [x] Focused on user value and business needs
|
||||
- [x] Written for non-technical stakeholders
|
||||
- [x] All mandatory sections completed
|
||||
|
||||
## Requirement Completeness
|
||||
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain
|
||||
- [x] Requirements are testable and unambiguous
|
||||
- [x] Success criteria are measurable
|
||||
- [x] Success criteria are technology-agnostic (no implementation details)
|
||||
- [x] All acceptance scenarios are defined
|
||||
- [x] Edge cases are identified
|
||||
- [x] Scope is clearly bounded
|
||||
- [x] Dependencies and assumptions identified
|
||||
|
||||
## Feature Readiness
|
||||
|
||||
- [x] All functional requirements have clear acceptance criteria
|
||||
- [x] User scenarios cover primary flows
|
||||
- [x] Feature meets measurable outcomes defined in Success Criteria
|
||||
- [x] No implementation details leak into specification
|
||||
|
||||
## Notes
|
||||
|
||||
- Validated against the existing findings workflow, ownership, inbox, intake, and alerts foundations.
|
||||
- No clarification markers remain.
|
||||
@ -0,0 +1,349 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: Findings Notifications & Escalation Surface Contract
|
||||
version: 1.0.0
|
||||
summary: Logical internal contract for Spec 224 delivery, alert-rule exposure, and finding deep links.
|
||||
description: |
|
||||
This contract documents the structured payloads and UI-facing surfaces that Spec 224 must satisfy.
|
||||
It is intentionally logical rather than public-API only: the feature reuses existing Filament resources,
|
||||
database notifications, and background jobs instead of introducing a new public controller namespace.
|
||||
servers:
|
||||
- url: https://logical.internal
|
||||
description: Non-routable placeholder used to describe internal repository contracts.
|
||||
paths:
|
||||
/internal/findings/notification-events:
|
||||
post:
|
||||
summary: Dispatch one finding event to direct personal delivery and optional external alert copies.
|
||||
description: |
|
||||
Logical internal contract implemented by the bounded finding-notification delivery seam.
|
||||
It normalizes one finding event, resolves at most one entitled direct recipient, writes one
|
||||
Filament-compatible database notification when appropriate, and forwards the same event to the
|
||||
existing workspace alert dispatch pipeline.
|
||||
operationId: dispatchFindingNotificationEvent
|
||||
x-not-public-http: true
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/vnd.tenantpilot.finding-notification-event+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingNotificationEventDispatch'
|
||||
responses:
|
||||
'202':
|
||||
description: Event accepted and evaluated for direct and optional external delivery.
|
||||
content:
|
||||
application/vnd.tenantpilot.finding-notification-dispatch-result+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingNotificationDispatchResult'
|
||||
/admin/alert-rules:
|
||||
get:
|
||||
summary: Existing alert-rule surfaces expose the four new finding event types.
|
||||
description: |
|
||||
Existing Filament resource pages continue to render HTML, while this logical media type documents
|
||||
the event-type options that must appear in create, edit, and filter flows.
|
||||
operationId: viewFindingAlertRuleOptions
|
||||
responses:
|
||||
'200':
|
||||
description: Alert-rule surfaces show the finding event options and reuse the existing delivery families.
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
application/vnd.tenantpilot.finding-alert-rule-options+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingAlertRuleOptionsSurface'
|
||||
'403':
|
||||
description: Workspace operator lacks permission to view alert-rule configuration.
|
||||
'404':
|
||||
description: Workspace operator is not a member of the active workspace or the alert surface is outside their visible scope.
|
||||
/admin/alert-deliveries:
|
||||
get:
|
||||
summary: Existing alert-delivery history can filter and label finding event copies.
|
||||
operationId: viewFindingAlertDeliveries
|
||||
parameters:
|
||||
- name: event_type
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
responses:
|
||||
'200':
|
||||
description: Alert-delivery viewer surfaces show finding-event labels and safe summaries.
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
application/vnd.tenantpilot.finding-alert-deliveries+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingAlertDeliveriesSurface'
|
||||
'403':
|
||||
description: Workspace operator lacks permission to inspect alert deliveries.
|
||||
'404':
|
||||
description: Workspace operator is not a member of the active workspace or the alert-delivery surface is outside their visible scope.
|
||||
/admin/t/{tenant}/findings/{finding}:
|
||||
get:
|
||||
summary: The direct notification action opens the existing tenant finding detail route.
|
||||
operationId: openFindingFromNotification
|
||||
parameters:
|
||||
- name: tenant
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
- name: finding
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
'200':
|
||||
description: Existing finding detail renders for an entitled tenant operator.
|
||||
content:
|
||||
text/html:
|
||||
schema:
|
||||
type: string
|
||||
application/vnd.tenantpilot.finding-notification-context+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/FindingNotificationContext'
|
||||
'403':
|
||||
description: Recipient still has tenant visibility but lacks current capability to inspect the finding.
|
||||
'404':
|
||||
description: Recipient no longer has tenant or record visibility.
|
||||
components:
|
||||
schemas:
|
||||
FindingEventType:
|
||||
type: string
|
||||
enum:
|
||||
- findings.assigned
|
||||
- findings.reopened
|
||||
- findings.due_soon
|
||||
- findings.overdue
|
||||
FindingSeverity:
|
||||
type: string
|
||||
enum:
|
||||
- low
|
||||
- medium
|
||||
- high
|
||||
- critical
|
||||
RecipientReason:
|
||||
type: string
|
||||
enum:
|
||||
- new_assignee
|
||||
- current_assignee
|
||||
- current_owner
|
||||
DirectRecipient:
|
||||
type: object
|
||||
required:
|
||||
- userId
|
||||
- reason
|
||||
properties:
|
||||
userId:
|
||||
type: integer
|
||||
displayName:
|
||||
type: string
|
||||
reason:
|
||||
$ref: '#/components/schemas/RecipientReason'
|
||||
FindingNotificationEventDispatch:
|
||||
type: object
|
||||
required:
|
||||
- eventType
|
||||
- workspaceId
|
||||
- tenantId
|
||||
- findingId
|
||||
- severity
|
||||
- title
|
||||
- body
|
||||
- fingerprintKey
|
||||
- metadata
|
||||
properties:
|
||||
eventType:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
workspaceId:
|
||||
type: integer
|
||||
tenantId:
|
||||
type: integer
|
||||
findingId:
|
||||
type: integer
|
||||
severity:
|
||||
$ref: '#/components/schemas/FindingSeverity'
|
||||
title:
|
||||
type: string
|
||||
body:
|
||||
type: string
|
||||
directRecipient:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/DirectRecipient'
|
||||
- type: 'null'
|
||||
fingerprintKey:
|
||||
type: string
|
||||
dueCycleKey:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
metadata:
|
||||
type: object
|
||||
required:
|
||||
- tenantName
|
||||
- recipientReason
|
||||
properties:
|
||||
tenantName:
|
||||
type: string
|
||||
recipientReason:
|
||||
$ref: '#/components/schemas/RecipientReason'
|
||||
ownerUserId:
|
||||
type:
|
||||
- integer
|
||||
- 'null'
|
||||
assigneeUserId:
|
||||
type:
|
||||
- integer
|
||||
- 'null'
|
||||
dueAt:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
format: date-time
|
||||
reopenedAt:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
format: date-time
|
||||
summary:
|
||||
type: string
|
||||
allOf:
|
||||
- if:
|
||||
properties:
|
||||
eventType:
|
||||
enum:
|
||||
- findings.due_soon
|
||||
- findings.overdue
|
||||
then:
|
||||
required:
|
||||
- dueCycleKey
|
||||
properties:
|
||||
dueCycleKey:
|
||||
type: string
|
||||
- if:
|
||||
properties:
|
||||
eventType:
|
||||
enum:
|
||||
- findings.assigned
|
||||
- findings.reopened
|
||||
then:
|
||||
properties:
|
||||
dueCycleKey:
|
||||
type: 'null'
|
||||
FindingNotificationDispatchResult:
|
||||
type: object
|
||||
required:
|
||||
- eventType
|
||||
- fingerprintKey
|
||||
- directDeliveryStatus
|
||||
- externalDeliveryCount
|
||||
properties:
|
||||
eventType:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
fingerprintKey:
|
||||
type: string
|
||||
directDeliveryStatus:
|
||||
type: string
|
||||
enum:
|
||||
- sent
|
||||
- suppressed
|
||||
- deduped
|
||||
- no_recipient
|
||||
externalDeliveryCount:
|
||||
type: integer
|
||||
minimum: 0
|
||||
externalDeliveryStatuses:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
enum:
|
||||
- queued
|
||||
- deferred
|
||||
- suppressed
|
||||
- none
|
||||
EventTypeOption:
|
||||
type: object
|
||||
required:
|
||||
- value
|
||||
- label
|
||||
properties:
|
||||
value:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
label:
|
||||
type: string
|
||||
FindingAlertRuleOptionsSurface:
|
||||
type: object
|
||||
required:
|
||||
- eventTypes
|
||||
- existingDeliveryFamiliesReused
|
||||
properties:
|
||||
eventTypes:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/EventTypeOption'
|
||||
existingDeliveryFamiliesReused:
|
||||
type: boolean
|
||||
notes:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
FindingAlertDeliveryRow:
|
||||
type: object
|
||||
required:
|
||||
- deliveryId
|
||||
- eventType
|
||||
- label
|
||||
- status
|
||||
properties:
|
||||
deliveryId:
|
||||
type: integer
|
||||
eventType:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
label:
|
||||
type: string
|
||||
tenantId:
|
||||
type:
|
||||
- integer
|
||||
- 'null'
|
||||
status:
|
||||
type: string
|
||||
destinationName:
|
||||
type: string
|
||||
summary:
|
||||
type: string
|
||||
FindingAlertDeliveriesSurface:
|
||||
type: object
|
||||
required:
|
||||
- filterEventTypes
|
||||
- rows
|
||||
properties:
|
||||
filterEventTypes:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/EventTypeOption'
|
||||
rows:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/FindingAlertDeliveryRow'
|
||||
FindingNotificationContext:
|
||||
type: object
|
||||
required:
|
||||
- findingId
|
||||
- tenantId
|
||||
- eventType
|
||||
- recipientReason
|
||||
properties:
|
||||
findingId:
|
||||
type: integer
|
||||
tenantId:
|
||||
type: integer
|
||||
eventType:
|
||||
$ref: '#/components/schemas/FindingEventType'
|
||||
recipientReason:
|
||||
$ref: '#/components/schemas/RecipientReason'
|
||||
title:
|
||||
type: string
|
||||
body:
|
||||
type: string
|
||||
204
specs/224-findings-notifications-escalation/data-model.md
Normal file
204
specs/224-findings-notifications-escalation/data-model.md
Normal file
@ -0,0 +1,204 @@
|
||||
# Data Model: Findings Notifications & Escalation v1
|
||||
|
||||
## Overview
|
||||
|
||||
This feature introduces no new persisted business entity. Existing finding truth, alert rules, alert deliveries, database notifications, and tenant-membership or capability truth remain canonical. The new work is a bounded derived-event layer over those existing records.
|
||||
|
||||
## Existing Persistent Entities
|
||||
|
||||
### Finding
|
||||
|
||||
**Purpose**: Canonical tenant-scoped finding truth for ownership, lifecycle, severity, and due-date evaluation.
|
||||
|
||||
**Key fields used by this feature**:
|
||||
|
||||
- `id`
|
||||
- `workspace_id`
|
||||
- `tenant_id`
|
||||
- `severity`
|
||||
- `status`
|
||||
- `due_at`
|
||||
- `sla_days`
|
||||
- `owner_user_id`
|
||||
- `assignee_user_id`
|
||||
- `reopened_at`
|
||||
- `resolved_at`
|
||||
- `closed_at`
|
||||
- `finding_type`
|
||||
- `subject_type`
|
||||
- `subject_external_id`
|
||||
|
||||
**Relationships**:
|
||||
|
||||
- belongs to one tenant
|
||||
- belongs to one workspace through tenant ownership
|
||||
- may reference one current owner user
|
||||
- may reference one current assignee user
|
||||
|
||||
**Rules relevant to notifications**:
|
||||
|
||||
- Only open findings participate in assignment, due-soon, and overdue notification evaluation.
|
||||
- Terminal findings suppress due-soon and overdue delivery even if they previously entered a reminder window.
|
||||
- The current due cycle is keyed by `due_at`; `reopened_at` remains explanatory lifecycle context and only matters when the existing lifecycle recalculates `due_at`. No extra reminder-state field is added.
|
||||
- Existing aggregate `sla_due` alerts remain separate and are not replaced by finding-level delivery.
|
||||
|
||||
### AlertRule
|
||||
|
||||
**Purpose**: Workspace-scoped configuration for optional external delivery copies.
|
||||
|
||||
**Key fields used by this feature**:
|
||||
|
||||
- `workspace_id`
|
||||
- `event_type`
|
||||
- `min_severity`
|
||||
- `destination_ids`
|
||||
- `cooldown_minutes`
|
||||
- `quiet_hours`
|
||||
- `enabled`
|
||||
|
||||
**Rules relevant to notifications**:
|
||||
|
||||
- The feature adds four new `event_type` values only.
|
||||
- A direct personal notification does not depend on an alert rule.
|
||||
- External copies still require an enabled matching rule and destination.
|
||||
|
||||
### AlertDelivery
|
||||
|
||||
**Purpose**: Existing persisted artifact for external-copy dispatch outcomes.
|
||||
|
||||
**Key fields used by this feature**:
|
||||
|
||||
- `workspace_id`
|
||||
- `tenant_id`
|
||||
- `event_type`
|
||||
- `status`
|
||||
- `destination_snapshot`
|
||||
- `payload`
|
||||
- `fingerprint`
|
||||
- `suppressed_reason`
|
||||
|
||||
**Rules relevant to notifications**:
|
||||
|
||||
- Finding-level external copies reuse the same delivery pipeline, cooldown, suppression, and quiet-hours semantics as other alerts.
|
||||
- Delivery-history viewing remains read-only and only gains the new event labels and safe summaries.
|
||||
|
||||
### Database Notification (`notifications` table)
|
||||
|
||||
**Purpose**: Existing persisted artifact for direct in-app notification delivery.
|
||||
|
||||
**Key fields used by this feature**:
|
||||
|
||||
- `id`
|
||||
- `type`
|
||||
- `notifiable_type`
|
||||
- `notifiable_id`
|
||||
- `data`
|
||||
- `read_at`
|
||||
- `created_at`
|
||||
|
||||
**Rules relevant to notifications**:
|
||||
|
||||
- The feature stores direct-delivery metadata and the deterministic `fingerprint_key` inside `data`; no new table is introduced.
|
||||
- The persisted payload remains Filament-compatible so the existing notification drawer can render it unchanged.
|
||||
|
||||
### Tenant Membership and User Entitlement Context
|
||||
|
||||
**Purpose**: Current authorization truth for whether a resolved direct recipient may still inspect the tenant and finding at send time.
|
||||
|
||||
**Key inputs used by this feature**:
|
||||
|
||||
- `tenant_memberships.tenant_id`
|
||||
- `tenant_memberships.user_id`
|
||||
- `User::canAccessTenant($tenant)`
|
||||
- `CapabilityResolver::can($user, $tenant, Capabilities::TENANT_FINDINGS_VIEW)` or the existing findings-view equivalent used by the implementation seam
|
||||
|
||||
**Rules relevant to notifications**:
|
||||
|
||||
- Direct delivery is suppressed when the resolved recipient is no longer entitled.
|
||||
- Open-time route authorization remains authoritative even after send-time validation.
|
||||
|
||||
## Derived Models
|
||||
|
||||
### FindingNotificationEvent
|
||||
|
||||
**Purpose**: Canonical derived event envelope used by both direct personal delivery and optional external alert copies.
|
||||
|
||||
**Fields**:
|
||||
|
||||
- `event_type`: one of `findings.assigned`, `findings.reopened`, `findings.due_soon`, `findings.overdue`
|
||||
- `workspace_id`
|
||||
- `tenant_id`
|
||||
- `finding_id`
|
||||
- `severity`
|
||||
- `title`
|
||||
- `body`
|
||||
- `recipient_reason`: one of `new_assignee`, `current_assignee`, `current_owner`
|
||||
- `resolved_recipient_user_id`: nullable
|
||||
- `fingerprint_key`
|
||||
- `due_cycle_key`: nullable, derived from current `due_at`
|
||||
- `metadata`: object with finding summary, owner and assignee ids, due date, reopen timestamp, and deep-link-safe context
|
||||
|
||||
**Validation rules**:
|
||||
|
||||
- Event type must be one of the four new finding events.
|
||||
- `recipient_reason` must match the event-specific precedence rule.
|
||||
- `fingerprint_key` must deterministically distinguish the specific assignment change, reopen occurrence, or due cycle.
|
||||
- `due_cycle_key` is required for `findings.due_soon` and `findings.overdue`, and omitted or null for assignment and reopen.
|
||||
|
||||
### RecipientResolutionResult
|
||||
|
||||
**Purpose**: Bounded contract that picks at most one direct recipient from existing owner and assignee truth without creating a second ownership model.
|
||||
|
||||
**Fields**:
|
||||
|
||||
- `user_id`: nullable
|
||||
- `reason`: one of `new_assignee`, `current_assignee`, `current_owner`
|
||||
- `is_entitled`: boolean
|
||||
- `suppression_reason`: nullable string
|
||||
|
||||
**Rules**:
|
||||
|
||||
- `findings.assigned` resolves to the new assignee only.
|
||||
- `findings.reopened` resolves to current assignee, else current owner.
|
||||
- `findings.due_soon` resolves to current assignee, else current owner.
|
||||
- `findings.overdue` resolves to current owner, else current assignee.
|
||||
- A recipient who is not currently entitled becomes a suppression result, not a broadened-delivery fallback.
|
||||
|
||||
### DirectFindingNotificationMessage
|
||||
|
||||
**Purpose**: Filament database-notification payload rendered in the existing notification drawer.
|
||||
|
||||
**Fields**:
|
||||
|
||||
- `format = filament`
|
||||
- `title`
|
||||
- `body`
|
||||
- `actions[0].label = Open finding`
|
||||
- `actions[0].url = /admin/t/{tenant}/findings/{finding}`
|
||||
- `finding_event.event_type`
|
||||
- `finding_event.recipient_reason`
|
||||
- `finding_event.fingerprint_key`
|
||||
- `finding_event.tenant_name`
|
||||
- `finding_event.severity`
|
||||
|
||||
**Rules**:
|
||||
|
||||
- One notification row represents one direct delivery to one entitled user.
|
||||
- The payload must explain why the operator received the notification.
|
||||
- The payload must not include hidden-tenant data beyond what the recipient is entitled to inspect.
|
||||
|
||||
## Event Matrix
|
||||
|
||||
| Event type | Trigger | Recipient precedence | Fingerprint components | Suppression rules |
|
||||
|------------|---------|----------------------|------------------------|-------------------|
|
||||
| `findings.assigned` | An open finding is assigned to a new assignee | new assignee | finding id + target assignee id + assignment change marker | suppress for owner-only changes, assignee clears, no-op saves, terminal findings, or non-entitled recipient |
|
||||
| `findings.reopened` | A terminal finding is reopened by system detection | current assignee, else current owner | finding id + reopened occurrence marker | suppress for manual reopen, missing recipient, or non-entitled recipient |
|
||||
| `findings.due_soon` | An open finding first enters the 24-hour pre-due window for the current due cycle | current assignee, else current owner | finding id + current `due_at` + event type | suppress for terminal findings, missing `due_at`, no entitled recipient, or duplicate within the same due cycle |
|
||||
| `findings.overdue` | An open finding first becomes overdue for the current due cycle | current owner, else current assignee | finding id + current `due_at` + event type | suppress for terminal findings, no entitled recipient, or duplicate within the same due cycle |
|
||||
|
||||
## Persistence Boundaries
|
||||
|
||||
- No new table, enum-backed persistence, or reminder-state model is introduced.
|
||||
- `notifications.data` stores direct-delivery fingerprint metadata only as a delivery artifact.
|
||||
- `alert_deliveries` stores external-copy artifacts only as it already does today.
|
||||
- `Finding` remains the sole business-truth model for ownership, lifecycle, and due-cycle resets.
|
||||
253
specs/224-findings-notifications-escalation/plan.md
Normal file
253
specs/224-findings-notifications-escalation/plan.md
Normal file
@ -0,0 +1,253 @@
|
||||
# Implementation Plan: Findings Notifications & Escalation v1
|
||||
|
||||
**Branch**: `224-findings-notifications-escalation` | **Date**: 2026-04-22 | **Spec**: `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/224-findings-notifications-escalation/spec.md`
|
||||
**Input**: Feature specification from `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/224-findings-notifications-escalation/spec.md`
|
||||
|
||||
**Note**: This plan keeps the work inside the existing findings workflow, workspace alerting, and Filament database-notification primitives. The intended implementation adds four finding event types, one narrow finding-notification service, one database notification class, and focused extensions to the existing alert evaluation and alert-management surfaces. It does not add a new table, a notification center, a preference system, a second findings queue, or a generic workflow engine.
|
||||
|
||||
## Summary
|
||||
|
||||
Extend the existing workspace Alerts event vocabulary with `findings.assigned`, `findings.reopened`, `findings.due_soon`, and `findings.overdue`, then add a narrow `FindingNotificationService` that sends one entitlement-safe direct database notification to the currently responsible operator and forwards the same event into `AlertDispatchService` for optional external copies. Emit assignment and system-reopen events from `FindingWorkflowService` after committed mutations, evaluate due-soon and overdue windows inside the existing `EvaluateAlertsJob` cadence, reuse the existing `notifications` table and Filament database-notification drawer for direct delivery, and keep finding follow-up on the existing tenant finding detail route.
|
||||
|
||||
## Technical Context
|
||||
|
||||
**Language/Version**: PHP 8.4.15, Laravel 12, Filament v5, Livewire v4, Blade
|
||||
**Primary Dependencies**: Laravel notifications (`database` channel), Filament database notifications, `Finding`, `FindingWorkflowService`, `FindingSlaPolicy`, `AlertRule`, `AlertDelivery`, `AlertDispatchService`, `EvaluateAlertsJob`, `CapabilityResolver`, `WorkspaceContext`, `TenantMembership`, `FindingResource`
|
||||
**Storage**: PostgreSQL via existing `findings`, `alert_rules`, `alert_deliveries`, `notifications`, `tenant_memberships`, and `audit_logs`; no schema changes planned
|
||||
**Testing**: Pest v4 feature tests with Filament/Livewire assertions and notification-payload checks
|
||||
**Validation Lanes**: fast-feedback, confidence
|
||||
**Target Platform**: Dockerized Laravel web application via Sail locally and Linux containers in deployment
|
||||
**Project Type**: Laravel monolith inside the `wt-plattform` monorepo
|
||||
**Performance Goals**: Keep direct notification dispatch and external alert-copy generation DB-backed and queue-safe, avoid N+1 tenant or recipient lookups, and keep due-window scans bounded to workspace-scoped open findings with due-date indexes already present
|
||||
**Constraints**: No new persisted notification-truth table, no notification-preference center, no new capability family, no hidden-tenant leakage, no manual-reopen notification in v1, no repeated overdue spam within the same due cycle, and no new frontend assets
|
||||
**Scale/Scope**: Four new event types, one narrow finding-notification service, one new database notification class, extensions to two existing alert resources, one extension to the existing alerts evaluation job, and four focused feature suites
|
||||
|
||||
## UI / Surface Guardrail Plan
|
||||
|
||||
- **Guardrail scope**: changed surfaces
|
||||
- **Native vs custom classification summary**: native Filament resources and existing database-notification primitives only
|
||||
- **Shared-family relevance**: workspace alert configuration and delivery-history family, existing admin and tenant database-notification family, existing tenant finding detail family
|
||||
- **State layers in scope**: shell, detail
|
||||
- **Handling modes by drift class or surface**: review-mandatory
|
||||
- **Repository-signal treatment**: review-mandatory
|
||||
- **Special surface test profiles**: standard-native-filament, global-context-shell
|
||||
- **Required tests or manual smoke**: functional-core, state-contract
|
||||
- **Exception path and spread control**: none; the feature extends existing alert resources and notification primitives rather than creating a new page family
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
|
||||
## Constitution Check
|
||||
|
||||
*GATE: Passed before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
| Principle | Pre-Research | Post-Design | Notes |
|
||||
|-----------|--------------|-------------|-------|
|
||||
| Inventory-first / snapshots-second | PASS | PASS | All event production stays derived from existing `Finding` lifecycle, ownership, severity, and due-date truth; notifications and alert deliveries remain delivery artifacts only |
|
||||
| Read/write separation | PASS | PASS | The feature adds no new operator mutation surface; assignment and reopen writes stay inside existing workflow actions, while due reminders remain scheduled evaluation side effects |
|
||||
| Graph contract path | PASS | PASS | No Microsoft Graph call paths or contract-registry changes are introduced |
|
||||
| Deterministic capabilities / RBAC-UX | PASS | PASS | Workspace-scoped alert configuration remains capability-gated, direct recipients are re-validated against current tenant membership plus findings-view capability at send time, non-members remain `404`, and in-scope capability failures remain `403` |
|
||||
| Workspace / tenant isolation | PASS | PASS | Alert rules and alert deliveries stay workspace-scoped, while direct notifications always deep-link to tenant-scoped finding detail and must not expose hidden tenant data |
|
||||
| Run observability / Ops-UX | PASS | PASS | Scheduled due-event evaluation stays inside the existing `alerts.evaluate` cadence; no `OperationRun` notification semantics are changed and no queued/running DB notifications are introduced |
|
||||
| Proportionality / no premature abstraction | PASS | PASS | The plan allows one narrow `FindingNotificationService` because direct-recipient resolution, dedupe, payload composition, and external alert-copy forwarding would otherwise be duplicated across workflow mutations and scheduled due evaluation |
|
||||
| Persisted truth / few layers | PASS | PASS | No new table or persisted workflow state is added; existing `notifications` JSONB and `alert_deliveries` rows remain the only delivery artifacts |
|
||||
| Behavioral state discipline | PASS | PASS | The four new values are delivery event types, not a new finding lifecycle or responsibility taxonomy |
|
||||
| Filament-native UI (UI-FIL-001) | PASS | PASS | Alert rules and alert deliveries remain native Filament resources; direct notifications use existing Filament database-notification payloads |
|
||||
| Decision-first / action-surface contract | PASS | PASS | Notifications stay as secondary drill-in entry points, alert rules remain config-first, and alert deliveries remain read-only diagnostics |
|
||||
| Test governance (TEST-GOV-001) | PASS | PASS | Proof stays in focused feature suites for event production, routing, alert-rule integration, and deep-link safety, with no browser or heavy-governance expansion |
|
||||
| Filament v5 / Livewire v4 compliance | PASS | PASS | The feature uses existing Filament v5 resources and Livewire v4-compatible database notifications only |
|
||||
| Provider registration / global search / assets | PASS | PASS | Panel providers already live in `apps/platform/bootstrap/providers.php`; no globally searchable resource is added or changed; no new assets are required, so the existing deploy `filament:assets` step remains unchanged |
|
||||
|
||||
## Test Governance Check
|
||||
|
||||
- **Test purpose / classification by changed surface**: `Feature` for finding-event production, direct-recipient routing, alert-rule UI integration, and deep-link authorization behavior
|
||||
- **Affected validation lanes**: `fast-feedback`, `confidence`
|
||||
- **Why this lane mix is the narrowest sufficient proof**: The main risk is integrated workflow behavior: which event fires, who gets it, whether direct delivery leaks scope, whether external copies remain optional, and whether alert-management surfaces expose the new event types coherently. Focused feature tests prove that without adding unit-only abstractions or browser cost.
|
||||
- **Narrowest proving command(s)**:
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsNotificationEventTest.php tests/Feature/Findings/FindingsNotificationRoutingTest.php`
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php tests/Feature/Alerts/SlaDueAlertTest.php tests/Feature/Notifications/FindingNotificationLinkTest.php`
|
||||
- **Fixture / helper / factory / seed / context cost risks**: Moderate. Tests need workspace and tenant context, current and removed memberships, owner-versus-assignee combinations, existing alert rules and destinations, notification-table assertions, and time-travel across due windows.
|
||||
- **Expensive defaults or shared helper growth introduced?**: no; any notification-specific helper should stay local to the new tests and reuse existing `createUserWithTenant(...)`, `Finding::factory()`, and alert destination factories
|
||||
- **Heavy-family additions, promotions, or visibility changes**: none
|
||||
- **Surface-class relief / special coverage rule**: `standard-native-filament` for alert resources and `global-context-shell` for database notifications that bridge admin shell context to tenant finding detail
|
||||
- **Closing validation and reviewer handoff**: Reviewers should rely on the exact commands above and verify that owner-only changes do not emit assignment notifications, manual reopen still emits nothing, due-soon and overdue stay one-per-due-cycle, same-user owner/assignee resolution creates one notification, direct delivery suppresses when entitlement is lost, and external alert copies only appear when a matching alert rule exists.
|
||||
- **Budget / baseline / trend follow-up**: none
|
||||
- **Review-stop questions**: Did the implementation introduce new persistence, a preference layer, or a generic workflow-notification engine? Did any path leak hidden tenant information in the notification title, body, or action URL? Did due evaluation widen beyond the existing alert-evaluation cadence without need? Did alert-rule resource changes stay native and read clearly?
|
||||
- **Escalation path**: document-in-feature unless a second delivery abstraction, a preference center, or a new findings-specific notification surface is proposed, in which case split or follow up with a dedicated spec
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
- **Why no dedicated follow-up spec is needed**: This feature remains bounded to four concrete event types and one direct-delivery contract built on existing infrastructure
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/224-findings-notifications-escalation/
|
||||
├── plan.md
|
||||
├── research.md
|
||||
├── data-model.md
|
||||
├── quickstart.md
|
||||
├── contracts/
|
||||
│ └── findings-notifications-escalation.logical.openapi.yaml
|
||||
├── checklists/
|
||||
│ └── requirements.md
|
||||
└── tasks.md
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
|
||||
```text
|
||||
apps/platform/
|
||||
├── app/
|
||||
│ ├── Filament/
|
||||
│ │ └── Resources/
|
||||
│ │ ├── AlertDeliveryResource.php
|
||||
│ │ └── AlertRuleResource.php
|
||||
│ ├── Jobs/
|
||||
│ │ └── Alerts/
|
||||
│ │ └── EvaluateAlertsJob.php
|
||||
│ ├── Models/
|
||||
│ │ └── AlertRule.php
|
||||
│ ├── Notifications/
|
||||
│ │ └── Findings/
|
||||
│ │ └── FindingEventNotification.php
|
||||
│ └── Services/
|
||||
│ ├── Alerts/
|
||||
│ │ └── AlertDispatchService.php
|
||||
│ └── Findings/
|
||||
│ ├── FindingNotificationService.php
|
||||
│ ├── FindingSlaPolicy.php
|
||||
│ └── FindingWorkflowService.php
|
||||
├── database/
|
||||
│ └── factories/
|
||||
│ └── FindingFactory.php
|
||||
└── tests/
|
||||
└── Feature/
|
||||
├── Alerts/
|
||||
│ └── FindingsAlertRuleIntegrationTest.php
|
||||
├── Findings/
|
||||
│ ├── FindingsNotificationEventTest.php
|
||||
│ └── FindingsNotificationRoutingTest.php
|
||||
└── Notifications/
|
||||
└── FindingNotificationLinkTest.php
|
||||
```
|
||||
|
||||
**Structure Decision**: Standard Laravel monolith. The feature stays inside existing finding workflow, alerting, and notification seams. No new base directory, panel, or persisted model is required.
|
||||
|
||||
## Complexity Tracking
|
||||
|
||||
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||||
|-----------|------------|-------------------------------------|
|
||||
| none | — | — |
|
||||
|
||||
## Proportionality Review
|
||||
|
||||
- **Current operator problem**: Finding assignment, automatic reopen, and due-state changes remain silent unless operators keep polling findings pages.
|
||||
- **Existing structure is insufficient because**: `FindingWorkflowService` knows about ownership changes but not delivery, `EvaluateAlertsJob` knows about workspace alert events but not direct responsible-user delivery, and the existing alert-rule UI cannot express these finding-specific workflow events yet.
|
||||
- **Narrowest correct implementation**: Add four event types, extend the existing alert-rule and delivery viewer labels, create one narrow `FindingNotificationService` to unify recipient resolution plus direct and external delivery, and emit events only from existing workflow and alert-evaluation seams.
|
||||
- **Ownership cost created**: One service, one notification class, incremental logic in `FindingWorkflowService` and `EvaluateAlertsJob`, and four focused feature suites.
|
||||
- **Alternative intentionally rejected**: A new `FindingNotificationDelivery` table or generic workflow-notification engine. Both add persistence or framework complexity that current-release truth does not require because existing `notifications` and `alert_deliveries` already capture delivery artifacts.
|
||||
- **Release truth**: Current-release truth. The feature closes an existing workflow loop now rather than preparing a later escalation framework.
|
||||
|
||||
## Phase 0 Research
|
||||
|
||||
Research outcomes are captured in `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/224-findings-notifications-escalation/research.md`.
|
||||
|
||||
Key decisions:
|
||||
|
||||
- Add the four new finding event types to the existing `AlertRule` constant registry and `AlertRuleResource::eventTypeOptions()` instead of creating a second event catalog.
|
||||
- Reuse existing Filament database notifications on the admin panel rather than building a findings-specific notification surface or page.
|
||||
- Emit `findings.assigned` and `findings.reopened` from `FindingWorkflowService` after the write transaction commits so delivery does not race an uncommitted finding state.
|
||||
- Evaluate `findings.due_soon` and `findings.overdue` inside the existing `EvaluateAlertsJob` workspace cadence rather than adding a second scheduler, command, or `OperationRun` family.
|
||||
- Use the existing `notifications` table `data` payload to store a finding-event fingerprint for direct-delivery dedupe; do not add a new persistence model.
|
||||
- Reuse `FindingResource::getUrl(..., panel: 'tenant', tenant: $tenant)` for notification deep links and re-check entitlement before sending any direct notification.
|
||||
|
||||
## Phase 1 Design
|
||||
|
||||
Design artifacts are created under `/Users/ahmeddarrazi/Documents/projects/wt-plattform/specs/224-findings-notifications-escalation/`:
|
||||
|
||||
- `research.md`: event-registry, delivery, dedupe, and evaluation-seam decisions
|
||||
- `data-model.md`: existing entities plus the derived finding-event and direct-notification payload models
|
||||
- `contracts/findings-notifications-escalation.logical.openapi.yaml`: internal logical contract for finding-event dispatch, alert-rule event exposure, alert-delivery viewing, and finding deep-link payloads
|
||||
- `quickstart.md`: focused validation workflow for implementation and review
|
||||
|
||||
Design decisions:
|
||||
|
||||
- No schema migration is required; direct notifications use the existing `notifications` table and external copies use existing `alert_deliveries` rows.
|
||||
- The canonical new seam is one narrow `FindingNotificationService`, not a reusable workflow-notification framework.
|
||||
- Direct-recipient dedupe uses a fingerprint stored in the existing database notification payload; due-cycle reset keys are derived from the current `due_at` value.
|
||||
- Alert rules remain optional for external copies; direct responsible-user notifications do not depend on any matching alert rule.
|
||||
- Existing tenant finding detail remains the only follow-up surface, and current `404` versus `403` route behavior remains authoritative at open time.
|
||||
|
||||
## Phase 1 Agent Context Update
|
||||
|
||||
Run:
|
||||
|
||||
- `.specify/scripts/bash/update-agent-context.sh copilot`
|
||||
|
||||
## Constitution Check — Post-Design Re-evaluation
|
||||
|
||||
- PASS — the design remains inside current findings, alerts, and database-notification seams with no new persistence, no Graph work, no new capability family, and no new frontend assets.
|
||||
- PASS — Livewire v4.0+ and Filament v5 constraints remain satisfied, panel provider registration stays in `apps/platform/bootstrap/providers.php`, no globally searchable resource behavior changes, and no new destructive action path is introduced.
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### Phase A — Extend the existing alert-event vocabulary and operator labels
|
||||
|
||||
**Goal**: Teach existing alert-management surfaces about the four new finding workflow events.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| A.1 | `apps/platform/app/Models/AlertRule.php` | Add the four new `EVENT_FINDINGS_*` constants alongside the existing alert event types |
|
||||
| A.2 | `apps/platform/app/Filament/Resources/AlertRuleResource.php` | Extend `eventTypeOptions()` and `eventTypeLabel()` with operator-facing labels for assignment, reopened, due soon, and overdue events |
|
||||
| A.3 | `apps/platform/app/Filament/Resources/AlertDeliveryResource.php` | Ensure list, view, and filter surfaces continue to render the new event labels cleanly through the existing event-type label seam without adding a new delivery viewer |
|
||||
|
||||
### Phase B — Add one narrow finding-notification delivery seam on existing primitives
|
||||
|
||||
**Goal**: Send one entitlement-safe direct database notification and one optional external alert copy from the same event envelope.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| B.1 | `apps/platform/app/Services/Findings/FindingNotificationService.php` | Add a focused service that builds finding-event payloads, resolves the direct recipient by the spec precedence rules, checks current tenant entitlement plus findings-view capability, computes a delivery fingerprint, suppresses duplicates by querying existing database notifications, and forwards the same event array to `AlertDispatchService` for external copies |
|
||||
| B.2 | `apps/platform/app/Notifications/Findings/FindingEventNotification.php` | Add a database notification class that returns Filament notification payloads with tenant-safe title/body copy, recipient-reason copy, one finding-detail action URL, and embedded metadata including the event type and fingerprint |
|
||||
| B.3 | `apps/platform/app/Services/Alerts/AlertDispatchService.php` | Keep the existing workspace alert-copy path intact and only absorb any payload-shape normalization needed for the new finding event titles, body copy, and metadata |
|
||||
|
||||
### Phase C — Emit assignment and automatic-reopen notifications from existing finding workflow mutations
|
||||
|
||||
**Goal**: Turn current write seams into finding-event producers without changing workflow truth.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| C.1 | `apps/platform/app/Services/Findings/FindingWorkflowService.php` | After committed `assign(...)` mutations, compare before and after owner and assignee state, suppress no-op, owner-only, and assignee-clear transitions, and dispatch `findings.assigned` only when a new assignee is set on an open finding |
|
||||
| C.2 | `apps/platform/app/Services/Findings/FindingWorkflowService.php` | After committed `reopenBySystem(...)` mutations, dispatch `findings.reopened` using the refreshed finding state; keep manual `reopen(...)` out of scope for v1 delivery |
|
||||
| C.3 | `apps/platform/app/Services/Findings/FindingWorkflowService.php` and `apps/platform/database/factories/FindingFactory.php` | Preserve existing due-date reset and reopen semantics so notification due-cycle logic stays derived from the recalculated `due_at` value, with reopen metadata remaining explanatory rather than becoming a second cycle key |
|
||||
|
||||
### Phase D — Evaluate due-soon and overdue events inside the existing alerts evaluation cadence
|
||||
|
||||
**Goal**: Keep scheduled due reminders and escalations inside the already-established workspace alert window.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| D.1 | `apps/platform/app/Jobs/Alerts/EvaluateAlertsJob.php` | Add finding-level due-soon and overdue candidate queries over workspace-scoped open findings with `due_at`, using the existing window semantics and a fixed v1 due-soon horizon of 24 hours |
|
||||
| D.2 | `apps/platform/app/Jobs/Alerts/EvaluateAlertsJob.php` | For each candidate finding event, call `FindingNotificationService` so direct delivery and optional external alert copies stay consistent and no second dispatch pipeline appears |
|
||||
| D.3 | `apps/platform/app/Services/Findings/FindingNotificationService.php` | Define due-cycle fingerprints from the current `due_at` value so due-soon and overdue notifications emit once per cycle and reset only when `due_at` is recalculated by existing lifecycle semantics |
|
||||
|
||||
### Phase E — Preserve tenant-safe deep links and existing notification shell behavior
|
||||
|
||||
**Goal**: Reuse the current notification drawer and finding detail route without widening visibility.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| E.1 | `apps/platform/app/Notifications/Findings/FindingEventNotification.php` | Build finding action URLs with `FindingResource::getUrl('view', ['record' => $finding], panel: 'tenant', tenant: $tenant)` so links target the tenant panel explicitly |
|
||||
| E.2 | Existing admin panel notification configuration | Rely on the already-configured `->databaseNotifications()` behavior in `AdminPanelProvider`; do not add polling, a new page, or a new notification surface |
|
||||
| E.3 | Existing finding detail route behavior | Keep current route authorization authoritative so an operator who lost access after send time still receives the existing `404` or `403` outcome instead of leaked detail |
|
||||
|
||||
### Phase F — Protect event truth, routing, and link safety with focused regression coverage
|
||||
|
||||
**Goal**: Lock down event production, recipient precedence, alert-rule integration, and tenant-safe finding drilldown.
|
||||
|
||||
| Step | File | Change |
|
||||
|------|------|--------|
|
||||
| F.1 | `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php` | Cover assignment-event production, system-reopen event production, rapid reassignment and repeated automatic-reopen dedupe, due-soon and overdue evaluation windows, terminal-finding suppression, and one-per-due-cycle behavior |
|
||||
| F.2 | `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php` | Cover recipient precedence, same-user owner and assignee dedupe, owner-only assignment suppression, entitlement-loss suppression, and no direct delivery without a current eligible recipient |
|
||||
| F.3 | `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php` and `apps/platform/tests/Feature/Alerts/SlaDueAlertTest.php` | Cover alert-rule event-type option exposure, `ALERTS_VIEW` read versus `ALERTS_MANAGE` mutation boundaries, inherited Alerts v1 external-copy behavior including minimum severity, tenant scoping, cooldown, quiet hours, and dedupe, delivery-history labels and filters, the rule-free case where direct personal delivery still occurs, and non-regression of existing aggregate `sla_due` behavior |
|
||||
| F.4 | `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php` | Cover database notification payload shape, explicit tenant-panel URLs, and finding-detail open behavior with correct tenant-safe `404` and `403` semantics |
|
||||
| F.5 | `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent` plus the focused Pest commands above | Run formatting and the narrowest proving suites before closing implementation |
|
||||
106
specs/224-findings-notifications-escalation/quickstart.md
Normal file
106
specs/224-findings-notifications-escalation/quickstart.md
Normal file
@ -0,0 +1,106 @@
|
||||
# Quickstart: Findings Notifications & Escalation v1
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Start the local platform stack.
|
||||
|
||||
```bash
|
||||
cd apps/platform && ./vendor/bin/sail up -d
|
||||
```
|
||||
|
||||
2. Work with a workspace that has at least one tenant, two tenant users, and existing findings data.
|
||||
|
||||
3. Ensure you can create or edit alert rules and inspect alert deliveries in the admin panel.
|
||||
|
||||
4. Remember that Filament database notification polling is intentionally disabled in this repo, so reload the page or reopen the notification drawer after each trigger when validating manually.
|
||||
|
||||
## Automated Validation
|
||||
|
||||
Run formatting and the narrowest proving suites for this feature:
|
||||
|
||||
```bash
|
||||
cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent
|
||||
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsNotificationEventTest.php tests/Feature/Findings/FindingsNotificationRoutingTest.php
|
||||
cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php tests/Feature/Alerts/SlaDueAlertTest.php tests/Feature/Notifications/FindingNotificationLinkTest.php
|
||||
```
|
||||
|
||||
## Manual Validation Flow
|
||||
|
||||
### 1. Confirm alert-rule event types are available
|
||||
|
||||
1. Open the admin panel alert-rule create or edit form.
|
||||
2. Verify the event selector contains:
|
||||
- `Finding assigned`
|
||||
- `Finding reopened`
|
||||
- `Finding due soon`
|
||||
- `Finding overdue`
|
||||
3. Save a rule that targets one of the new event types and confirm the Alert deliveries viewer can filter and label it correctly.
|
||||
|
||||
### 1b. Validate admin alert-surface RBAC semantics
|
||||
|
||||
1. As a workspace member with `ALERTS_VIEW` but without `ALERTS_MANAGE`, confirm the existing alert-rule and alert-delivery read surfaces open successfully while alert-rule mutation stays forbidden.
|
||||
2. As an in-scope workspace member without `ALERTS_VIEW`, confirm the existing alert-rule and alert-delivery view surfaces return `403`.
|
||||
3. As a non-member or wrong-workspace user, confirm the existing alert-rule and alert-delivery surfaces return `404`.
|
||||
|
||||
### 2. Validate direct assignment notification
|
||||
|
||||
1. Start with an open finding that has no assignee or a different assignee.
|
||||
2. Assign the finding to a new entitled operator.
|
||||
3. Reload the shell and open the database notification drawer.
|
||||
4. Confirm the new assignee receives exactly one notification with:
|
||||
- the finding vocabulary
|
||||
- an explanation that the finding was assigned to them
|
||||
- one `Open finding` action
|
||||
5. Confirm owner-only changes, assignee clears, and no-op saves emit no assignment notification.
|
||||
|
||||
### 3. Validate automatic reopen notification
|
||||
|
||||
1. Start with a terminal finding that still has an assignee or owner.
|
||||
2. Trigger the existing system path that reopens the finding through recurring detection.
|
||||
3. Reload the shell and confirm one `Finding reopened` notification reaches the current assignee, or the current owner if no assignee exists.
|
||||
4. Confirm manual reopen remains silent in v1.
|
||||
|
||||
### 4. Validate due-soon and overdue direct delivery
|
||||
|
||||
1. Prepare two open findings:
|
||||
- one with `due_at` inside the next 24 hours
|
||||
- one with `due_at` already in the past
|
||||
2. Run the existing alert-evaluation command for the target workspace.
|
||||
|
||||
```bash
|
||||
cd apps/platform && ./vendor/bin/sail artisan tenantpilot:alerts:dispatch --workspace=<workspace-id>
|
||||
```
|
||||
|
||||
3. Reload the notification drawer.
|
||||
4. Confirm:
|
||||
- due soon goes to the current assignee, else the current owner
|
||||
- overdue goes to the current owner, else the current assignee
|
||||
- if owner and assignee are the same user, only one direct notification is created
|
||||
5. Run the same command again without changing `due_at` or reopening the finding and confirm no duplicate due-soon or overdue direct notification is created for the current cycle.
|
||||
6. Recalculate the due cycle through the existing lifecycle contract, then rerun evaluation and confirm one fresh due notification can emit for the new cycle.
|
||||
|
||||
### 5. Validate optional external copies through existing alert rules
|
||||
|
||||
1. Enable an alert rule for one of the new finding event types with a real destination.
|
||||
2. Trigger the corresponding event again.
|
||||
3. Confirm the direct responsible-user notification still appears.
|
||||
4. Confirm one or more `Alert deliveries` rows are created only when a matching enabled rule exists.
|
||||
5. Confirm the existing tenant-level aggregate `sla_due` alert behavior remains unchanged.
|
||||
|
||||
### 6. Validate entitlement-safe deep links
|
||||
|
||||
1. Create a direct finding notification for an entitled recipient.
|
||||
2. Remove that user’s tenant membership or findings-view capability.
|
||||
3. Open the notification action URL.
|
||||
4. Confirm the existing route behavior remains authoritative:
|
||||
- hidden tenant or record paths stay `404`
|
||||
- in-scope but unauthorized access stays `403`
|
||||
5. Confirm the notification title and body never broaden disclosure beyond the existing finding summary vocabulary.
|
||||
|
||||
## Reviewer Notes
|
||||
|
||||
- The feature is Livewire v4.0+ compatible and stays on existing Filament v5 primitives.
|
||||
- Provider registration remains unchanged in `apps/platform/bootstrap/providers.php`.
|
||||
- No globally searchable resource behavior changes in this feature.
|
||||
- No new destructive action is introduced, so no new confirmation flow is required.
|
||||
- Asset strategy is unchanged: no new panel or shared assets, and the existing deploy `filament:assets` step remains sufficient.
|
||||
69
specs/224-findings-notifications-escalation/research.md
Normal file
69
specs/224-findings-notifications-escalation/research.md
Normal file
@ -0,0 +1,69 @@
|
||||
# Research: Findings Notifications & Escalation v1
|
||||
|
||||
## Decision 1: Reuse the existing alert event registry and alert-rule surfaces
|
||||
|
||||
**Decision**: Add the four finding event constants to `AlertRule` and expose them through `AlertRuleResource::eventTypeOptions()` and `AlertRuleResource::eventTypeLabel()`.
|
||||
|
||||
**Rationale**: Workspace alert rules, destinations, deliveries, cooldowns, quiet hours, and delivery-history viewing already exist and are the approved external-copy path. Extending that registry keeps rule configuration and delivery viewing in one place and avoids a second event catalog.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Create a findings-specific alert configuration surface. Rejected because the spec explicitly requires reuse of the existing alert system and forbids a second preference or notification center.
|
||||
- Pass new event strings ad hoc without updating the central registry. Rejected because alert-rule selectors, delivery filters, and labels would drift immediately.
|
||||
|
||||
## Decision 2: Use existing Filament database notifications for direct personal delivery
|
||||
|
||||
**Decision**: Deliver direct operator notifications through Laravel database notifications with Filament payloads stored in the existing `notifications` table.
|
||||
|
||||
**Rationale**: `AdminPanelProvider` already enables `databaseNotifications()`, and the existing `OperationRunQueued` and `OperationRunCompleted` notification classes show the repository’s established pattern for title, body, and action-link payloads. This satisfies the requirement for in-app personal notifications without creating a new page or asset surface.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Build a custom Livewire inbox or findings-notification page. Rejected because it introduces a second notification surface and broader UI scope than the spec allows.
|
||||
- Deliver only external copies through email or Teams. Rejected because the spec requires direct in-app notifications first and treats external channels as optional copies controlled by alert rules.
|
||||
|
||||
## Decision 3: Emit assignment and automatic-reopen events from `FindingWorkflowService` after commit
|
||||
|
||||
**Decision**: Hook `findings.assigned` and `findings.reopened` at the workflow-service boundary after `mutateAndAudit(...)` returns a refreshed `Finding` record.
|
||||
|
||||
**Rationale**: `FindingWorkflowService` already owns assignment, reopen, due-date reset, authorization, and audit semantics. Emitting after commit avoids dispatching notification side effects for rolled-back writes and keeps event truth attached to the seam that actually changes responsibility or lifecycle.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Emit from controllers, Filament actions, or pages. Rejected because some finding changes are system-driven and those surfaces do not own the canonical mutation truth.
|
||||
- Emit inside the transaction. Rejected because direct or external delivery could start before the write commits.
|
||||
- Notify on manual `reopen(...)` in the same pass. Rejected for v1 because the spec is limited to automatic reopen notification and keeping manual reopen silent reduces scope.
|
||||
|
||||
## Decision 4: Keep due-soon and overdue evaluation inside `EvaluateAlertsJob`
|
||||
|
||||
**Decision**: Extend `EvaluateAlertsJob` with finding due-soon and overdue candidate scans and route each candidate through the finding-notification delivery seam.
|
||||
|
||||
**Rationale**: The job already evaluates workspace-scoped alert events on a scheduled cadence, carries evaluation-window semantics, and runs inside the existing `alerts.evaluate` operational path. Reusing it avoids a second scheduler, command, or run family.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Create a dedicated due-notification job or Artisan command. Rejected because it duplicates scheduling, workspace scoping, and operational observability for no functional gain.
|
||||
- Trigger due reminders from the UI. Rejected because reminder delivery must not depend on an operator visiting a page.
|
||||
|
||||
## Decision 5: Use notification-payload metadata for direct-delivery dedupe
|
||||
|
||||
**Decision**: Store a `fingerprint_key` and event metadata in the existing database notification `data` JSONB payload and query the existing `notifications` table to suppress duplicate direct deliveries.
|
||||
|
||||
**Rationale**: The spec forbids new persistence while still requiring one notification per due cycle and fingerprint-aware delivery semantics. Existing notification rows are already persisted delivery artifacts, so they are the narrowest place to record direct-delivery fingerprints without adding a new table.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Create a new `FindingNotificationDelivery` table. Rejected because it adds persistence and lifecycle ownership that the spec explicitly avoids.
|
||||
- Skip direct dedupe entirely. Rejected because due-soon and overdue would repeat on every scheduled evaluation pass.
|
||||
|
||||
## Decision 6: Reuse tenant finding detail links and current entitlement checks
|
||||
|
||||
**Decision**: Build notification actions against the existing tenant-panel finding detail route and suppress send-time direct delivery if the selected recipient no longer has current tenant membership plus findings-view capability.
|
||||
|
||||
**Rationale**: The spec requires the notification to explain why the user is seeing it and send them to the existing finding detail route while preserving current `404` and `403` semantics. Rechecking entitlement at send time prevents stale assignments or ownership from generating a misleading in-app notification.
|
||||
|
||||
**Alternatives considered**:
|
||||
|
||||
- Link to the My Findings inbox instead of the single finding detail. Rejected because the spec calls for direct follow-up on the existing finding detail and the inbox adds avoidable navigation indirection.
|
||||
- Add a new notification-detail page. Rejected because it duplicates finding detail and creates a second follow-up surface.
|
||||
- Skip send-time entitlement revalidation. Rejected because tenant membership and capability state can change between assignment and delivery.
|
||||
257
specs/224-findings-notifications-escalation/spec.md
Normal file
257
specs/224-findings-notifications-escalation/spec.md
Normal file
@ -0,0 +1,257 @@
|
||||
# Feature Specification: Findings Notifications & Escalation v1
|
||||
|
||||
**Feature Branch**: `224-findings-notifications-escalation`
|
||||
**Created**: 2026-04-22
|
||||
**Status**: Draft
|
||||
**Input**: User description: "Findings Notifications & Escalation v1"
|
||||
|
||||
## Spec Candidate Check *(mandatory — SPEC-GATE-001)*
|
||||
|
||||
- **Problem**: Findings now have clear owner-versus-assignee semantics plus personal and shared work surfaces, but assignment, automatic reopen, and aging transitions still remain silent unless operators keep polling findings pages.
|
||||
- **Today's failure**: A finding can be assigned, auto-reopened, become due soon, or become overdue without the responsible operator noticing in time. Due dates become passive metadata instead of a real control loop.
|
||||
- **User-visible improvement**: Responsible operators receive calm, tenant-safe notifications with one clear deep link when work is assigned, reopens automatically, approaches its due date, or becomes overdue. Workspace teams can optionally add existing external alert copies without building a second findings-specific notification system.
|
||||
- **Smallest enterprise-capable version**: Add four finding event types, one bounded recipient-resolution contract over existing owner and assignee truth, direct personal notifications for actionable finding events, and optional workspace-level external copies through the existing Alerts rules and destinations.
|
||||
- **Explicit non-goals**: No multi-stage escalation chains, no notification-preference center, no comments or chat, no external ticket synchronization, no new owner-only queue, and no generic workflow engine.
|
||||
- **Permanent complexity imported**: Four finding event types, one bounded recipient-resolution contract, one direct-notification copy contract, and focused regression coverage for entitlement-safe delivery and dedupe.
|
||||
- **Why now**: Spec 219 clarified responsibility, Spec 221 created the personal assignee queue, and Spec 222 created shared intake. The next missing slice is to close the loop so those surfaces no longer rely on manual polling.
|
||||
- **Why not local**: A badge or queue-only polish fix would still leave assignment, reopen, and aging changes silent across the workspace. The gap is cross-cutting workflow feedback, not one page.
|
||||
- **Approval class**: Core Enterprise
|
||||
- **Red flags triggered**: One bounded new recipient-resolution rule and one new event family. Scope stays acceptable because it reuses existing finding truth, existing alert delivery infrastructure, and existing notification primitives.
|
||||
- **Score**: Nutzen: 2 | Dringlichkeit: 2 | Scope: 2 | Komplexität: 1 | Produktnähe: 2 | Wiederverwendung: 1 | **Gesamt: 10/12**
|
||||
- **Decision**: approve
|
||||
|
||||
## Spec Scope Fields *(mandatory)*
|
||||
|
||||
- **Scope**: workspace
|
||||
- **Primary Routes**:
|
||||
- Admin UI → Workspace → Monitoring → Alerts → Alert rules
|
||||
- Admin UI → Workspace → Monitoring → Alerts → Alert deliveries
|
||||
- `/admin/t/{tenant}/findings/{finding}` as the primary follow-up destination from finding notifications
|
||||
- **Data Ownership**:
|
||||
- Tenant-owned findings remain the only source of truth for assignment, reopen state, due state, severity, and tenant scope.
|
||||
- Workspace-owned alert rules and alert destinations remain the only source of truth for external copies and shared escalation delivery.
|
||||
- Existing user notification records remain delivery artifacts only and must not become a second findings workflow state store.
|
||||
- **RBAC**:
|
||||
- Workspace membership is required for alert rule and alert delivery surfaces.
|
||||
- `ALERTS_VIEW` gates viewing alert-rule configuration and alert delivery history.
|
||||
- `ALERTS_MANAGE` gates creating, editing, enabling, disabling, or deleting external alert-copy rules.
|
||||
- Direct finding notifications are only delivered to currently entitled operators who may already inspect the target tenant and finding scope.
|
||||
- Non-members or wrong-plane requests remain deny-as-not-found. Members missing capability receive `403` on protected configuration surfaces.
|
||||
|
||||
## UI / Surface Guardrail Impact *(mandatory when operator-facing surfaces are changed; otherwise write `N/A`)*
|
||||
|
||||
| Surface / Change | Operator-facing surface change? | Native vs Custom | Shared-Family Relevance | State Layers Touched | Exception Needed? | Low-Impact / `N/A` Note |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Alert rules resource gains finding notification event types and routing copy | yes | Native Filament resource forms + existing alert configuration primitives | Same workspace monitoring configuration family as existing alert rules | form, event labels, routing helper copy | no | Existing surface extended; no new alert page |
|
||||
| Alert deliveries viewer gains finding-event labels and delivery visibility | yes | Native Filament table + existing alert delivery viewer | Same workspace alert observability family | table, filter labels, delivery summaries | no | Existing viewer extended; still read-only |
|
||||
| Direct finding notifications and deep links | yes | Existing in-app notification primitives + shared link helpers | Same personal workflow entry-point family as other operator notifications | notification payload, deep link, recipient explanation | no | Reuses current notification surface; no new notification center |
|
||||
|
||||
## Decision-First Surface Role *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Decision Role | Human-in-the-loop Moment | Immediately Visible for First Decision | On-Demand Detail / Evidence | Why This Is Primary or Why Not | Workflow Alignment | Attention-load Reduction |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Alert rules resource gains finding notification event types and routing copy | Secondary Context Surface | A workspace operator decides which finding events should also create external or shared-team copies | Event type, tenant scope, severity threshold, cooldown, quiet-hours, and destinations | Delivery history, raw event keys, and failure diagnostics | Secondary because it configures workflow feedback rather than hosting the work itself | Keeps findings notification policy inside existing Alerts administration | Avoids inventing a second findings-specific settings area |
|
||||
| Alert deliveries viewer gains finding-event labels and delivery visibility | Tertiary Evidence / Diagnostics Surface | A workspace operator verifies whether rule-based copies were sent, deferred, suppressed, or failed | Event label, tenant, severity, status, and timestamp | Safe diagnostics and historical delivery details | Tertiary because it explains delivery history after the notification decision already happened | Preserves one audit-style surface for external delivery truth | Avoids debugging notification behavior by searching logs or guessing destination behavior |
|
||||
| Direct finding notifications and deep links | Secondary Context Surface | An operator receives a finding event and decides whether to open the finding now | Why the operator was notified, the affected tenant, the finding summary, severity, and one deep link | Full finding detail, evidence, audit trail, and workflow actions after opening the finding | Secondary because the notification points into the real work surface instead of replacing it | Aligns assignment and aging signals with the already-established findings workflow surfaces | Removes repeated polling of My Findings, intake, and tenant-local findings pages |
|
||||
|
||||
## UI/UX Surface Classification *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Action Surface Class | Surface Type | Likely Next Operator Action | Primary Inspect/Open Model | Row Click | Secondary Actions Placement | Destructive Actions Placement | Canonical Collection Route | Canonical Detail Route | Scope Signals | Canonical Noun | Critical Truth Visible by Default | Exception Type / Justification |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Alert rules resource gains finding notification event types and routing copy | Config / Settings | Workflow routing configuration | Save or update a rule for finding events | Alert rule | required on the existing list | Existing `More` group on the alert-rules list | Existing destructive actions remain grouped and confirmed on the resource | Workspace Monitoring → Alerts → Alert rules | Existing alert-rule edit surface | Workspace scope, event type, severity, tenant targeting, destinations | Alert rules / Alert rule | Which finding events are routed externally and under which scope rules | none |
|
||||
| Alert deliveries viewer gains finding-event labels and delivery visibility | Utility / System | Read-only log / report surface | Inspect whether a finding-event delivery was sent or suppressed | Alert delivery | allowed on the existing viewer | Existing read-only filter and inspect controls only | none | Workspace Monitoring → Alerts → Alert deliveries | Existing delivery inspect surface | Workspace scope, tenant label, delivery status, event type | Alert deliveries / Alert delivery | Whether a finding-event copy was sent, deferred, suppressed, or failed | none |
|
||||
| Direct finding notifications and deep links | Utility / System | Notification / drill-in entry point | Open the finding that needs follow-up | Finding | forbidden | No competing mutation; one deep link only | none | Existing in-app notification surface | `/admin/t/{tenant}/findings/{finding}` | Tenant name, severity, recipient reason, event label | Findings / Finding | Why this operator was notified and what finding requires attention | Existing notification surface reused; no new standalone page |
|
||||
|
||||
## Operator Surface Contract *(mandatory when operator-facing surfaces are changed)*
|
||||
|
||||
| Surface | Primary Persona | Decision / Operator Action Supported | Surface Type | Primary Operator Question | Default-visible Information | Diagnostics-only Information | Status Dimensions Used | Mutation Scope | Primary Actions | Dangerous Actions |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Alert rules resource gains finding notification event types and routing copy | Workspace operator with alert-management responsibility | Decide which finding events should create external copies or shared escalation signals | Configuration surface | Which finding workflow events should notify beyond the directly responsible operator? | Event type, minimum severity, tenant scope, destinations, cooldown, quiet hours | Delivery failures, suppressed history, low-level event keys | alert-event type, severity threshold, tenant scope | Workspace configuration only | Create rule, Edit rule, Enable or disable rule | Delete rule |
|
||||
| Alert deliveries viewer gains finding-event labels and delivery visibility | Workspace operator reviewing alert behavior | Verify whether external finding-event copies were delivered as configured | Read-only history surface | Did the configured finding notification copy actually go out? | Event label, tenant, severity, timestamp, delivery status | Safe failure reasons and delivery metadata | delivery status, event type, severity | none | View delivery | none |
|
||||
| Direct finding notifications and deep links | Tenant operator or tenant manager | Decide whether to open a specific finding now because work was assigned, reopened, is due soon, or is overdue | Notification entry point | Why am I being notified, and what do I need to look at? | Tenant, finding summary, severity, event label, recipient reason, deep link | Full evidence, audit trail, lifecycle history, and related context after opening the finding | assignment change, reopen truth, due-state aging | none on the notification itself | Open finding | none |
|
||||
|
||||
## Proportionality Review *(mandatory when structural complexity is introduced)*
|
||||
|
||||
- **New source of truth?**: no
|
||||
- **New persisted entity/table/artifact?**: no
|
||||
- **New abstraction?**: yes — one bounded recipient-resolution contract over existing finding owner and assignee truth plus existing alert destinations
|
||||
- **New enum/state/reason family?**: yes — four finding notification event types and one bounded recipient-reason vocabulary
|
||||
- **New cross-domain UI framework/taxonomy?**: no
|
||||
- **Current operator problem**: Findings already move through assignment, reopen, and due-state transitions, but the responsible operator still has to rediscover those changes by polling queues and tenant pages.
|
||||
- **Existing structure is insufficient because**: Existing findings queues only show current backlog once an operator opens them. Existing Alerts rules handle shared external delivery, but they do not by themselves define who the directly responsible operator should be for assignment, reopen, and aging signals.
|
||||
- **Narrowest correct implementation**: Reuse the current finding owner and assignee contract, add four event types, resolve one direct recipient per event when possible, and let existing Alerts rules optionally produce external copies.
|
||||
- **Ownership cost**: Ongoing maintenance for one bounded recipient-resolution rule set, event labels, and regression coverage for entitlement-safe delivery and dedupe.
|
||||
- **Alternative intentionally rejected**: A full notification-preference center or a generic workflow-notification engine was rejected because it imports durable product complexity before the smaller control-loop problem is proven.
|
||||
- **Release truth**: Current-release truth. This spec turns existing findings workflow changes into actionable operator feedback now rather than preparing for a distant automation layer.
|
||||
|
||||
### Compatibility posture
|
||||
|
||||
This feature assumes a pre-production environment.
|
||||
|
||||
Backward compatibility, legacy aliases, migration shims, historical fixtures, and compatibility-specific tests are out of scope unless explicitly required by this spec.
|
||||
|
||||
Canonical replacement is preferred over preservation.
|
||||
|
||||
## Testing / Lane / Runtime Impact *(mandatory for runtime behavior changes)*
|
||||
|
||||
- **Test purpose / classification**: Feature
|
||||
- **Validation lane(s)**: fast-feedback, confidence
|
||||
- **Why this classification and these lanes are sufficient**: The feature changes visible workflow consequences for findings and workspace alert configuration, but it does not add a new browser-only interaction model or a heavy-governance computation lane. Focused feature coverage proves event production, direct recipient routing, external rule integration, deep-link safety, and no-leak authorization behavior.
|
||||
- **New or expanded test families**: Add focused finding-notification event tests, direct-recipient routing tests, due-cycle dedupe tests, alert-rule event-type option tests, and deep-link authorization tests.
|
||||
- **Fixture / helper cost impact**: Moderate. Tests need findings with explicit owner and assignee combinations, due dates across notification thresholds, workspace alert rules and destinations, and hidden versus visible tenant memberships.
|
||||
- **Heavy-family visibility / justification**: none
|
||||
- **Special surface test profile**: global-context-shell
|
||||
- **Standard-native relief or required special coverage**: Ordinary feature coverage is sufficient, plus explicit proof that notification deep links honor current tenant entitlement and that hidden tenants do not leak through notification text, event routing, or delivery history.
|
||||
- **Reviewer handoff**: Reviewers must confirm that each event type has a deterministic trigger, that direct recipient precedence matches the spec, that owner-only changes do not emit assignment notifications, and that external rule-based copies remain optional rather than becoming the only notification path.
|
||||
- **Budget / baseline / trend impact**: none
|
||||
- **Escalation needed**: none
|
||||
- **Active feature PR close-out entry**: Guardrail
|
||||
- **Planned validation commands**:
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Findings/FindingsNotificationEventTest.php tests/Feature/Findings/FindingsNotificationRoutingTest.php`
|
||||
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php tests/Feature/Notifications/FindingNotificationLinkTest.php`
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### User Story 1 - Receive direct notification when work changes hands or reopens (Priority: P1)
|
||||
|
||||
As a responsible operator, I want assignment and automatic reopen events to notify me directly, so findings do not silently appear in my workload.
|
||||
|
||||
**Why this priority**: This is the smallest workflow-closing slice. If assignment and automatic reopen remain silent, ownership semantics and personal queues still rely on manual polling.
|
||||
|
||||
**Independent Test**: Can be fully tested by assigning findings to a user, triggering an automatic reopen, and verifying that the correct recipient receives one tenant-safe notification with a deep link.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an open finding is assigned to a new assignee, **When** the assignment is saved, **Then** the new assignee receives one direct notification explaining that the finding was assigned to them.
|
||||
2. **Given** a previously resolved finding is automatically reopened by system detection and still has an assignee, **When** the reopen is recorded, **Then** the assignee receives one direct reopen notification with a deep link to the finding.
|
||||
3. **Given** only the accountable owner changes while the assignee remains unchanged, **When** the owner update is saved, **Then** no assignment notification is emitted.
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - Get due-soon reminders and overdue escalation without spam (Priority: P1)
|
||||
|
||||
As an operator responsible for a finding, I want the system to remind me before a due date and escalate overdue items predictably, so aging work does not disappear until the next manual review.
|
||||
|
||||
**Why this priority**: Due dates without reminder and escalation behavior are not operational controls. This story turns due metadata into an actionable workflow signal.
|
||||
|
||||
**Independent Test**: Can be fully tested by placing findings into the due-soon window and overdue state across different owner and assignee combinations, then verifying the correct recipient, one-time due-cycle behavior, and no duplicate notifications when the same person holds both roles.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** an open finding enters the due-soon reminder window and has a current assignee, **When** evaluation runs, **Then** the assignee receives one due-soon reminder for that due cycle.
|
||||
2. **Given** an open finding becomes overdue and has an owner distinct from the assignee, **When** evaluation runs, **Then** the owner receives the overdue escalation and the system does not send a second duplicate direct notification if owner and assignee are the same person.
|
||||
3. **Given** a finding has already emitted a due-soon or overdue notification for the current due cycle, **When** later evaluations run without a due-date reset or reopen, **Then** no duplicate direct notification is emitted for that same cycle.
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - Configure external copies through existing Alerts management (Priority: P2)
|
||||
|
||||
As a workspace operator, I want the existing Alerts rules to support finding assignment, reopen, due-soon, and overdue event types, so shared team destinations can receive the same workflow signals without a second notification product.
|
||||
|
||||
**Why this priority**: The direct user notification closes the personal loop, but enterprise teams still need optional shared or external copies through the current alerting foundation.
|
||||
|
||||
**Independent Test**: Can be fully tested by adding the new event types to an alert rule, triggering one matching event, and verifying that an external delivery is created while the direct personal notification behavior remains available.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a workspace operator edits an alert rule, **When** they open the event-type selector, **Then** the four new findings notification event types are available.
|
||||
2. **Given** a matching alert rule exists for an overdue findings event, **When** an open finding becomes overdue, **Then** the existing alert delivery pipeline creates one external copy per matching enabled destination.
|
||||
3. **Given** no matching alert rule exists for an assignment event, **When** a finding is assigned to an entitled operator, **Then** the direct operator notification still occurs while no external delivery is created.
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- The same entitled user may be both owner and assignee; the system must send one direct notification, not two copies with different labels.
|
||||
- A finding may lose its assignee or owner entitlement after the workflow event was created but before delivery; direct delivery must re-check current entitlement and suppress the personal notification instead of leaking scope.
|
||||
- A finding may become terminal after entering the due-soon window but before evaluation sends reminders; due-soon and overdue notifications must suppress for terminal findings.
|
||||
- Rapid reassignment or repeated automatic reopen within the same notification fingerprint window must not fan out duplicate direct notifications.
|
||||
- Existing tenant-level `sla_due` summary alerts remain valid and separate; this feature must not redefine or remove that aggregate overdue signal.
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
**Constitution alignment (required):** This feature adds no Microsoft Graph calls and no new `OperationRun` type. It reuses the existing alert-evaluation and alert-delivery operations plus existing in-app notification primitives. Scheduled evaluation remains system-run, so no new initiator-only terminal DB notification rule is introduced. Tenant isolation, delivery history, and test coverage remain mandatory because the feature emits new finding event types into existing background alert flows.
|
||||
|
||||
**Constitution alignment (TEST-GOV-001):** The proof burden is focused feature coverage for finding event production, recipient resolution, direct notification deep-link safety, alert-rule UI options, external delivery integration, and hidden-tenant suppression. No browser or heavy-governance lane is required.
|
||||
|
||||
**Constitution alignment (RBAC-UX):** The feature spans workspace-context alert configuration and tenant-scoped finding follow-up. Non-members, wrong-workspace users, and hidden-tenant requests remain `404`. Workspace members without `ALERTS_VIEW` or `ALERTS_MANAGE` remain `403` on protected alert pages. Notification payloads and deep links must not reveal finding or tenant details to operators who are no longer entitled to inspect the finding at open time.
|
||||
|
||||
**Constitution alignment (UI-FIL-001):** Existing Filament `AlertRuleResource` and alert delivery viewer remain the only configuration and delivery-history surfaces. Existing notification primitives and shared link helpers must be reused for direct finding notifications. No findings-specific notification center, badge system, or page-local alert markup may be introduced.
|
||||
|
||||
**Constitution alignment (UI-NAMING-001):** The target object is always the `finding`. Primary operator verbs are `assigned`, `reopened`, `due soon`, `overdue`, and `Open finding`. The same finding vocabulary must hold across alert-rule labels, notification titles, delivery history, and deep-link copy. Implementation-first terms such as fingerprint, recipient resolver, or evaluation window remain secondary.
|
||||
|
||||
**Constitution alignment (DECIDE-001):** Direct notifications are entry points, not replacement work surfaces. They must make the first decision obvious in one glance and then defer to the existing finding detail as the durable decision context.
|
||||
|
||||
**Constitution alignment (UI-CONST-001 / UI-SURF-001 / ACTSURF-001 / HDR-001):** No new list or detail page is introduced. Existing alert configuration surfaces stay config-first. Direct notifications expose one inspect model only: the finding. They must not compete with page-local mutation affordances or invent a second queue model.
|
||||
|
||||
**Constitution alignment (UI-SEM-001 / LAYER-001 / TEST-TRUTH-001):** This feature derives notification truth directly from existing finding lifecycle, ownership, due-date, and tenant-entitlement data. It must not add a second persisted workflow state, a local notification-only status, or a duplicate owner or assignee meaning.
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: The system MUST support four new finding notification event types for the existing alert dispatch pipeline: `findings.assigned`, `findings.reopened`, `findings.due_soon`, and `findings.overdue`.
|
||||
- **FR-002**: `findings.assigned` MUST be produced when an open finding is assigned to a new assignee. Owner-only changes, assignee clears, and no-op saves MUST NOT emit this event.
|
||||
- **FR-003**: `findings.reopened` MUST be produced only for system-driven reopen of an existing finding caused by recurring detection. Manual reopen remains out of scope for v1 notifications.
|
||||
- **FR-004**: `findings.due_soon` MUST be produced once per due cycle when an open finding first enters the due-soon reminder window. The default v1 reminder window is 24 hours before `due_at`.
|
||||
- **FR-005**: `findings.overdue` MUST be produced once per due cycle when an open finding first becomes overdue.
|
||||
- **FR-006**: A finding due cycle resets only when the finding’s `due_at` is recalculated by the existing lifecycle contract, such as after a system reopen that resets due dates. `reopened_at` may explain why the cycle changed, but only a new `due_at` value may produce a new due-soon or overdue event for the same finding.
|
||||
- **FR-007**: The system MUST resolve one direct personal recipient for each event when possible using this precedence:
|
||||
- `findings.assigned` → new assignee
|
||||
- `findings.reopened` → current assignee, else current owner
|
||||
- `findings.due_soon` → current assignee, else current owner
|
||||
- `findings.overdue` → current owner, else current assignee
|
||||
- **FR-008**: Direct personal delivery MUST only occur when the resolved recipient is still currently entitled to inspect the target tenant and finding at send time. If no currently entitled direct recipient exists, the system MUST suppress direct personal delivery rather than broaden disclosure.
|
||||
- **FR-009**: When the resolved owner and assignee are the same currently entitled user, the system MUST send only one direct personal notification for that event.
|
||||
- **FR-010**: Each finding event MUST carry a deterministic fingerprint suitable for dedupe and cooldown. Assignment fingerprints must distinguish the target assignee change, automatic reopen fingerprints must distinguish the reopen occurrence, and due-soon or overdue fingerprints must roll when the due cycle resets.
|
||||
- **FR-011**: Direct personal notifications MUST be available without requiring a matching workspace alert rule. Workspace alert rules remain optional copies for external or shared-team delivery.
|
||||
- **FR-012**: Existing Alerts rules MUST support the four new finding notification event types in the event-type selector. No new alert pages, no new destination type family, and no findings-specific preference center may be introduced in v1.
|
||||
- **FR-013**: Existing Alerts v1 behavior for minimum severity, tenant scoping, cooldown, dedupe, quiet hours, and destination fan-out MUST apply unchanged to external rule-based copies of the new finding events.
|
||||
- **FR-014**: Direct personal notification payloads MUST include the finding summary, tenant context, severity, event label, why the current operator received it, and one deep link to open the finding.
|
||||
- **FR-015**: Notification titles, body copy, delivery history labels, and alert-rule event labels MUST stay domain-first and must not expose raw internal event keys as the primary operator language.
|
||||
- **FR-016**: Direct and external notifications MUST deep-link to the existing tenant finding detail route for the target finding. Opening that link MUST continue to honor current `404` versus `403` entitlement semantics at the time of use.
|
||||
- **FR-017**: Existing tenant-level `sla_due` summary alert behavior from Spec 111 MUST remain in place. The new due-soon and overdue events are finding-level actionable signals and MUST NOT replace or silently redefine the aggregate `sla_due` event.
|
||||
- **FR-018**: Alert delivery history MUST show external finding-event deliveries in the existing workspace alert deliveries viewer with the new event labels. The feature MUST NOT introduce a second workspace-wide history page for direct in-app personal notifications.
|
||||
- **FR-019**: The feature MUST NOT introduce a new findings lifecycle state, a second assignment model, a notification-only queue, or a repeated daily overdue escalation loop by default.
|
||||
|
||||
## UI Action Matrix *(mandatory when Filament is changed)*
|
||||
|
||||
| Surface | Location | Header Actions | Inspect Affordance (List/Table) | Row Actions (max 2 visible) | Bulk Actions (grouped) | Empty-State CTA(s) | View Header Actions | Create/Edit Save+Cancel | Audit log? | Notes / Exemptions |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| Alert Rules Resource | Workspace Monitoring → Alerts → Alert rules | Existing create action only | Clickable row to existing edit surface | Existing Edit and `More` actions only | none | Existing create CTA only | n/a | Save / Cancel | Yes for existing rule mutations | Surface is extended only with four event types and routing helper copy. Action Surface Contract remains satisfied by the existing resource pattern. |
|
||||
| Alert Deliveries viewer | Workspace Monitoring → Alerts → Alert deliveries | none | Existing inspect behavior only | Existing read-only inspect action only | none | none | n/a | n/a | No new mutation audit because the surface stays read-only | Existing viewer only gains finding-event labels and safe recipient-facing delivery summaries. |
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
|
||||
- **Finding notification event**: A derived workflow event produced from an existing finding transition or aging threshold and routed through the existing alerting pipeline.
|
||||
- **Direct finding notification**: A personal in-app notification sent to the single currently responsible operator resolved from existing finding owner and assignee truth.
|
||||
- **Alert rule (extended)**: The existing workspace alert rule model, extended with the four new finding notification event types.
|
||||
- **Recipient-resolution contract**: The bounded precedence rule that selects the directly responsible operator for assignment, automatic reopen, due-soon, and overdue events without creating a second ownership model.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: In acceptance review, an operator can understand why they received an assignment, reopen, due-soon, or overdue notification and open the correct finding in one interaction.
|
||||
- **SC-002**: 100% of covered automated tests route each of the four event types to the correct direct recipient or correctly suppress direct delivery when no currently entitled recipient exists.
|
||||
- **SC-003**: 100% of covered due-cycle tests emit at most one direct due-soon reminder and one direct overdue escalation per finding due cycle unless the due cycle resets.
|
||||
- **SC-004**: 100% of covered alert-rule tests show that the four new event types are available in the existing Alerts UI and create external deliveries only when matching rules exist.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The existing notification-routing foundation can deliver direct in-app notifications to currently entitled operators without introducing a second notification product.
|
||||
- The due-soon horizon is fixed at 24 hours before `due_at` in v1.
|
||||
- Existing finding detail remains the canonical follow-up surface reached from the notification deep link.
|
||||
- Membership and assignment hygiene after a person loses tenant access remains a separate hardening slice and is not solved fully here.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Introduce multi-stage escalation chains or automatic reassign logic.
|
||||
- Build a findings-specific notification-preference center or destination management UX.
|
||||
- Replace the existing aggregate `sla_due` alert semantics with item-level reminders.
|
||||
- Add comments, chat, or external ticket handoff.
|
||||
- Create a second findings queue or a notification-only workflow state.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Spec 099, Alerts v1, remains the source of truth for workspace alert rules, destinations, cooldown, quiet hours, and delivery history.
|
||||
- Spec 100, Alert target test actions, remains the source of truth for alert destination testability and delivery-viewer conventions.
|
||||
- Spec 111, Findings Workflow + SLA, remains the source of truth for finding lifecycle, due dates, reopen behavior, and aggregate `sla_due` alerts.
|
||||
- Spec 219, Finding Ownership Semantics Clarification, remains the source of truth for owner-versus-assignee meaning.
|
||||
- Spec 221, Findings Operator Inbox V1, and Spec 222, Findings Intake & Team Queue V1, remain the established work surfaces that benefit from these notifications even though this spec does not create new queue pages.
|
||||
211
specs/224-findings-notifications-escalation/tasks.md
Normal file
211
specs/224-findings-notifications-escalation/tasks.md
Normal file
@ -0,0 +1,211 @@
|
||||
# Tasks: Findings Notifications & Escalation v1
|
||||
|
||||
**Input**: Design documents from `/specs/224-findings-notifications-escalation/`
|
||||
**Prerequisites**: `plan.md`, `spec.md`, `research.md`, `data-model.md`, `contracts/findings-notifications-escalation.logical.openapi.yaml`, `quickstart.md`
|
||||
|
||||
**Tests**: Required. This feature changes runtime behavior in finding workflow mutations, scheduled alert evaluation, Laravel database notifications, and existing Filament alert-management surfaces, so Pest coverage must be added in `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`, `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`, `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php`, `apps/platform/tests/Feature/Alerts/SlaDueAlertTest.php`, and `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php`.
|
||||
**Operations**: No new `OperationRun` is introduced. Scheduled due-soon and overdue evaluation must remain on the existing `alerts.evaluate` cadence via `apps/platform/app/Jobs/Alerts/EvaluateAlertsJob.php` and the existing `tenantpilot:alerts:dispatch` command.
|
||||
**RBAC**: Workspace alert configuration stays on the admin `/admin` plane and finding follow-up stays on the tenant `/admin/t/{tenant}/findings/{finding}` plane. The implementation must preserve `ALERTS_VIEW`-gated read access to alert rules and alert deliveries, `ALERTS_MANAGE`-gated alert-rule mutation, non-member and hidden-scope `404`, in-scope missing-capability `403`, and send-time entitlement rechecks before direct personal delivery.
|
||||
**UI / Surface Guardrails**: `Alert rules` and `Alert deliveries` stay `standard-native-filament` surfaces. The database notification drawer plus tenant finding detail link is a `global-context-shell` seam and must keep one calm `Open finding` drill-in path only.
|
||||
**Filament UI Action Surfaces**: `AlertRuleResource` and `AlertDeliveryResource` remain existing resource patterns with no new page family, no new destructive action, and no second notification center. Direct finding notifications expose one inspect model only: the finding.
|
||||
**Badges**: Existing finding severity, lifecycle, and alert-delivery status semantics remain authoritative. No page-local badge taxonomy or ad-hoc status mapping is introduced.
|
||||
|
||||
**Organization**: Tasks are grouped by user story so each slice stays independently testable. Recommended delivery order is `US1 -> US2 -> US3`, because direct responsible-user delivery closes the smallest workflow gap first, due-cycle reminders build on the same delivery seam second, and external-copy management is safest after direct-event truth is established.
|
||||
|
||||
## Test Governance Checklist
|
||||
|
||||
- [x] Lane assignment is named and is the narrowest sufficient proof for the changed behavior.
|
||||
- [x] New or changed tests stay in the smallest honest family, and any heavy-governance or browser addition is explicit.
|
||||
- [x] Shared helpers, factories, seeds, fixtures, and context defaults stay cheap by default; any widening is isolated or documented.
|
||||
- [x] Planned validation commands cover the change without pulling in unrelated lane cost.
|
||||
- [x] The declared surface test profile or `standard-native-filament` relief is explicit.
|
||||
- [x] Any material budget, baseline, trend, or escalation note is recorded in the active spec or PR.
|
||||
|
||||
## Phase 1: Setup (Notification Scaffolding)
|
||||
|
||||
**Purpose**: Prepare the shared delivery seam and focused regression suites used across all stories.
|
||||
|
||||
- [X] T001 [P] Create the finding notification service scaffold in `apps/platform/app/Services/Findings/FindingNotificationService.php`
|
||||
- [X] T002 [P] Create the finding event database-notification scaffold in `apps/platform/app/Notifications/Findings/FindingEventNotification.php`
|
||||
- [X] T003 [P] Create focused Pest scaffolding in `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`, `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`, `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php`, and `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php`
|
||||
|
||||
**Checkpoint**: The shared service, notification class, and focused test files exist and are ready for implementation work.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Foundational (Blocking Event Vocabulary And Delivery Seams)
|
||||
|
||||
**Purpose**: Establish the canonical finding event keys, direct-delivery baseline, and shared dispatch contract every story depends on.
|
||||
|
||||
**⚠️ CRITICAL**: No user story work should begin until this phase is complete.
|
||||
|
||||
- [X] T004 Add the four canonical finding event constants in `apps/platform/app/Models/AlertRule.php`
|
||||
- [X] T005 Implement the shared finding-event envelope builder, recipient-resolution precedence, send-time entitlement recheck, fingerprint helpers, and direct-delivery dedupe baseline in `apps/platform/app/Services/Findings/FindingNotificationService.php`
|
||||
- [X] T006 Implement the base Filament database notification payload, recipient-reason copy, and tenant finding deep link in `apps/platform/app/Notifications/Findings/FindingEventNotification.php`
|
||||
- [X] T007 Add foundational database-notification payload-shape and tenant-safe `404` versus `403` link coverage in `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php`
|
||||
- [X] T008 Wire the shared optional external-copy dispatch baseline from `apps/platform/app/Services/Findings/FindingNotificationService.php` into `apps/platform/app/Services/Alerts/AlertDispatchService.php`
|
||||
|
||||
**Checkpoint**: Shared event vocabulary, recipient resolution, direct personal delivery, and external-copy handoff are available for all stories.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: User Story 1 - Receive direct notification when work changes hands or reopens (Priority: P1) 🎯 MVP
|
||||
|
||||
**Goal**: Notify the directly responsible operator when an open finding is assigned to them or a previously terminal finding is reopened by system detection.
|
||||
|
||||
**Independent Test**: Assign an open finding to a new assignee and trigger a system reopen on a terminal finding, then verify one entitled recipient receives one tenant-safe notification with a deep link while owner-only changes remain silent.
|
||||
|
||||
### Tests for User Story 1
|
||||
|
||||
- [X] T009 [P] [US1] Add assignment and system-reopen event production plus rapid reassignment and repeated automatic-reopen dedupe coverage in `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`
|
||||
- [X] T010 [P] [US1] Add recipient precedence, owner-only suppression, assignee-clear suppression, and entitlement-loss coverage for assignment and reopen flows in `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`
|
||||
|
||||
### Implementation for User Story 1
|
||||
|
||||
- [X] T011 [US1] Emit `findings.assigned` only after committed assignee changes and suppress owner-only, assignee-clear, and no-op saves in `apps/platform/app/Services/Findings/FindingWorkflowService.php`
|
||||
- [X] T012 [US1] Emit `findings.reopened` only from the system-driven reopen path in `apps/platform/app/Services/Findings/FindingWorkflowService.php`
|
||||
- [X] T013 [US1] Align assignment and reopen notification titles, bodies, and recipient-reason vocabulary in `apps/platform/app/Services/Findings/FindingNotificationService.php` and `apps/platform/app/Notifications/Findings/FindingEventNotification.php`
|
||||
|
||||
**Checkpoint**: User Story 1 is independently functional and the responsible operator no longer needs to poll findings pages to notice assignment or automatic reopen.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: User Story 2 - Get due-soon reminders and overdue escalation without spam (Priority: P1)
|
||||
|
||||
**Goal**: Turn finding due dates into one-per-cycle due-soon reminders and overdue escalations without duplicate personal notification noise.
|
||||
|
||||
**Independent Test**: Seed open findings across due-soon and overdue thresholds with different owner and assignee combinations, run alert evaluation, and verify correct recipient precedence, terminal suppression, same-user dedupe, and one notification per due cycle.
|
||||
|
||||
### Tests for User Story 2
|
||||
|
||||
- [X] T014 [P] [US2] Add due-soon and overdue window, one-per-cycle, and `due_at`-driven due-cycle-reset coverage in `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`
|
||||
- [X] T015 [P] [US2] Add due recipient precedence, same-user dedupe, terminal-finding suppression, and no-entitled-recipient suppression coverage in `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`
|
||||
|
||||
### Implementation for User Story 2
|
||||
|
||||
- [X] T016 [US2] Add workspace-scoped due-soon and overdue candidate collection with a 24-hour reminder window and non-open-finding suppression in `apps/platform/app/Jobs/Alerts/EvaluateAlertsJob.php`
|
||||
- [X] T017 [US2] Route due-soon and overdue candidates through the shared delivery seam and derive per-cycle fingerprints from the recalculated `due_at` value in `apps/platform/app/Services/Findings/FindingNotificationService.php`
|
||||
- [X] T018 [US2] Add due-window and owner-versus-assignee factory states needed for due-cycle reminder coverage in `apps/platform/database/factories/FindingFactory.php`
|
||||
|
||||
**Checkpoint**: User Story 2 is independently functional and due dates now produce predictable, non-spammy direct reminders and overdue escalation.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: User Story 3 - Configure external copies through existing Alerts management (Priority: P2)
|
||||
|
||||
**Goal**: Let workspace operators configure and inspect optional external copies for the same finding events through the existing Alerts management surfaces.
|
||||
|
||||
**Independent Test**: Add the new finding event types to an alert rule, trigger a matching event through the shared delivery seam, and verify external deliveries appear in the existing viewer while direct personal delivery still works without a matching rule.
|
||||
|
||||
### Tests for User Story 3
|
||||
|
||||
- [X] T019 [US3] Add alert-rule event option exposure, alert-rule and alert-delivery non-member or hidden-scope `404` versus in-scope capability `403` coverage, `ALERTS_VIEW` read versus `ALERTS_MANAGE` mutation boundaries, inherited external-copy behavior covering minimum severity, tenant scoping, cooldown, quiet hours, dedupe, delivery-history label and filter coverage, and direct-without-rule behavior in `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php`; extend `apps/platform/tests/Feature/Alerts/SlaDueAlertTest.php` to prove aggregate `sla_due` behavior remains unchanged
|
||||
|
||||
### Implementation for User Story 3
|
||||
|
||||
- [X] T020 [P] [US3] Expose the four finding notification event types in the existing selector and label mapping in `apps/platform/app/Filament/Resources/AlertRuleResource.php`
|
||||
- [X] T021 [P] [US3] Render finding-event labels and filter options in the existing viewer in `apps/platform/app/Filament/Resources/AlertDeliveryResource.php`
|
||||
- [X] T022 [US3] Finalize finding-event payload normalization and rule-driven external-copy fan-out behavior in `apps/platform/app/Services/Alerts/AlertDispatchService.php` and `apps/platform/app/Services/Findings/FindingNotificationService.php`
|
||||
|
||||
**Checkpoint**: User Story 3 is independently functional and workspace teams can reuse existing Alerts rules and delivery history for finding assignment, reopen, due-soon, and overdue copies.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Polish & Cross-Cutting Concerns
|
||||
|
||||
**Purpose**: Finish guardrail alignment, formatting, and focused verification across the full feature.
|
||||
|
||||
- [X] T023 Review operator-facing finding vocabulary, recipient-reason copy, and guardrail alignment in `apps/platform/app/Services/Findings/FindingNotificationService.php`, `apps/platform/app/Notifications/Findings/FindingEventNotification.php`, `apps/platform/app/Filament/Resources/AlertRuleResource.php`, and `apps/platform/app/Filament/Resources/AlertDeliveryResource.php`
|
||||
- [X] T024 Run formatting for `apps/platform/app/Services/Findings/FindingNotificationService.php`, `apps/platform/app/Notifications/Findings/FindingEventNotification.php`, `apps/platform/app/Services/Findings/FindingWorkflowService.php`, `apps/platform/app/Jobs/Alerts/EvaluateAlertsJob.php`, `apps/platform/app/Services/Alerts/AlertDispatchService.php`, `apps/platform/app/Models/AlertRule.php`, `apps/platform/app/Filament/Resources/AlertRuleResource.php`, `apps/platform/app/Filament/Resources/AlertDeliveryResource.php`, `apps/platform/database/factories/FindingFactory.php`, `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`, `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`, `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php`, and `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php` with `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
|
||||
- [X] T025 Run the focused verification workflow from `specs/224-findings-notifications-escalation/quickstart.md` against `apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php`, `apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php`, `apps/platform/tests/Feature/Alerts/FindingsAlertRuleIntegrationTest.php`, `apps/platform/tests/Feature/Alerts/SlaDueAlertTest.php`, and `apps/platform/tests/Feature/Notifications/FindingNotificationLinkTest.php`
|
||||
|
||||
---
|
||||
|
||||
## Dependencies & Execution Order
|
||||
|
||||
### Phase Dependencies
|
||||
|
||||
- **Setup (Phase 1)**: Starts immediately and prepares the shared service, notification class, and focused Pest files.
|
||||
- **Foundational (Phase 2)**: Depends on Setup and blocks all user stories until shared event vocabulary, recipient resolution, and dispatch seams exist.
|
||||
- **User Story 1 (Phase 3)**: Depends on Foundational completion and is the recommended MVP cut.
|
||||
- **User Story 2 (Phase 4)**: Depends on Foundational completion and extends the same direct-delivery seam with scheduled due evaluation.
|
||||
- **User Story 3 (Phase 5)**: Depends on Foundational completion and extends the existing Alerts management surfaces with the same event vocabulary.
|
||||
- **Polish (Phase 6)**: Depends on all desired user stories being complete.
|
||||
|
||||
### User Story Dependencies
|
||||
|
||||
- **US1**: No dependencies beyond Foundational.
|
||||
- **US2**: No hard dependency on US1, but it reuses the same delivery seam and should preserve direct-delivery vocabulary established there.
|
||||
- **US3**: No hard dependency on US1 or US2 after Foundational, but it must stay aligned with the shared event vocabulary and direct-delivery contract they use.
|
||||
|
||||
### Within Each User Story
|
||||
|
||||
- Write the story tests first and confirm they fail before implementation is considered complete.
|
||||
- Keep shared delivery behavior authoritative in `FindingNotificationService.php` before duplicating logic in `FindingWorkflowService.php` or `EvaluateAlertsJob.php`.
|
||||
- Finish story-level verification before moving to the next priority slice.
|
||||
|
||||
### Parallel Opportunities
|
||||
|
||||
- `T001`, `T002`, and `T003` can run in parallel during Setup.
|
||||
- `T009` and `T010` can run in parallel for User Story 1.
|
||||
- `T014` and `T015` can run in parallel for User Story 2.
|
||||
- `T020` and `T021` can run in parallel for User Story 3.
|
||||
|
||||
---
|
||||
|
||||
## Parallel Example: User Story 1
|
||||
|
||||
```bash
|
||||
# User Story 1 tests in parallel
|
||||
T009 apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php
|
||||
T010 apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php
|
||||
```
|
||||
|
||||
## Parallel Example: User Story 2
|
||||
|
||||
```bash
|
||||
# User Story 2 tests in parallel
|
||||
T014 apps/platform/tests/Feature/Findings/FindingsNotificationEventTest.php
|
||||
T015 apps/platform/tests/Feature/Findings/FindingsNotificationRoutingTest.php
|
||||
```
|
||||
|
||||
## Parallel Example: User Story 3
|
||||
|
||||
```bash
|
||||
# User Story 3 surface work in parallel
|
||||
T020 apps/platform/app/Filament/Resources/AlertRuleResource.php
|
||||
T021 apps/platform/app/Filament/Resources/AlertDeliveryResource.php
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### MVP First (User Story 1 Only)
|
||||
|
||||
1. Complete Phase 1: Setup.
|
||||
2. Complete Phase 2: Foundational.
|
||||
3. Complete Phase 3: User Story 1.
|
||||
4. Validate the feature against the focused US1 tests before widening the slice.
|
||||
|
||||
### Incremental Delivery
|
||||
|
||||
1. Ship US1 to close the direct assignment and automatic-reopen feedback gap.
|
||||
2. Add US2 to turn due dates into actionable reminders and overdue escalation.
|
||||
3. Add US3 to let workspace teams configure optional external copies through the existing Alerts UI.
|
||||
4. Finish with copy review, formatting, and the focused verification pack.
|
||||
|
||||
### Parallel Team Strategy
|
||||
|
||||
1. One contributor can scaffold the shared service and notification class while another prepares the focused Pest suites.
|
||||
2. After Foundational work lands, one contributor can wire workflow-event production while another implements due-evaluation logic.
|
||||
3. Alert-rule and delivery-viewer surface work can proceed in parallel with direct-delivery trigger work once the shared event vocabulary is stable.
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- `[P]` tasks target different files and can be worked independently once upstream blockers are cleared.
|
||||
- `[US1]`, `[US2]`, and `[US3]` map directly to the feature specification user stories.
|
||||
- The suggested MVP scope is Phase 1 through Phase 3 only.
|
||||
- All implementation tasks above follow the required checklist format with task ID, optional parallel marker, story label where applicable, and exact file paths.
|
||||
Loading…
Reference in New Issue
Block a user