LAR_Maintenance/app/Jobs/ScheduleNextMaintenance.php

59 lines
1.7 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\Maintenance;
use App\Models\MaintenanceHistory;
use App\Models\MaintenanceTaskHistory;
use Carbon\Carbon;
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;
use Poliander\Cron\CronExpression as CronCronExpression;
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) {
$cron = new CronCronExpression($maintenance->schedule);
$maintenancePlanned = $maintenance->history()->create([
'start_at' => Carbon::createFromTimestamp($cron->getNext()),
]);
$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
]);
}
}
}
}
}