80 lines
2.4 KiB
PHP
80 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\ClassSession;
|
|
use App\Models\CourseSchedule;
|
|
use App\Settings\GeneralSettings;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Database\QueryException;
|
|
|
|
class GenerateDailySessions extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'app:generate-daily-sessions';
|
|
|
|
protected $description = 'Membangun sesi kelas harian secara otomatis berdasarkan jadwal.';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle()
|
|
{
|
|
$dayOfWeek = now()->dayOfWeekIso;
|
|
$currentSemester = app(GeneralSettings::class)->current_semester;
|
|
|
|
$schedules = CourseSchedule::query()
|
|
->where('day_of_week', $dayOfWeek)
|
|
->whereHas('course', function ($query) use ($currentSemester) {
|
|
$query->where('semester', $currentSemester);
|
|
})
|
|
->get();
|
|
|
|
$count = 0;
|
|
foreach ($schedules as $schedule) {
|
|
$existingSession = ClassSession::withTrashed()
|
|
->where('course_id', $schedule->course_id)
|
|
->whereDate('date', today())
|
|
->first();
|
|
|
|
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' => 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/Restored {$count} sessions for ".today()->toDateString());
|
|
}
|
|
}
|