LAR_Maintenance/app/Jobs/ScheduleNextMaintenance.php
2024-08-06 11:02:45 +02:00

64 lines
1.8 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\Maintenance;
use App\Models\MaintenanceHistory;
use App\Models\MaintenanceTaskHistory;
use Cron\CronExpression;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ScheduleNextMaintenance implements ShouldQueue
{
use Queueable;
/**
* Create a new job instance.
*/
public function __construct()
{
//
}
/**
* Execute the job.
*/
public function handle(): void
{
$maintenances = Maintenance::all();
foreach ($maintenances as $maintenance) {
$valid = CronExpression::isValidExpression($maintenance->schedule);
if (!$valid) {
dd($maintenance->schedule);
return;
}
$cron = new CronExpression($maintenance->schedule);
$maintenancePlanned = $maintenance->history()->create([
'start_at' => $cron->getNextRunDate(null, 2)
]);
$maintenancePlanned->refresh();
$hosts = $maintenance->hosts;
foreach ($hosts as $key => $host) {
$maintenancePlannedHost = $maintenancePlanned->historyHosts()->create([
'host_id' => $host->id
]);
$tasks = $maintenance->tasks;
foreach ($tasks as $key => $task) {
$maintenancePlannedHost->historyTasks()->create([
'maintenance_task_id' => $task->id,
'maintenance_history_id' => $maintenancePlanned->id
]);
}
}
}
die();
}
}