A free open source IT asset/license management system
Added migration to backfill dates into new table
snipe021bd9dab8e5
diff --git a/app/Console/Commands/ReconcileCalendarEvents.php b/app/Console/Commands/ReconcileCalendarEvents.phpnew file mode 100644index 0000000000..76c13c5f82--- /dev/null+++ b/app/Console/Commands/ReconcileCalendarEvents.php@@ -0,0 +1,180 @@+<?php++namespace App\Console\Commands;++use App\Models\CalendarEvent;+use App\Models\Traits\HasCalendarEvents;+use Illuminate\Console\Command;+use Illuminate\Database\Eloquent\Model;++/**+ * Reconciles the calendar_events index against every source model+ * that uses the HasCalendarEvents trait.+ *+ * The observer keeps rows in sync on live saves, but drift can still+ * happen from:+ * - Direct DB edits that bypass Eloquent (raw SQL, migrations+ * that touch date columns, restored backups).+ * - Missed observer fires (queue jobs that ->save() then throw+ * between save and observer completion in pre-Laravel-12+ * versions).+ * - New sources added after existing data was already in place -+ * nothing published events until the trait was added; this+ * command backfills them.+ * - Orphan rows whose source was hard-deleted while the observer+ * was down (rare, but the reconcile also cleans these).+ *+ * Sources are discovered by walking app/Models for classes that use+ * the trait. Each source is chunked to keep memory flat on large+ * installs.+ *+ * Idempotent - safe to schedule (e.g. nightly) alongside the observer.+ */+class ReconcileCalendarEvents extends Command+{+ protected $signature = 'snipeit:reconcile-calendar-events+ {--source= : Fully-qualified class name of a single source to reconcile, if you don\'t want to walk everything}+ {--dry-run : Report the counts of what would change without writing}';++ protected $description = 'Rebuilds the calendar_events index from source model date columns.';++ public function handle(): int+ {+ $sources = $this->discoverSources();+ if (empty($sources)) {+ $this->warn('No models use the HasCalendarEvents trait. Nothing to reconcile.');++ return self::SUCCESS;+ }++ $dryRun = (bool) $this->option('dry-run');+ $totalUpserts = 0;+ $totalOrphans = 0;++ foreach ($sources as $sourceClass) {+ $this->info(sprintf('Reconciling %s ...', $sourceClass));++ [$upserts, $orphans] = $this->reconcileSource($sourceClass, $dryRun);+ $totalUpserts += $upserts;+ $totalOrphans += $orphans;++ $this->line(sprintf(+ ' %s: %d source rows synced, %d orphan calendar_events %s',+ class_basename($sourceClass),+ $upserts,+ $orphans,+ $dryRun ? 'would be removed' : 'removed',+ ));+ }++ $this->newLine();+ $this->info(sprintf(+ 'Done. %d syncs, %d orphans %s.',+ $totalUpserts,+ $totalOrphans,+ $dryRun ? '(dry run)' : 'processed',+ ));++ return self::SUCCESS;+ }++ /**+ * @return array{0: int, 1: int} [upsert count, orphan count]+ */+ protected function reconcileSource(string $sourceClass, bool $dryRun): array+ {+ $upserts = 0;+ $orphans = 0;++ // Sync path: walk every live source row and force-sync its+ // calendar_events. force=true bypasses the observer's+ // "did any declared field change" gate so drifted-in-place+ // date values get corrected.+ $sourceClass::query()+ ->when(+ in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses_recursive($sourceClass), true),+ fn ($q) => $q->withTrashed(),+ )+ ->chunkById(500, function ($rows) use (&$upserts, $dryRun) {+ foreach ($rows as $row) {+ if (! $dryRun) {+ $row->forceSyncCalendarEvents();+ }+ $upserts++;+ }+ });++ // Orphan sweep: any calendar_events pointing at a+ // source_type / source_id that no longer resolves to a row+ // (even a trashed one) is unreachable. Batches at 500 to+ // keep DELETE statements bounded.+ CalendarEvent::withTrashed()+ ->where('source_type', $sourceClass)+ ->chunkById(500, function ($events) use ($sourceClass, &$orphans, $dryRun) {+ $ids = $events->pluck('source_id')->all();+ $existingIds = $sourceClass::query()+ ->when(+ in_array(\Illuminate\Database\Eloquent\SoftDeletes::class, class_uses_recursive($sourceClass), true),+ fn ($q) => $q->withTrashed(),+ )+ ->whereIn('id', $ids)+ ->pluck('id')+ ->all();++ $orphanEvents = $events->filter(fn ($e) => ! in_array($e->source_id, $existingIds, true));+ $orphans += $orphanEvents->count();++ if (! $dryRun && $orphanEvents->isNotEmpty()) {+ CalendarEvent::withTrashed()+ ->whereIn('id', $orphanEvents->pluck('id')->all())+ ->forceDelete();+ }+ });++ return [$upserts, $orphans];+ }++ /**+ * Discover source classes by walking app/Models and picking any+ * that use HasCalendarEvents. Explicit --source overrides the+ * scan for targeted reconciles (e.g. after a bulk import touched+ * one model).+ */+ protected function discoverSources(): array+ {+ if ($single = $this->option('source')) {+ if (! class_exists($single)) {+ $this->error(sprintf('%s not found. Pass a fully-qualified class name.', $single));++ return [];+ }++ return [$single];+ }++ $sources = [];+ $modelDir = app_path('Models');+ $files = glob($modelDir.'/*.php');+ foreach ($files as $file) {+ $class = 'App\\Models\\'.pathinfo($file, PATHINFO_FILENAME);+ if (! class_exists($class)) {+ continue;+ }++ $reflection = new \ReflectionClass($class);+ if ($reflection->isAbstract() || $reflection->isInterface() || $reflection->isTrait()) {+ continue;+ }+ if (! is_subclass_of($class, Model::class)) {+ continue;+ }+ if (in_array(HasCalendarEvents::class, class_uses_recursive($class), true)) {+ $sources[] = $class;+ }+ }++ sort($sources);++ return $sources;+ }+}diff --git a/database/migrations/2026_08_13_160000_create_calendar_events_table.php b/database/migrations/2026_08_13_160000_create_calendar_events_table.phpnew file mode 100644index 0000000000..5f7fa23102--- /dev/null+++ b/database/migrations/2026_08_13_160000_create_calendar_events_table.php@@ -0,0 +1,65 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++/**+ * Polymorphic index of "when did what happen" across every source+ * model that opts in via HasCalendarEvents. The table stores only+ * the dates + a pointer back to the source row + a categorization+ * key for filter buttons on the calendar UI. Everything else (name,+ * url, color, badges) is resolved live from the source model at read+ * time via its presenter so this table stays free of drift-prone+ * denormalized fields.+ *+ * Sources register their date columns via the trait's+ * calendarEventDefinitions() method. The observer keeps rows in+ * sync on source save / delete / restore, and the+ * snipeit:reconcile-calendar-events command sweeps date drift plus+ * heals any orphans on demand.+ *+ * Composite unique on (source_type, source_id, source_field) is what+ * the observer upserts against - a single source can contribute+ * multiple rows (e.g. Maintenance publishes both start_date and+ * expected_completion_date events), one per declared field.+ */+return new class extends Migration+{+ public function up(): void+ {+ Schema::create('calendar_events', function (Blueprint $table) {+ $table->id();++ $table->string('source_type');+ $table->unsignedBigInteger('source_id');+ $table->string('source_field');++ $table->string('event_type');++ $table->dateTime('start');+ $table->dateTime('end')->nullable();++ $table->timestamps();+ $table->softDeletes();++ // Upsert / delete lookup used by the observer on every+ // source save. Unique because a source can only publish+ // one event per field.+ $table->unique(+ ['source_type', 'source_id', 'source_field'],+ 'calendar_events_source_unique'+ );++ // Read path filter: WHERE event_type IN (...) AND start+ // BETWEEN ? AND ?. Composite lets the planner satisfy both+ // predicates from the index.+ $table->index(['event_type', 'start'], 'calendar_events_type_start_index');+ });+ }++ public function down(): void+ {+ Schema::dropIfExists('calendar_events');+ }+};diff --git a/database/migrations/2026_08_13_160100_backfill_calendar_events_from_existing_sources.php b/database/migrations/2026_08_13_160100_backfill_calendar_events_from_existing_sources.phpnew file mode 100644index 0000000000..0048058fc1--- /dev/null+++ b/database/migrations/2026_08_13_160100_backfill_calendar_events_from_existing_sources.php@@ -0,0 +1,83 @@+<?php++use App\Models\Traits\HasCalendarEvents;+use Illuminate\Database\Eloquent\Model;+use Illuminate\Database\Eloquent\SoftDeletes;+use Illuminate\Database\Migrations\Migration;++/**+ * One-shot backfill of the calendar_events index for every source+ * model that uses HasCalendarEvents at the time this migration runs.+ * Walks the sources, chunks the rows, and force-syncs each so their+ * declared date columns land as calendar_events rows.+ *+ * On a fresh install the source tables are usually empty at this+ * point (this migration runs early), so the backfill is a no-op and+ * the observer takes over from there. On an upgrade from an install+ * that already has maintenances / audits / etc., the backfill+ * populates the index so those existing records show up on the+ * calendar without waiting for a manual save on each one.+ *+ * Duplicates snipeit:reconcile-calendar-events's sync logic on+ * purpose - the command is meant to be re-runnable on demand later,+ * this migration is the one-time seed at deploy time. Kept small+ * enough that no shared helper class is needed between them.+ */+return new class extends Migration+{+ public function up(): void+ {+ foreach ($this->discoverSources() as $sourceClass) {+ $this->backfillSource($sourceClass);+ }+ }++ public function down(): void+ {+ // No-op. The calendar_events table gets dropped by the+ // create-table migration's down(); trying to un-backfill+ // individual rows here would just reset the index to an+ // empty state that the observer would immediately fill on+ // the next source save anyway.+ }++ protected function backfillSource(string $sourceClass): void+ {+ $sourceClass::query()+ ->when(+ in_array(SoftDeletes::class, class_uses_recursive($sourceClass), true),+ fn ($q) => $q->withTrashed(),+ )+ ->chunkById(500, function ($rows) {+ foreach ($rows as $row) {+ $row->forceSyncCalendarEvents();+ }+ });+ }++ protected function discoverSources(): array+ {+ $sources = [];+ $modelDir = app_path('Models');+ $files = glob($modelDir.'/*.php');+ foreach ($files as $file) {+ $class = 'App\\Models\\'.pathinfo($file, PATHINFO_FILENAME);+ if (! class_exists($class)) {+ continue;+ }++ $reflection = new \ReflectionClass($class);+ if ($reflection->isAbstract() || $reflection->isInterface() || $reflection->isTrait()) {+ continue;+ }+ if (! is_subclass_of($class, Model::class)) {+ continue;+ }+ if (in_array(HasCalendarEvents::class, class_uses_recursive($class), true)) {+ $sources[] = $class;+ }+ }++ return $sources;+ }+};diff --git a/database/migrations/2026_08_13_170000_backfill_calendar_events_for_new_sources.php b/database/migrations/2026_08_13_170000_backfill_calendar_events_for_new_sources.phpnew file mode 100644index 0000000000..c174d59c92--- /dev/null+++ b/database/migrations/2026_08_13_170000_backfill_calendar_events_for_new_sources.php@@ -0,0 +1,74 @@+<?php++use App\Models\Traits\HasCalendarEvents;+use Illuminate\Database\Eloquent\Model;+use Illuminate\Database\Eloquent\SoftDeletes;+use Illuminate\Database\Migrations\Migration;++/**+ * Second-pass backfill for calendar_events. The first backfill+ * migration ran when only Maintenance used HasCalendarEvents; this+ * one runs after Asset / License / User adopted the trait so any+ * install that already applied the earlier migration also picks up+ * the new sources without a manual reconcile.+ *+ * Same discover-and-force-sync logic as the first backfill: idempotent+ * on rows that already have an index entry (updateOrCreate-shaped+ * lookup in the trait uses withTrashed to sidestep the unique+ * constraint even for restored rows), so re-running for+ * already-synced Maintenance rows is a no-op.+ */+return new class extends Migration+{+ public function up(): void+ {+ foreach ($this->discoverSources() as $sourceClass) {+ $this->backfillSource($sourceClass);+ }+ }++ public function down(): void+ {+ // No-op. See sibling backfill migration.+ }++ protected function backfillSource(string $sourceClass): void+ {+ $sourceClass::query()+ ->when(+ in_array(SoftDeletes::class, class_uses_recursive($sourceClass), true),+ fn ($q) => $q->withTrashed(),+ )+ ->chunkById(500, function ($rows) {+ foreach ($rows as $row) {+ $row->forceSyncCalendarEvents();+ }+ });+ }++ protected function discoverSources(): array+ {+ $sources = [];+ $modelDir = app_path('Models');+ $files = glob($modelDir.'/*.php');+ foreach ($files as $file) {+ $class = 'App\\Models\\'.pathinfo($file, PATHINFO_FILENAME);+ if (! class_exists($class)) {+ continue;+ }++ $reflection = new \ReflectionClass($class);+ if ($reflection->isAbstract() || $reflection->isInterface() || $reflection->isTrait()) {+ continue;+ }+ if (! is_subclass_of($class, Model::class)) {+ continue;+ }+ if (in_array(HasCalendarEvents::class, class_uses_recursive($class), true)) {+ $sources[] = $class;+ }+ }++ return $sources;+ }+};