74 lines
3.2 KiB
PHP
74 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use App\Models\User;
|
|
use Spatie\Permission\Models\Role;
|
|
|
|
class MigrateUsers extends Command
|
|
{
|
|
protected $signature = 'lms:migrate-users';
|
|
protected $description = 'Menggabungkan 65 Staff & 810 Students menjadi tabel Users terpadu dengan Role dinamis.';
|
|
|
|
public function handle()
|
|
{
|
|
// 1. Pastikan Role Tersedia
|
|
Role::firstOrCreate(['name' => 'trainer', 'guard_name' => 'web']);
|
|
Role::firstOrCreate(['name' => 'trainee', 'guard_name' => 'web']);
|
|
|
|
$this->info('1. Memproses 65 Data Staff (sebagai Trainer)...');
|
|
$staffs = DB::table('lmsv2-old.staff')->get();
|
|
|
|
foreach ($staffs as $staff) {
|
|
$email = !empty($staff->email) ? trim($staff->email) : 'staff_' . $staff->id . '@noemail.com';
|
|
|
|
// Gunakan email sebagai kunci penyatuan
|
|
$user = User::updateOrCreate(
|
|
['email' => $email],
|
|
[
|
|
// Gunakan 'name' dan 'surname' sesuai tabel staff lama
|
|
'first_name' => !empty($staff->name) ? trim($staff->name) : 'Staff ' . $staff->id,
|
|
'last_name' => !empty($staff->surname) ? trim($staff->surname) : '',
|
|
'password' => User::where('email', $email)->exists() ? User::where('email', $email)->value('password') : (!empty($staff->password) ? $staff->password : Hash::make('rahasia1234')),
|
|
'is_active' => $staff->status ?? 1,
|
|
]
|
|
);
|
|
$user->assignRole('trainer');
|
|
}
|
|
$this->info('Data Staff berhasil diproses!');
|
|
|
|
$this->info('2. Memproses 810 Data Students (sebagai Trainee)...');
|
|
$students = DB::table('lmsv2-old.students')->get();
|
|
$bar = $this->output->createProgressBar(count($students));
|
|
$bar->start();
|
|
|
|
foreach ($students as $student) {
|
|
$email = !empty($student->email) ? trim($student->email) : 'student_' . $student->id . '@noemail.com';
|
|
|
|
$user = User::updateOrCreate(
|
|
['email' => $email],
|
|
[
|
|
// Gunakan 'firstname' dan 'lastname' TANPA garis bawah
|
|
'first_name' => !empty($student->firstname) ? trim($student->firstname) : 'Student ' . $student->id,
|
|
'last_name' => !empty($student->lastname) ? trim($student->lastname) : '',
|
|
'old_id' => $student->id,
|
|
'password' => User::where('email', $email)->exists() ? User::where('email', $email)->value('password') : (!empty($student->password) ? $student->password : Hash::make('rahasia1234')),
|
|
'is_active' => $student->status ?? 1,
|
|
]
|
|
);
|
|
|
|
// Jika akun ini sebelumnya sudah jadi Staff (Trainer), ia akan mendapatkan Role Trainee JUGA! (Rangkap 2)
|
|
$user->assignRole('trainee');
|
|
$bar->advance();
|
|
}
|
|
|
|
$bar->finish();
|
|
$this->newLine();
|
|
|
|
$total = User::count();
|
|
$this->info("Migrasi Selesai! Total unik akun di sistem saat ini: $total User.");
|
|
}
|
|
} |