Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions app/Actions/Automation/Automation/ActivateAutomation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Enums\Automation\Node\Type as NodeType;
use App\Enums\Automation\Status;
use App\Models\Automation;
use App\Services\Automation\GenerateNodeValidator;

class ActivateAutomation
{
public function __construct(private GenerateNodeValidator $generateValidator) {}

public function __invoke(Automation $automation): Automation
{
$this->validate($automation);

$automation->update([
'status' => Status::Active,
'activated_at' => now(),
'paused_at' => null,
]);

return $automation;
}

private function validate(Automation $automation): void
{
$nodes = $automation->nodes ?? [];
$connections = $automation->connections ?? [];

$triggers = collect($nodes)->where('type', 'trigger');
if ($triggers->count() !== 1) {
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'));
}

foreach ($nodes as $node) {
if (data_get($node, 'type') !== NodeType::Generate->value) {
continue;
}

$issue = $this->generateValidator->issueFor((array) data_get($node, 'data', []));

if ($issue !== null) {
throw new \DomainException($issue);
}
}
}
}
52 changes: 52 additions & 0 deletions app/Actions/Automation/Automation/CreateAutomation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Enums\Automation\Status;
use App\Enums\Automation\Trigger\Type as TriggerType;
use App\Models\Automation;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Str;

class CreateAutomation
{
public function __invoke(Workspace $workspace, User $user, ?string $name = null): Automation
{
return Automation::create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
'name' => $name ?: __('automations.default_name'),
'status' => Status::Draft,
'nodes' => [$this->defaultTriggerNode()],
'connections' => [],
]);
}

/**
* Every automation has exactly one trigger — its entry point — so we seed it
* on creation. The trigger can't be added or deleted from the editor; only
* its type (schedule / post published / post scheduled) is configurable.
*
* @return array<string, mixed>
*/
private function defaultTriggerNode(): array
{
return [
'id' => (string) Str::uuid(),
'type' => 'trigger',
'position' => ['x' => 0, 'y' => 0],
'data' => [
'trigger_type' => TriggerType::Schedule->value,
'cron' => '0 9 * * *',
'schedule_field' => 'days',
'schedule_days_interval' => 1,
'schedule_hour' => 9,
'schedule_minute' => 0,
'schedule_timezone' => config('app.timezone'),
],
];
}
}
15 changes: 15 additions & 0 deletions app/Actions/Automation/Automation/DeleteAutomation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Models\Automation;

class DeleteAutomation
{
public function __invoke(Automation $automation): void
{
$automation->delete();
}
}
27 changes: 27 additions & 0 deletions app/Actions/Automation/Automation/GetAutomationDetails.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Models\Automation;
use App\Models\AutomationRun;
use App\Models\AutomationTriggerItem;
use Illuminate\Database\Eloquent\Collection;

class GetAutomationDetails
{
/**
* @return array{
* runs: Collection<int, AutomationRun>,
* triggerItems: Collection<int, AutomationTriggerItem>,
* }
*/
public function __invoke(Automation $automation): array
{
return [
'runs' => $automation->runs()->excludingDryRuns()->latest()->take(50)->get(),
'triggerItems' => $automation->triggerItems()->with('run')->latest()->take(50)->get(),
];
}
}
60 changes: 60 additions & 0 deletions app/Actions/Automation/Automation/GetAutomationEditorData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Enums\SocialAccount\Platform;
use App\Models\Automation;
use App\Models\SocialAccount;
use App\Services\Social\PinterestPublisher;
use App\Services\Social\TikTokCreatorInfo;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as SupportCollection;

class GetAutomationEditorData
{
public function __construct(
private PinterestPublisher $pinterestPublisher,
private TikTokCreatorInfo $tikTokCreatorInfo,
) {}

/**
* @return array{
* socialAccounts: Collection<int, SocialAccount>,
* pinterestBoards: SupportCollection<string, array<int, mixed>>,
* tiktokCreatorInfos: SupportCollection<string, mixed>,
* }
*/
public function __invoke(Automation $automation): array
{
$socialAccounts = $automation->workspace->socialAccounts()->active()->get();

$pinterestBoards = $socialAccounts
->where('platform', Platform::Pinterest)
->mapWithKeys(fn ($account) => [
$account->id => rescue(
fn () => $this->pinterestPublisher->getBoards($account),
[],
report: false,
),
]);

$tiktokCreatorInfos = $socialAccounts
->where('platform', Platform::TikTok)
->mapWithKeys(fn ($account) => [
$account->id => rescue(
fn () => $this->tikTokCreatorInfo->fetch($account),
null,
report: false,
),
])
->filter();

return [
'socialAccounts' => $socialAccounts,
'pinterestBoards' => $pinterestBoards,
'tiktokCreatorInfos' => $tiktokCreatorInfos,
];
}
}
20 changes: 20 additions & 0 deletions app/Actions/Automation/Automation/ListAutomations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Models\Automation;
use App\Models\Workspace;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class ListAutomations
{
public function __invoke(Workspace $workspace, ?int $perPage = null): LengthAwarePaginator
{
return Automation::query()
->where('workspace_id', $workspace->id)
->orderByDesc('created_at')
->paginate($perPage ?? (int) config('app.pagination.default'));
}
}
21 changes: 21 additions & 0 deletions app/Actions/Automation/Automation/PauseAutomation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Enums\Automation\Status;
use App\Models\Automation;

class PauseAutomation
{
public function __invoke(Automation $automation): Automation
{
$automation->update([
'status' => Status::Paused,
'paused_at' => now(),
]);

return $automation;
}
}
66 changes: 66 additions & 0 deletions app/Actions/Automation/Automation/UpdateAutomation.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Automation;

use App\Models\Automation;
use DomainException;

class UpdateAutomation
{
public function __invoke(Automation $automation, array $data): Automation
{
$this->detectCycles($data['nodes'] ?? [], $data['connections'] ?? []);

$automation->update([
'name' => $data['name'] ?? $automation->name,
'nodes' => $data['nodes'] ?? $automation->nodes,
'connections' => $data['connections'] ?? $automation->connections,
'variables' => $data['variables'] ?? $automation->variables,
]);

return $automation->fresh();
}

private function detectCycles(array $nodes, array $connections): void
{
$adj = [];
foreach ($connections as $c) {
$adj[$c['source']][] = $c['target'];
}

/** @var array<string, string> $state state: 'white' (unvisited), 'gray' (in stack), 'black' (done) */
$state = [];
foreach ($nodes as $node) {
$state[$node['id']] = 'white';
}

foreach ($nodes as $node) {
if ($state[$node['id']] === 'white' && $this->hasCycleFrom($node['id'], $adj, $state)) {
throw new DomainException(__('automations.errors.graph_contains_cycle'));
}
}
}

private function hasCycleFrom(string $node, array $adj, array &$state): bool
{
$state[$node] = 'gray';

foreach ($adj[$node] ?? [] as $next) {
if (! isset($state[$next])) {
continue;
}
if ($state[$next] === 'gray') {
return true;
}
if ($state[$next] === 'white' && $this->hasCycleFrom($next, $adj, $state)) {
return true;
}
}

$state[$node] = 'black';

return false;
}
}
62 changes: 62 additions & 0 deletions app/Actions/Automation/Node/RunConditionNode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace App\Actions\Automation\Node;

use App\DataTransferObjects\Automation\NodeRunResult;
use App\Enums\Automation\Condition\Operator;
use App\Models\AutomationRun;
use App\Services\Automation\ExpressionResolver;

class RunConditionNode
{
private const MAX_REGEX_LENGTH = 200;

public function __construct(private ExpressionResolver $resolver) {}

public function __invoke(AutomationRun $run, array $config): NodeRunResult
{
$context = $run->resolverContext();
$field = $this->resolver->resolve(data_get($config, 'field', ''), $context);
$operator = Operator::from(data_get($config, 'operator', 'equals'));
$value = $this->resolver->resolve((string) data_get($config, 'value', ''), $context);

$matched = match ($operator) {
Operator::Contains => str_contains($field, $value),
Operator::NotContains => ! str_contains($field, $value),
Operator::Equals => $field === $value,
Operator::NotEquals => $field !== $value,
Operator::Matches => $this->safeRegexMatch($value, $field),
Operator::GreaterThan => is_numeric($field) && is_numeric($value) && (float) $field > (float) $value,
Operator::LessThan => is_numeric($field) && is_numeric($value) && (float) $field < (float) $value,
};

return NodeRunResult::completed(
output: ['condition' => ['resolved_field' => $field, 'matched' => $matched]],
nextHandle: $matched ? 'yes' : 'no',
);
}

private function safeRegexMatch(string $pattern, string $subject): bool
{
if (strlen($pattern) > self::MAX_REGEX_LENGTH) {
return false;
}

$escaped = str_replace('~', '\~', $pattern);
$regex = "~{$escaped}~u";

try {
$result = @preg_match($regex, $subject);
} catch (\Throwable) {
return false;
}

if ($result === false || preg_last_error() !== PREG_NO_ERROR) {
return false;
}

return $result === 1;
}
}
Loading
Loading