diff --git a/app/Console/Commands/FixWoCompanyCommand.php b/app/Console/Commands/FixWoCompanyCommand.php new file mode 100644 index 0000000..9739462 --- /dev/null +++ b/app/Console/Commands/FixWoCompanyCommand.php @@ -0,0 +1,93 @@ +argument('target_slug'); + $dryRun = $this->option('dry-run'); + + $target = DB::table('companies')->where('slug', $slug)->first(); + if (! $target) { + $this->error("Compania '{$slug}' nu există."); + $this->showCompanies(); + return; + } + + $this->info("Compania țintă: [{$target->id}] {$target->name} (slug={$target->slug})"); + $this->newLine(); + + // Show all WOs grouped by company + $this->info('=== Toate fișele din sistem (grupate pe companie) ==='); + $all = DB::table('work_orders') + ->whereNull('deleted_at') + ->selectRaw('company_id, count(*) as cnt, group_concat(number, ", ") as numbers') + ->groupBy('company_id') + ->get(); + + $wrongIds = []; + foreach ($all as $row) { + $c = DB::table('companies')->where('id', $row->company_id)->first(); + $label = $c ? "[{$c->id}] {$c->name} (slug={$c->slug})" : "[{$row->company_id}] COMPANIE INEXISTENTĂ"; + $isTarget = $row->company_id === $target->id ? ' ← CORECT' : ' ← GREȘIT'; + $this->line(" company_id={$row->company_id} count={$row->cnt}{$isTarget}"); + $this->line(" Numere: {$row->numbers}"); + $this->line(" Companie: {$label}"); + $this->newLine(); + + if ($row->company_id !== $target->id) { + $wrongIds[] = $row->company_id; + } + } + + if (empty($wrongIds)) { + $this->info('✓ Toate fișele au deja company_id corect. Nu e nimic de mutat.'); + return; + } + + $wrongWos = DB::table('work_orders') + ->whereNull('deleted_at') + ->whereIn('company_id', $wrongIds) + ->get(['id', 'number', 'company_id']); + + $this->warn("Fișe cu company_id greșit: {$wrongWos->count()}"); + foreach ($wrongWos as $w) { + $this->line(" id={$w->id} #{$w->number} company_id actual={$w->company_id} → va deveni {$target->id}"); + } + $this->newLine(); + + if ($dryRun) { + $this->warn('--dry-run activ. Nicio modificare nu a fost făcută.'); + $this->line('Rulează fără --dry-run pentru a aplica.'); + return; + } + + if (! $this->confirm("Muți {$wrongWos->count()} fișe în compania [{$target->id}] {$target->name}?")) { + $this->line('Anulat.'); + return; + } + + $updated = DB::table('work_orders') + ->whereNull('deleted_at') + ->whereIn('company_id', $wrongIds) + ->update(['company_id' => $target->id]); + + $this->info("✓ {$updated} fișe mutate în company_id={$target->id}."); + } + + private function showCompanies(): void + { + $this->line('Companii disponibile:'); + DB::table('companies')->get(['id', 'slug', 'name'])->each( + fn ($c) => $this->line(" id={$c->id} slug={$c->slug} name={$c->name}") + ); + } +}