move into sonardesk
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Automation\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Modules\Automation\Contracts\ActionRegistry;
|
||||
use Modules\Automation\Models\AutomationStep;
|
||||
|
||||
final class AutomationActionRegistry implements ActionRegistry
|
||||
{
|
||||
public function all(): array
|
||||
{
|
||||
return [
|
||||
'log' => ['label' => 'Write log', 'fields' => ['message']],
|
||||
'webhook' => ['label' => 'Send webhook', 'fields' => ['url', 'method']],
|
||||
'email' => ['label' => 'Send email', 'fields' => ['to', 'subject', 'body']],
|
||||
'delay' => ['label' => 'Delay', 'fields' => ['seconds']],
|
||||
];
|
||||
}
|
||||
|
||||
public function execute(AutomationStep $step, array $payload): array
|
||||
{
|
||||
$config = $step->configuration ?? [];
|
||||
|
||||
return match ($step->action_type) {
|
||||
'log' => $this->log($config, $payload),
|
||||
'webhook' => $this->webhook($config, $payload),
|
||||
'email' => $this->email($config, $payload),
|
||||
'delay' => $this->delay($config),
|
||||
default => throw new \InvalidArgumentException("Unknown automation action [{$step->action_type}]."),
|
||||
};
|
||||
}
|
||||
|
||||
private function log(array $config, array $payload): array
|
||||
{
|
||||
$message = (string) ($config['message'] ?? 'Automation executed');
|
||||
Log::info($message, $payload);
|
||||
|
||||
return ['message' => $message];
|
||||
}
|
||||
|
||||
private function webhook(array $config, array $payload): array
|
||||
{
|
||||
$url = (string) ($config['url'] ?? '');
|
||||
if ($url === '') {
|
||||
throw new \InvalidArgumentException('Webhook URL is required.');
|
||||
}
|
||||
$method = strtolower((string) ($config['method'] ?? 'post'));
|
||||
$response = Http::timeout(config('automation.webhook_timeout', 10))->send($method, $url, ['json' => $payload]);
|
||||
$response->throw();
|
||||
|
||||
return ['status' => $response->status()];
|
||||
}
|
||||
|
||||
private function email(array $config, array $payload): array
|
||||
{
|
||||
$to = (string) ($config['to'] ?? '');
|
||||
if ($to === '') {
|
||||
throw new \InvalidArgumentException('Email recipient is required.');
|
||||
}
|
||||
$subject = (string) ($config['subject'] ?? 'Automation notification');
|
||||
$body = (string) ($config['body'] ?? json_encode($payload, JSON_PRETTY_PRINT));
|
||||
Mail::raw($body, fn ($message) => $message->to($to)->subject($subject));
|
||||
|
||||
return ['to' => $to];
|
||||
}
|
||||
|
||||
private function delay(array $config): array
|
||||
{
|
||||
$seconds = max(0, min(30, (int) ($config['seconds'] ?? 1)));
|
||||
if ($seconds > 0) {
|
||||
sleep($seconds);
|
||||
}
|
||||
|
||||
return ['seconds' => $seconds];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user