feat: enhance session generation logic to restore trashed sessions and handle duplicates

This commit is contained in:
Yoga Pangestu 2026-05-21 18:09:09 +07:00
parent 7ea60d4aa3
commit 7c5b279689

View File

@ -6,6 +6,7 @@
use App\Models\CourseSchedule;
use App\Settings\GeneralSettings;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
class GenerateDailySessions extends Command
{
@ -23,7 +24,7 @@ class GenerateDailySessions extends Command
*/
public function handle()
{
$dayOfWeek = now()->dayOfWeekIso; // 1 (Mon) - 7 (Sun)
$dayOfWeek = now()->dayOfWeekIso;
$currentSemester = app(GeneralSettings::class)->current_semester;
$schedules = CourseSchedule::query()
@ -35,24 +36,44 @@ public function handle()
$count = 0;
foreach ($schedules as $schedule) {
$exists = ClassSession::where('course_id', $schedule->course_id)
->whereDate('date', now())
->exists();
$existingSession = ClassSession::withTrashed()
->where('course_id', $schedule->course_id)
->whereDate('date', today())
->first();
if (! $exists) {
$lastSession = ClassSession::where('course_id', $schedule->course_id)->max('session_number');
if ($existingSession) {
if ($existingSession->trashed()) {
$existingSession->restore();
$this->info("Restored session for course_id {$schedule->course_id}");
$count++;
}
continue;
}
$lastSession = ClassSession::withTrashed()
->where('course_id', $schedule->course_id)
->max('session_number');
try {
ClassSession::create([
'course_id' => $schedule->course_id,
'session_number' => ($lastSession ?? 0) + 1,
'date' => now()->toDateString(),
'date' => today()->toDateString(),
'start_time' => $schedule->start_time,
'end_time' => $schedule->end_time,
]);
$count++;
} catch (QueryException $e) {
if ($e->errorInfo[1] === 1062) {
$this->warn("Skipped duplicate session for course_id {$schedule->course_id}");
continue;
}
throw $e;
}
}
$this->info("Generated {$count} sessions for ".now()->toDateString());
$this->info("Generated/Restored {$count} sessions for ".today()->toDateString());
}
}