LAR_Maintenance/app/Jobs/ScheduleNextMaintenance.php

67 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2024-07-31 15:04:33 +00:00
<?php
namespace App\Jobs;
use App\Models\Maintenance;
use App\Models\MaintenanceHistory;
2024-08-06 09:02:45 +00:00
use App\Models\MaintenanceTaskHistory;
2024-08-06 14:57:48 +00:00
use Carbon\Carbon;
2024-07-31 15:04:33 +00:00
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;
2024-08-06 14:57:48 +00:00
use Poliander\Cron\CronExpression as CronCronExpression;
2024-07-31 15:04:33 +00:00
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) {
2024-08-06 14:57:48 +00:00
$cron = new CronCronExpression($maintenance->schedule);
2024-08-16 16:20:45 +00:00
$nextRunTime = Carbon::createFromTimestamp($cron->getNext());
2024-08-16 21:37:42 +00:00
if(MaintenanceHistory::where('hash', md5($maintenance->id . $nextRunTime))->first() !== null){
2024-08-16 16:20:45 +00:00
continue;
};
2024-08-06 06:31:51 +00:00
$maintenancePlanned = $maintenance->history()->create([
2024-08-16 16:20:45 +00:00
'start_at' => $nextRunTime,
'guestor_id' => $maintenance->guestor_id,
2024-07-31 15:04:33 +00:00
]);
2024-09-10 13:17:13 +00:00
2024-08-06 06:31:51 +00:00
$maintenancePlanned->refresh();
2024-08-06 09:02:45 +00:00
$hosts = $maintenance->hosts;
foreach ($hosts as $key => $host) {
$maintenancePlannedHost = $maintenancePlanned->historyHosts()->create([
'host_id' => $host->id
]);
2024-08-07 19:45:21 +00:00
$tasks = $maintenance->hosts->find($host->id)->tasks;
2024-08-06 06:31:51 +00:00
foreach ($tasks as $key => $task) {
2024-08-06 09:02:45 +00:00
$maintenancePlannedHost->historyTasks()->create([
'maintenance_task_id' => $task->id,
'maintenance_history_id' => $maintenancePlanned->id
2024-08-06 06:31:51 +00:00
]);
}
}
2024-07-31 15:04:33 +00:00
}
}
}