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; } }