LAR_Maintenance/app/Jobs/ScheduleNextMaintenance.php

67 lines
1.9 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);
$nextRunTime = Carbon::createFromTimestamp($cron->getNext());
if(MaintenanceHistory::where('hash', md5($maintenance->id . $nextRunTime))->first() !== null){
continue;
};
$maintenancePlanned = $maintenance->history()->create([
'start_at' => $nextRunTime,
'guestor_id' => $maintenance->guestor_id,
]);
$maintenancePlanned->refresh();
$hosts = $maintenance->hosts;
foreach ($hosts as $key => $host) {
$maintenancePlannedHost = $maintenancePlanned->historyHosts()->create([
'host_id' => $host->id
]);
$tasks = $maintenance->hosts->find($host->id)->tasks;
foreach ($tasks as $key => $task) {
$maintenancePlannedHost->historyTasks()->create([
'maintenance_task_id' => $task->id,
'maintenance_history_id' => $maintenancePlanned->id
]);
}
}
}
}
}