TenantAtlas/app/Console/Commands/TenantpilotDispatchDirectoryGroupsSync.php
ahmido d6e7de597a feat(spec-087): remove legacy runs (#106)
Implements Spec 087: Legacy Runs Removal (rigorous).

### What changed
- Canonicalized run history: **`operation_runs` is the only run system** for inventory sync, Entra group sync, backup schedule execution/retention/purge.
- Removed legacy UI surfaces (Filament Resources / relation managers) for legacy run models.
- Legacy run URLs now return **404** (no redirects), with RBAC semantics preserved (404 vs 403 as specified).
- Canonicalized affected `operation_runs.type` values (dotted → underscore) via migration.
- Drift + inventory references now point to canonical operation runs; includes backfills and then drops legacy FK columns.
- Drops legacy run tables after cutover.
- Added regression guards to prevent reintroducing legacy run tokens or “backfilling” canonical runs from legacy tables.

### Migrations
- `2026_02_12_000001..000006_*` canonicalize types, add/backfill operation_run_id references, drop legacy columns, and drop legacy run tables.

### Tests
Focused pack for this spec passed:
- `tests/Feature/Guards/NoLegacyRunsTest.php`
- `tests/Feature/Guards/NoLegacyRunBackfillTest.php`
- `tests/Feature/Operations/LegacyRunRoutesNotFoundTest.php`
- `tests/Feature/Monitoring/MonitoringOperationsTest.php`
- `tests/Feature/Jobs/RunInventorySyncJobTest.php`

### Notes / impact
- Destructive cleanup is handled via migrations (drops legacy tables) after code cutover; deploy should run migrations in the same release.

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #106
2026-02-12 12:40:51 +00:00

128 lines
3.9 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Tenant;
use App\Services\OperationRunService;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
class TenantpilotDispatchDirectoryGroupsSync extends Command
{
protected $signature = 'tenantpilot:directory-groups:dispatch {--tenant=* : Limit to tenant_id/external_id}';
protected $description = 'Dispatch scheduled directory group sync runs (idempotent per tenant minute-slot).';
public function handle(): int
{
if (! (bool) config('directory_groups.schedule.enabled', false)) {
return self::SUCCESS;
}
$now = CarbonImmutable::now('UTC');
$timeUtc = (string) config('directory_groups.schedule.time_utc', '02:00');
if (! $this->isDueAt($now, $timeUtc)) {
return self::SUCCESS;
}
if (! class_exists(\App\Jobs\EntraGroupSyncJob::class)) {
$this->warn('EntraGroupSyncJob is not available; skipping scheduled directory group sync dispatch.');
return self::SUCCESS;
}
$tenantIdentifiers = array_values(array_filter(array_map('strval', array_merge(
(array) $this->option('tenant'),
(array) config('directory_groups.schedule.tenants', []),
))));
$tenants = $this->resolveTenants($tenantIdentifiers);
$selectionKey = 'groups-v1:all';
$slotKey = $now->format('YmdHi').'Z';
$created = 0;
$skipped = 0;
foreach ($tenants as $tenant) {
/** @var OperationRunService $opService */
$opService = app(OperationRunService::class);
$opRun = $opService->ensureRunWithIdentityStrict(
tenant: $tenant,
type: 'entra_group_sync',
identityInputs: [
'selection_key' => $selectionKey,
'slot_key' => $slotKey,
],
context: [
'selection_key' => $selectionKey,
'slot_key' => $slotKey,
'trigger' => 'scheduled',
],
initiator: null,
);
if (! $opRun->wasRecentlyCreated) {
$skipped++;
continue;
}
$created++;
dispatch(new \App\Jobs\EntraGroupSyncJob(
tenantId: $tenant->getKey(),
selectionKey: $selectionKey,
slotKey: $slotKey,
runId: null,
operationRun: $opRun,
));
}
$this->info(sprintf(
'Scanned %d tenant(s), created %d run(s), skipped %d duplicate run(s).',
$tenants->count(),
$created,
$skipped,
));
return self::SUCCESS;
}
/**
* @param array<int, string> $tenantIdentifiers
*/
private function resolveTenants(array $tenantIdentifiers): \Illuminate\Support\Collection
{
$query = Tenant::activeQuery();
if ($tenantIdentifiers !== []) {
$query->where(function ($subQuery) use ($tenantIdentifiers) {
foreach ($tenantIdentifiers as $identifier) {
if (ctype_digit($identifier)) {
$subQuery->orWhereKey((int) $identifier);
continue;
}
$subQuery->orWhere('tenant_id', $identifier)
->orWhere('external_id', $identifier);
}
});
}
return $query->get();
}
private function isDueAt(CarbonImmutable $now, string $timeUtc): bool
{
if (! preg_match('/^(?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d)$/', $timeUtc, $matches)) {
return false;
}
return (int) $matches['hour'] === (int) $now->format('H')
&& (int) $matches['minute'] === (int) $now->format('i');
}
}