Files
2026-07-24 14:59:44 +01:00

47 lines
1.9 KiB
PHP

<?php
namespace Modules\Automation\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Modules\Automation\Contracts\ActionRegistry;
use Modules\Automation\Models\AutomationRun;
final class ExecuteAutomation implements ShouldQueue
{
use Dispatchable,InteractsWithQueue,Queueable,SerializesModels;
public function __construct(public readonly int $runId) {}
public function handle(ActionRegistry $actions): void
{
$run = AutomationRun::with('automation.steps')->findOrFail($this->runId);
$automation = $run->automation;
$run->update(['status' => 'running', 'started_at' => now()]);
try {
foreach ($automation->steps->where('is_enabled', true) as $step) {
$run->update(['current_step' => $step->position]);
try {
$result = $actions->execute($step, $run->payload ?? []);
$run->logs()->create(['automation_step_id' => $step->id, 'level' => 'info', 'message' => $step->name ?: $step->action_type.' completed', 'context' => $result, 'created_at' => now()]);
} catch (\Throwable $e) {
$run->logs()->create(['automation_step_id' => $step->id, 'level' => 'error', 'message' => $e->getMessage(), 'created_at' => now()]);
if ($automation->stop_on_failure) {
throw $e;
}
}
}
$run->update(['status' => 'completed', 'finished_at' => now()]);
} catch (\Throwable $e) {
$run->update(['status' => 'failed', 'error' => $e->getMessage(), 'finished_at' => now()]);
throw $e;
} finally {
$automation->increment('run_count');
$automation->update(['last_ran_at' => now()]);
}
}
}