parfum/app/Console/Commands/Migrations/MigrateUsersFromOldData.php
Yoga Pangestu 3a05ee2617 feat: implement comprehensive migration commands for legacy data
- Added migration commands for users, employees, outlets, categories, products, bottles, and perfumes to transfer data from the old database to the new structure.
- Each command includes options for forced migration and recreation of existing records.
- Implemented progress feedback and error handling during migration processes.
- Updated database configuration to include connection settings for the old database.
- Enhanced DatabaseSeeder to automatically trigger the migration process after seeding essential data.
2026-01-10 19:04:31 +07:00

171 lines
5.0 KiB
PHP

<?php
namespace App\Console\Commands\Migrations;
use App\Enums\UserStatus;
use App\Models\Outlet;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
class MigrateUsersFromOldData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:users {--force : Force migration without confirmation}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate users data from old database to new structure';
/**
* Execute the console command.
*/
public function handle()
{
if (! $this->option('force') && ! $this->confirm('Are you sure you want to migrate users data? This will add new users to your database.')) {
$this->info('Migration cancelled.');
return;
}
$this->info('Starting users migration...');
// Ensure roles exist
$this->ensureRolesExist();
try {
// Filter users yang tidak memiliki end_date (masih aktif)
$oldUsers = DB::connection('old_database')
->table('users')
->whereNull('out_date')
->whereNull('deleted_at')
->get();
$this->info("Found {$oldUsers->count()} active users to migrate.");
$bar = $this->output->createProgressBar($oldUsers->count());
$migrated = 0;
$skipped = 0;
foreach ($oldUsers as $oldUser) {
$existingUser = User::where('email', $oldUser->email)->first();
if ($existingUser) {
$this->warn("User with email {$oldUser->email} already exists, skipping...");
$skipped++;
$bar->advance();
continue;
}
$user = User::create([
'email' => $oldUser->email,
'username' => $this->generateUsername($oldUser->email),
'password' => Hash::make(config('myconfig.password_default')),
'status' => UserStatus::ACTIVE,
'email_verified_at' => now(),
'created_at' => $oldUser->created_at,
'updated_at' => $oldUser->updated_at,
]);
// Assign role based on role_id
$roleId = $this->mapRoleId($oldUser->role_id);
if ($roleId) {
$user->assignRole($roleId);
}
// Create outlet relation if store_id exists
if ($oldUser->store_id) {
// Map old store_id to new outlet_id
$outletMapping = $this->getOutletMapping();
$outletId = $outletMapping[$oldUser->store_id] ?? null;
if ($outletId) {
// Create many-to-many relation
DB::table('outlet_user')->insert([
'outlet_id' => $outletId,
'user_id' => $user->id,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
$migrated++;
$bar->advance();
}
$bar->finish();
$this->newLine(2);
$this->info('✅ Users migration completed!');
$this->info("📊 Migrated: {$migrated} users");
$this->info("⏭️ Skipped: {$skipped} users (already exist)");
} catch (\Exception $e) {
$this->error("❌ Migration failed: {$e->getMessage()}");
return 1;
}
return 0;
}
private function generateUsername(string $email): string
{
$username = explode('@', $email)[0];
$baseUsername = $username;
$counter = 1;
while (User::where('username', $username)->exists()) {
$username = $baseUsername.$counter;
$counter++;
}
return $username;
}
private function mapRoleId(int $oldRoleId): ?string
{
return match ($oldRoleId) {
1 => 'Owner',
2 => 'Leader',
3 => 'Admin',
default => null,
};
}
private function ensureRolesExist(): void
{
$roles = ['Owner', 'Leader', 'Admin'];
foreach ($roles as $roleName) {
Role::firstOrCreate(['name' => $roleName]);
}
$this->info('Roles verified/created successfully.');
}
private function getOutletMapping(): array
{
// Map old store_id to new outlet_id
// This assumes outlets have been migrated first
$outlets = Outlet::select('id')->orderBy('id')->get();
$mapping = [];
foreach ($outlets as $index => $outlet) {
$mapping[$index + 1] = $outlet->id; // Old store_id starts from 1
}
return $mapping;
}
}