simedkom/app/Console/Commands/MigrateDepartmentCommand.php

92 lines
2.6 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\IsActive;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class MigrateDepartmentCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:department';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate department data from legacy agencies table with optimized processing';
/**
* Store migrated record IDs to optimize processing.
*/
private array $migratedIds = [];
/**
* Execute the console command.
*/
public function handle()
{
$this->info('Starting optimized department migration...');
$legacyConn = DB::connection('mysql_second');
$query = $legacyConn->table('agencies');
$totalCount = $query->count();
if ($totalCount === 0) {
$this->warn('No departments found in legacy database.');
return;
}
$this->info("Found {$totalCount} legacy department records.");
// Cache existing IDs for faster processing
$this->migratedIds = DB::table('departments')->pluck('id')->flip()->all();
$query->orderBy('id')->chunk(50, function ($chunk) {
foreach ($chunk as $legacy) {
$this->processDepartment($legacy);
}
});
$this->newLine();
$this->info('Department migration completed successfully!');
}
/**
* Process a single legacy department record.
*/
private function processDepartment($legacy): void
{
$idText = "[#{$legacy->id}]";
$idOutput = $legacy->deleted_at ? "<fg=red>{$idText}</>" : "<info>{$idText}</info>";
$this->output->write("{$idOutput} Processing: <comment>".Str::limit($legacy->name, 40).'</comment>... ');
try {
DB::table('departments')->updateOrInsert(
['id' => $legacy->id],
[
'name' => $legacy->name,
'alias' => Str::limit($legacy->name, 20, ''),
'is_active' => IsActive::ACTIVE->value,
'created_at' => $legacy->created_at ?? now(),
'updated_at' => $legacy->updated_at ?? now(),
'deleted_at' => $legacy->deleted_at,
]
);
$this->output->writeln('<info>DONE</info>');
} catch (\Exception $e) {
$this->output->writeln('<error>FAILED: '.$e->getMessage().'</error>');
}
}
}