Files

94 lines
3.6 KiB
PHP
Raw Permalink Normal View History

2026-05-30 22:15:16 +07:00
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\QuestionBank;
use App\Models\User;
class MigrateOldQuestions extends Command
{
protected $signature = 'lms:migrate-questions';
protected $description = 'Menyalin data soal dari lmsv2-old.questions ke lmsv2.question_banks secara presisi';
public function handle()
{
$this->info('Memulai Sinkronisasi Bank Soal dari Database Lama...');
$oldQuestions = DB::table('lmsv2-old.questions')->get();
if ($oldQuestions->isEmpty()) {
$this->warn('Tidak ada data di tabel lmsv2-old.questions!');
return;
}
$bar = $this->output->createProgressBar(count($oldQuestions));
$bar->start();
$successCount = 0;
foreach ($oldQuestions as $old) {
// 1. Pemetaan Tipe Soal
$type = 'single';
$oldType = strtolower($old->question_type ?? '');
if (str_contains($oldType, 'multiple')) { $type = 'multiple'; }
elseif (str_contains($oldType, 'true') || str_contains($oldType, 'boolean')) { $type = 'true_false'; }
elseif (str_contains($oldType, 'desc') || str_contains($oldType, 'essay')) { $type = 'descriptive'; }
// 2. Pemetaan Level
$level = 'sedang';
$oldLevel = strtolower($old->level ?? '');
if (str_contains($oldLevel, 'mudah') || str_contains($oldLevel, 'easy')) { $level = 'mudah'; }
elseif (str_contains($oldLevel, 'sulit') || str_contains($oldLevel, 'hard')) { $level = 'sulit'; }
// 3. Pemetaan Pembuat (Creator)
$creatorId = null;
if (isset($old->staff_id)) {
$oldStaff = DB::table('lmsv2-old.staff')->where('id', $old->staff_id)->first();
if ($oldStaff && !empty($oldStaff->email)) {
$user = User::where('email', $oldStaff->email)->first();
if ($user) $creatorId = $user->id;
}
}
// 4. Penanganan Kunci Jawaban (Karena di Model di-cast sebagai Array)
$correctAnswer = null;
if (!empty($old->correct)) {
// Dibungkus ke dalam array agar tidak error saat Laravel mencoba json_encode
$correctAnswer = [$old->correct];
}
// 5. Simpan menggunakan format nama kolom yang BARU
QuestionBank::updateOrCreate(
['old_id' => $old->id], // Pencocokan menggunakan old_id
[
'question_type' => $type,
'question_level' => $level,
'question_text' => $old->question,
// Opsi A sampai E
'option_a' => $old->opt_a,
'option_b' => $old->opt_b,
'option_c' => $old->opt_c,
'option_d' => $old->opt_d,
'option_e' => $old->opt_e,
'correct_answer' => $correctAnswer, // Sudah dalam bentuk array
'created_by' => $creatorId,
'created_at' => $old->created_at ?? now(),
'updated_at' => $old->updated_at ?? now(),
]
);
$successCount++;
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info("Sinkronisasi Selesai! Berhasil memindahkan {$successCount} Soal beserta kunci jawabannya.");
}
}