Tighten automation conventions: pagination, imports, i18n, enums

- Pagination: drop the perPage override from ListAutomations and the
  hardcoded page size from GetAutomationInvocations; both use
  config('app.pagination.default'). Document the rule in CLAUDE.md.
- Imports: import DomainException / InvalidArgumentException / Throwable
  instead of inline backslash references across the automation actions.
- i18n: move the hardcoded Fetch RSS and HTTP Request failure strings to
  automations.errors.* in all three locales.
- Publish: require scheduled_offset when mode is scheduled (validation)
  and drop the magic 60-minute default in the node. Fixes the required_if
  rules to reference the concrete node index instead of a wildcard that
  never resolved (also repairs the trigger cron rule).
- Condition handles: back the yes/no output handles with a shared
  Condition\Handle enum (PHP) and ConditionHandle const (TS).
This commit is contained in:
Paulo Castellano 2026-06-13 13:59:52 -03:00
parent 1b2ff23dff
commit 478cad9f27
19 changed files with 116 additions and 27 deletions

View file

@ -265,6 +265,8 @@ ## Pagination
- Always use normal pagination (`->paginate()`). NEVER use cursor pagination (`->cursorPaginate()`).
- All paginated lists must use Inertia's scroll pagination (`Inertia::scroll()` on the backend with `<InfiniteScroll>` on the frontend). NEVER use traditional page-based pagination with page links/buttons.
- The page size ALWAYS comes from `config('app.pagination.default')` — never a magic number, and never a `perPage`/`per_page` value supplied by the request or frontend. Action/service list methods must NOT accept a `$perPage` parameter; call `->paginate((int) config('app.pagination.default'))` directly.
- The only exception is the public REST API (`app/Http/Controllers/Api`), which uses its own fixed, documented page size (15) as a stable API contract.
## Form Validation

View file

@ -8,6 +8,7 @@
use App\Enums\Automation\Status;
use App\Models\Automation;
use App\Services\Automation\GenerateNodeValidator;
use DomainException;
class ActivateAutomation
{
@ -33,13 +34,13 @@ private function validate(Automation $automation): void
$triggers = collect($nodes)->where('type', 'trigger');
if ($triggers->count() !== 1) {
throw new \DomainException(__('automations.errors.must_have_one_trigger'));
throw new DomainException(__('automations.errors.must_have_one_trigger'));
}
$trigger = $triggers->first();
$hasTargetFromTrigger = collect($connections)->contains('source', $trigger['id']);
if (! $hasTargetFromTrigger) {
throw new \DomainException(__('automations.errors.trigger_must_be_connected'));
throw new DomainException(__('automations.errors.trigger_must_be_connected'));
}
foreach ($nodes as $node) {
@ -50,7 +51,7 @@ private function validate(Automation $automation): void
$issue = $this->generateValidator->issueFor((array) data_get($node, 'data', []));
if ($issue !== null) {
throw new \DomainException($issue);
throw new DomainException($issue);
}
}
}

View file

@ -26,6 +26,6 @@ public function __invoke(Automation $automation, ?string $status = null, ?string
->when($status !== null, fn ($query) => $query->where('status', $status))
->when($search !== null && $search !== '', fn ($query) => $query->whereLike('id', "%{$search}%"))
->latest()
->paginate(25);
->paginate((int) config('app.pagination.default'));
}
}

View file

@ -10,11 +10,11 @@
class ListAutomations
{
public function __invoke(Workspace $workspace, ?int $perPage = null): LengthAwarePaginator
public function __invoke(Workspace $workspace): LengthAwarePaginator
{
return Automation::query()
->where('workspace_id', $workspace->id)
->orderByDesc('created_at')
->paginate($perPage ?? (int) config('app.pagination.default'));
->paginate((int) config('app.pagination.default'));
}
}

View file

@ -5,9 +5,11 @@
namespace App\Actions\Automation\Node;
use App\DataTransferObjects\Automation\NodeRunResult;
use App\Enums\Automation\Condition\Handle;
use App\Enums\Automation\Condition\Operator;
use App\Models\AutomationRun;
use App\Services\Automation\ExpressionResolver;
use Throwable;
class RunConditionNode
{
@ -34,7 +36,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
return NodeRunResult::completed(
output: ['condition' => ['resolved_field' => $field, 'matched' => $matched]],
nextHandle: $matched ? 'yes' : 'no',
nextHandle: ($matched ? Handle::Yes : Handle::No)->value,
);
}
@ -49,7 +51,7 @@ private function safeRegexMatch(string $pattern, string $subject): bool
try {
$result = @preg_match($regex, $subject);
} catch (\Throwable) {
} catch (Throwable) {
return false;
}

View file

@ -6,6 +6,7 @@
use App\DataTransferObjects\Automation\NodeRunResult;
use App\Models\AutomationRun;
use InvalidArgumentException;
class RunDelayNode
{
@ -18,7 +19,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
'minutes' => now()->addMinutes($duration),
'hours' => now()->addHours($duration),
'days' => now()->addDays($duration),
default => throw new \InvalidArgumentException("Unknown delay unit: {$unit}"),
default => throw new InvalidArgumentException("Unknown delay unit: {$unit}"),
};
return NodeRunResult::sleep($until);

View file

@ -46,7 +46,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
$feedUrl = $this->resolver->resolve((string) data_get($config, 'feed_url', ''), $run->resolverContext());
if ($feedUrl === '') {
return NodeRunResult::failed('Fetch RSS node missing feed_url.');
return NodeRunResult::failed(__('automations.errors.fetch_rss_missing_url'));
}
try {
@ -61,7 +61,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
$response = Http::get($feedUrl);
if (! $response->successful()) {
return NodeRunResult::failed('Feed request failed.', ['status' => $response->status()]);
return NodeRunResult::failed(__('automations.errors.fetch_rss_request_failed'), ['status' => $response->status()]);
}
try {
@ -73,7 +73,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
'error' => $e->getMessage(),
]);
return NodeRunResult::failed('Malformed RSS feed.');
return NodeRunResult::failed(__('automations.errors.fetch_rss_malformed'));
}
$nodeId = (string) $run->current_node_id;

View file

@ -18,6 +18,7 @@
use App\Services\Automation\GenerateNodeValidator;
use App\Services\Image\PostImagePipeline;
use Illuminate\Support\Facades\Log;
use Throwable;
class RunGenerateNode
{
@ -224,7 +225,7 @@ private function humanize(Workspace $workspace, array $structured, string $forma
$structured['image_title'] = data_get($humanized, 'image_title', $structured['image_title'] ?? '');
$structured['image_body'] = data_get($humanized, 'image_body', $structured['image_body'] ?? '');
}
} catch (\Throwable $e) {
} catch (Throwable $e) {
Log::warning('RunGenerateNode: PostContentHumanizer failed, using generator output as-is', [
'error' => $e->getMessage(),
]);

View file

@ -67,7 +67,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
$context = $run->resolverContext();
if ($url === '') {
return NodeRunResult::failed('HTTP request node missing url.');
return NodeRunResult::failed(__('automations.errors.http_missing_url'));
}
$resolvedUrl = $this->resolver->resolve($url, $context);
@ -94,7 +94,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
default => null,
};
} catch (Throwable $e) {
return NodeRunResult::failed('HTTP request threw an exception.', ['message' => $e->getMessage()]);
return NodeRunResult::failed(__('automations.errors.http_request_exception'), ['message' => $e->getMessage()]);
}
if ($response === null) {
@ -102,7 +102,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
}
if (! $response->successful()) {
return NodeRunResult::failed('HTTP request failed.', [
return NodeRunResult::failed(__('automations.errors.http_request_failed'), [
'status' => $response->status(),
'body' => substr($response->body(), 0, 500),
]);
@ -128,7 +128,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
$resolved = data_get($payload, $itemsPath);
if (! is_array($resolved)) {
return NodeRunResult::failed('Items path did not resolve to an array.');
return NodeRunResult::failed(__('automations.errors.http_items_path_not_array'));
}
return $this->processItems($run, $nodeId, $config, array_values($resolved));

View file

@ -15,7 +15,7 @@ class RunPublishNode
{
public function __invoke(AutomationRun $run, array $config): NodeRunResult
{
$mode = Mode::from($config['mode'] ?? 'now');
$mode = Mode::from(data_get($config, 'mode', 'now'));
// Dry runs never have a generated Post (RunGenerateNode skipped
// persistence). Mirror the call site without touching the DB or
@ -34,7 +34,7 @@ public function __invoke(AutomationRun $run, array $config): NodeRunResult
match ($mode) {
Mode::Now => $this->publishNow($post),
Mode::Scheduled => $this->schedule($post, (int) ($config['scheduled_offset'] ?? 60)),
Mode::Scheduled => $this->schedule($post, (int) data_get($config, 'scheduled_offset')),
Mode::Draft => null,
};

View file

@ -7,13 +7,14 @@
use App\Enums\Automation\Run\Status;
use App\Jobs\Automation\ProcessAutomationNode;
use App\Models\AutomationRun;
use DomainException;
class RetryRunFromNode
{
public function __invoke(AutomationRun $run, string $nodeId): void
{
if ($run->status !== Status::Failed) {
throw new \DomainException(__('automations.errors.only_failed_can_retry'));
throw new DomainException(__('automations.errors.only_failed_can_retry'));
}
$run->update([

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Enums\Automation\Condition;
/**
* Output handles of a Condition node. The matched branch determines which
* handle the run continues down — these values must mirror the `id`s of the
* handles rendered in the frontend ConditionNode (resources/js/types/automation
* /condition-handle.ts) and the `source_handle` stored on edges.
*/
enum Handle: string
{
case Yes = 'yes';
case No = 'no';
}

View file

@ -52,7 +52,7 @@ public function rules(): array
if (is_array($nodes)) {
foreach ($nodes as $i => $node) {
$type = data_get($node, 'type');
foreach ($this->dataRulesForNodeType($type) as $field => $fieldRules) {
foreach ($this->dataRulesForNodeType($type, (int) $i) as $field => $fieldRules) {
$rules["nodes.{$i}.data.{$field}"] = $fieldRules;
}
}
@ -115,12 +115,12 @@ public function attributes(): array
/**
* @return array<string, array<int, mixed>>
*/
private function dataRulesForNodeType(?string $type): array
private function dataRulesForNodeType(?string $type, int $i): array
{
return match ($type) {
NodeType::Trigger->value => [
'trigger_type' => ['required', Rule::in(array_column(TriggerType::cases(), 'value'))],
'cron' => ['required_if:nodes.*.data.trigger_type,'.TriggerType::Schedule->value, 'string'],
'cron' => ['required_if:nodes.'.$i.'.data.trigger_type,'.TriggerType::Schedule->value, 'string'],
'schedule_field' => ['sometimes', Rule::in(['minutes', 'hours', 'days', 'weeks', 'months'])],
'schedule_minutes_interval' => ['sometimes', 'integer', 'min:1', 'max:59'],
'schedule_hours_interval' => ['sometimes', 'integer', 'min:1', 'max:23'],
@ -168,7 +168,7 @@ private function dataRulesForNodeType(?string $type): array
],
NodeType::Publish->value => [
'mode' => ['required', Rule::in(array_column(PublishMode::cases(), 'value'))],
'scheduled_offset' => ['nullable', 'integer', 'min:0'],
'scheduled_offset' => ['required_if:nodes.'.$i.'.data.mode,'.PublishMode::Scheduled->value, 'integer', 'min:0'],
],
NodeType::Webhook->value => [
'url' => ['required', 'url'],

View file

@ -381,5 +381,12 @@
'url_not_allowed' => 'The request URL points to a private or unreachable address and was blocked.',
'node_no_longer_exists' => 'Node :node_id no longer exists in the automation.',
'no_trigger_connection' => 'No node connected to the Trigger node.',
'fetch_rss_missing_url' => 'The Fetch RSS node is missing a feed URL.',
'fetch_rss_request_failed' => 'The RSS feed request failed.',
'fetch_rss_malformed' => 'The RSS feed is malformed.',
'http_missing_url' => 'The HTTP request node is missing a URL.',
'http_request_exception' => 'The HTTP request threw an exception.',
'http_request_failed' => 'The HTTP request failed.',
'http_items_path_not_array' => 'The items path did not resolve to a list.',
],
];

View file

@ -381,5 +381,12 @@
'url_not_allowed' => 'La URL de la petición apunta a una dirección privada o inaccesible y fue bloqueada.',
'node_no_longer_exists' => 'El nodo :node_id ya no existe en la automatización.',
'no_trigger_connection' => 'Ningún nodo está conectado al nodo disparador.',
'fetch_rss_missing_url' => 'Al nodo Obtener RSS le falta la URL del feed.',
'fetch_rss_request_failed' => 'La solicitud del feed RSS falló.',
'fetch_rss_malformed' => 'El feed RSS está mal formado.',
'http_missing_url' => 'Al nodo de petición HTTP le falta la URL.',
'http_request_exception' => 'La petición HTTP lanzó una excepción.',
'http_request_failed' => 'La petición HTTP falló.',
'http_items_path_not_array' => 'El items path no resolvió a una lista.',
],
];

View file

@ -381,5 +381,12 @@
'url_not_allowed' => 'A URL da requisição aponta para um endereço privado ou inacessível e foi bloqueada.',
'node_no_longer_exists' => 'O nó :node_id não existe mais nesta automação.',
'no_trigger_connection' => 'Nenhum nó conectado ao nó de trigger.',
'fetch_rss_missing_url' => 'O nó Buscar RSS está sem a URL do feed.',
'fetch_rss_request_failed' => 'A requisição do feed RSS falhou.',
'fetch_rss_malformed' => 'O feed RSS está malformado.',
'http_missing_url' => 'O nó de requisição HTTP está sem a URL.',
'http_request_exception' => 'A requisição HTTP lançou uma exceção.',
'http_request_failed' => 'A requisição HTTP falhou.',
'http_items_path_not_array' => 'O items path não resultou em uma lista.',
],
];

View file

@ -1,8 +1,10 @@
<script setup lang="ts">
import { Handle, Position } from '@vue-flow/core';
import { IconGitBranch } from '@tabler/icons-vue';
import { Handle, Position } from '@vue-flow/core';
import { computed } from 'vue';
import { ConditionHandle } from '@/types/automation/condition-handle';
const props = defineProps<{
data: {
field?: string;
@ -41,7 +43,7 @@ const summary = computed(() => {
class="!bg-rose-500"
/>
<Handle
id="yes"
:id="ConditionHandle.Yes"
type="source"
:position="Position.Right"
class="!bg-emerald-500"
@ -49,7 +51,7 @@ const summary = computed(() => {
/>
<span class="pointer-events-none absolute left-full top-[35%] z-10 ml-3 -translate-y-1/2 rounded bg-background px-1.5 text-[10px] font-bold uppercase tracking-wider text-emerald-700">yes</span>
<Handle
id="no"
:id="ConditionHandle.No"
type="source"
:position="Position.Right"
class="!bg-rose-500"

View file

@ -0,0 +1,11 @@
/**
* Output handle ids of a Condition node. Must mirror the backend
* App\Enums\Automation\Condition\Handle enum — the id rendered here becomes the
* edge `source_handle`, which the run engine matches to decide the branch.
*/
export const ConditionHandle = {
Yes: 'yes',
No: 'no',
} as const;
export type ConditionHandleValue = (typeof ConditionHandle)[keyof typeof ConditionHandle];

View file

@ -157,6 +157,36 @@
->assertJsonValidationErrors(['nodes.1.data.url']);
});
it('rejects a scheduled publish node with no scheduled_offset', function () {
$automation = Automation::factory()->for($this->workspace)->create();
$this->actingAs($this->user)
->putJson(route('app.automations.update', $automation->id), [
'nodes' => [
['id' => 'n1', 'type' => 'trigger', 'position' => ['x' => 0, 'y' => 0], 'data' => ['trigger_type' => 'schedule', 'cron' => '0 9 * * *']],
['id' => 'n2', 'type' => 'publish', 'position' => ['x' => 200, 'y' => 0], 'data' => ['mode' => 'scheduled']],
],
'connections' => [['id' => 'e1', 'source' => 'n1', 'target' => 'n2']],
])
->assertStatus(422)
->assertJsonValidationErrors(['nodes.1.data.scheduled_offset']);
});
it('allows a now publish node without scheduled_offset', function () {
$automation = Automation::factory()->for($this->workspace)->create();
$this->actingAs($this->user)
->put(route('app.automations.update', $automation->id), [
'nodes' => [
['id' => 'n1', 'type' => 'trigger', 'position' => ['x' => 0, 'y' => 0], 'data' => ['trigger_type' => 'schedule', 'cron' => '0 9 * * *']],
['id' => 'n2', 'type' => 'publish', 'position' => ['x' => 200, 'y' => 0], 'data' => ['mode' => 'now']],
],
'connections' => [['id' => 'e1', 'source' => 'n1', 'target' => 'n2']],
])
->assertRedirect()
->assertSessionHasNoErrors();
});
it('activates a valid automation', function () {
$automation = Automation::factory()->for($this->workspace)->withScheduleTrigger()->create();
$automation->update([