TenantAtlas/tests/Feature/Inventory/RunInventorySyncJobTest.php
ahmido 3030dd9af2 054-unify-runs-suitewide (#63)
Summary

Kurz: Implementiert Feature 054 — canonical OperationRun-flow, Monitoring UI, dispatch-safety, notifications, dedupe, plus small UX safety clarifications (RBAC group search delegated; Restore group mapping DB-only).
What Changed

Core service: OperationRun lifecycle, dedupe and dispatch helpers — OperationRunService.php.
Model + migration: OperationRun model and migration — OperationRun.php, 2026_01_16_180642_create_operation_runs_table.php.
Notifications: queued + terminal DB notifications (initiator-only) — OperationRunQueued.php, OperationRunCompleted.php.
Monitoring UI: Filament list/detail + Livewire pieces (DB-only render) — OperationRunResource.php and related pages/views.
Start surfaces / Jobs: instrumented start surfaces, job middleware, and job updates to use canonical runs — multiple app/Jobs/* and app/Filament/* updates (see tests for full coverage).
RBAC + Restore UX clarifications: RBAC group search is delegated-Graph-based and disabled without delegated token; Restore group mapping remains DB-only (directory cache) and helper text always visible — TenantResource.php, RestoreRunResource.php.
Specs / Constitution: updated spec & quickstart and added one-line constitution guideline about Graph usage:
spec.md
quickstart.md
constitution.md
Tests & Verification

Unit / Feature tests added/updated for run lifecycle, notifications, idempotency, and UI guards: see tests/Feature/* (notably OperationRunServiceTest, MonitoringOperationsTest, OperationRunNotificationTest, and various Filament feature tests).
Full test run locally: ./vendor/bin/sail artisan test → 587 passed, 5 skipped.
Migrations

Adds create_operation_runs_table migration; run php artisan migrate in staging after review.
Notes / Rationale

Monitoring pages are explicitly DB-only at render time (no Graph calls). Start surfaces enqueue work only and return a “View run” link.
Delegated Graph access is used only for explicit user actions (RBAC group search); restore mapping intentionally uses cached DB data only to avoid render-time Graph calls.
Dispatch wrapper marks runs failed immediately if background dispatch throws synchronously to avoid misleading “queued” states.
Upgrade / Deploy Considerations

Run migrations: ./vendor/bin/sail artisan migrate.
Background workers should be running to process queued jobs (recommended to monitor queue health during rollout).
No secret or token persistence changes.
PR checklist

 Tests updated/added for changed behavior
 Specs updated: 054-unify-runs-suitewide docs + quickstart
 Constitution note added (.specify)
 Pint formatting applied

Co-authored-by: Ahmed Darrazi <ahmeddarrazi@adsmac.local>
Reviewed-on: #63
2026-01-17 22:25:00 +00:00

122 lines
4.2 KiB
PHP

<?php
use App\Jobs\RunInventorySyncJob;
use App\Models\InventorySyncRun;
use App\Services\BulkOperationService;
use App\Services\Graph\GraphClientInterface;
use App\Services\Graph\GraphResponse;
use App\Services\Intune\AuditLogger;
use App\Services\Inventory\InventorySyncService;
use Mockery\MockInterface;
it('executes a pending inventory sync run and updates bulk progress + initiator attribution', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$this->mock(GraphClientInterface::class, function (MockInterface $mock) {
$mock->shouldReceive('listPolicies')
->atLeast()
->once()
->andReturn(new GraphResponse(true, [], 200));
});
$sync = app(InventorySyncService::class);
$selectionPayload = $sync->defaultSelectionPayload();
$computed = $sync->normalizeAndHashSelection($selectionPayload);
$policyTypes = $computed['selection']['policy_types'];
$run = $sync->createPendingRunForUser($tenant, $user, $computed['selection']);
$bulkRun = app(BulkOperationService::class)->createRun(
tenant: $tenant,
user: $user,
resource: 'inventory',
action: 'sync',
itemIds: $policyTypes,
totalItems: count($policyTypes),
);
$job = new RunInventorySyncJob(
tenantId: (int) $tenant->getKey(),
userId: (int) $user->getKey(),
bulkRunId: (int) $bulkRun->getKey(),
inventorySyncRunId: (int) $run->getKey(),
);
$job->handle(app(BulkOperationService::class), $sync, app(AuditLogger::class));
$run->refresh();
$bulkRun->refresh();
expect($run->user_id)->toBe($user->id);
expect($run->status)->toBe(InventorySyncRun::STATUS_SUCCESS);
expect($run->started_at)->not->toBeNull();
expect($run->finished_at)->not->toBeNull();
expect($bulkRun->status)->toBe('completed');
expect($bulkRun->failed)->toBe(0);
expect($bulkRun->skipped)->toBe(0);
expect($bulkRun->processed_items)->toBeGreaterThan(0);
expect($bulkRun->processed_items)->toBe($bulkRun->succeeded);
});
it('maps skipped inventory sync runs to bulk progress as skipped with reason', function () {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$sync = app(InventorySyncService::class);
$selectionPayload = $sync->defaultSelectionPayload();
$run = $sync->createPendingRunForUser($tenant, $user, $selectionPayload);
$computed = $sync->normalizeAndHashSelection($selectionPayload);
$policyTypes = $computed['selection']['policy_types'];
$run->update(['selection_payload' => $computed['selection']]);
$bulkRun = app(BulkOperationService::class)->createRun(
tenant: $tenant,
user: $user,
resource: 'inventory',
action: 'sync',
itemIds: $policyTypes,
totalItems: count($policyTypes),
);
$mockSync = \Mockery::mock(InventorySyncService::class);
$mockSync
->shouldReceive('executePendingRun')
->once()
->andReturnUsing(function (InventorySyncRun $inventorySyncRun) {
$inventorySyncRun->forceFill([
'status' => InventorySyncRun::STATUS_SKIPPED,
'error_codes' => ['locked'],
'selection_payload' => $inventorySyncRun->selection_payload ?? [],
'started_at' => now(),
'finished_at' => now(),
])->save();
return $inventorySyncRun;
});
$job = new RunInventorySyncJob(
tenantId: (int) $tenant->getKey(),
userId: (int) $user->getKey(),
bulkRunId: (int) $bulkRun->getKey(),
inventorySyncRunId: (int) $run->getKey(),
);
$job->handle(app(BulkOperationService::class), $mockSync, app(AuditLogger::class));
$run->refresh();
$bulkRun->refresh();
expect($run->status)->toBe(InventorySyncRun::STATUS_SKIPPED);
expect($bulkRun->status)->toBe('completed')
->and($bulkRun->processed_items)->toBe(count($policyTypes))
->and($bulkRun->skipped)->toBe(count($policyTypes))
->and($bulkRun->succeeded)->toBe(0)
->and($bulkRun->failed)->toBe(0);
expect($bulkRun->failures)->toBeArray();
expect($bulkRun->failures[0]['type'] ?? null)->toBe('skipped');
expect($bulkRun->failures[0]['reason'] ?? null)->toBe('locked');
});