Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
InstallWorkflowTemplateAction
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 2
72
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3declare(strict_types=1);
4
5namespace ImovelZapAi\Automation\Application\Actions;
6
7use App\Models\User;
8use ImovelZapAi\Automation\Domain\Enums\WorkflowStatus;
9use ImovelZapAi\Automation\Domain\Exceptions\AutomationException;
10use ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent\AutomationTemplateModel;
11use ImovelZapAi\Automation\Infrastructure\Persistence\Eloquent\AutomationWorkflowModel;
12
13final class InstallWorkflowTemplateAction
14{
15    public function __construct(
16        private readonly CreateWorkflowAction $createWorkflow,
17        private readonly ActivateWorkflowAction $activateWorkflow,
18    ) {}
19
20    public function execute(string $tenantId, User $user, string $slug, bool $activate = false): AutomationWorkflowModel
21    {
22        $template = AutomationTemplateModel::query()
23            ->where('slug', $slug)
24            ->where('is_active', true)
25            ->first();
26
27        if ($template === null) {
28            throw AutomationException::templateNotFound();
29        }
30
31        /** @var array<string, mixed>|null $definition */
32        $definition = is_array($template->definition) ? $template->definition : null;
33
34        if ($definition === null || empty($definition['trigger']['event_key'])) {
35            throw AutomationException::invalidState('modelo sem gatilho configurado.');
36        }
37
38        $workflow = $this->createWorkflow->execute($tenantId, $user, [
39            'name' => (string) ($definition['name'] ?? $template->name),
40            'description' => $definition['description'] ?? $template->description,
41            'status' => WorkflowStatus::Draft->value,
42            'trigger' => $definition['trigger'],
43            'conditions' => $definition['conditions'] ?? [],
44            'actions' => $definition['actions'] ?? [],
45        ]);
46
47        $workflow->forceFill(['is_template_clone' => true])->save();
48
49        if ($activate || (bool) ($definition['activate'] ?? false)) {
50            return $this->activateWorkflow->execute($tenantId, (string) $workflow->id);
51        }
52
53        return $workflow->fresh(['triggers', 'conditions', 'actions']);
54    }
55}