Files
WMS/Modules/Helpdesk/Services/AutomationRuleService.php
2026-09-21 10:14:57 +01:00

67 lines
2.3 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace Modules\Helpdesk\Services;
use Illuminate\Support\Str;
use Modules\Helpdesk\Models\AutomationRule;
use Modules\Helpdesk\Models\Ticket;
final class AutomationRuleService
{
/** @param array<string, mixed> $context */
public function apply(Ticket $ticket, array $context = []): Ticket
{
$sender = (string) ($context['sender'] ?? $ticket->owner?->email ?? '');
$mailbox = (string) ($context['mailbox'] ?? '');
AutomationRule::query()
->where('is_active', true)
->where(static function ($query) use ($ticket): void {
$query->whereNull('company_id')->orWhere('company_id', $ticket->company_id);
})
->orderBy('sort_order')
->orderBy('id')
->get()
->each(function (AutomationRule $rule) use ($ticket, $sender, $mailbox): void {
if (! $this->matches($rule, $ticket, $sender, $mailbox)) {
return;
}
$this->applyRuleUpdates($rule, $ticket);
});
return $ticket->fresh() ?? $ticket;
}
private function matches(AutomationRule $rule, Ticket $ticket, string $sender, string $mailbox): bool
{
return $this->containsWhenConfigured($sender, $rule->match_sender)
&& $this->containsWhenConfigured($ticket->subject, $rule->match_subject)
&& $this->containsWhenConfigured($mailbox, $rule->match_mailbox)
&& (! $rule->match_category_id || (int) $ticket->category_id === (int) $rule->match_category_id);
}
private function containsWhenConfigured(string $value, ?string $match): bool
{
return ! $match || Str::contains(Str::lower($value), Str::lower($match));
}
private function applyRuleUpdates(AutomationRule $rule, Ticket $ticket): void
{
$updates = array_filter([
'priority_id' => $rule->set_priority_id,
'category_id' => $rule->set_category_id,
'team_id' => $rule->set_team_id,
'project_id' => $rule->set_project_id,
'status_id' => $rule->set_status_id,
'agent_id' => $rule->set_agent_id,
], static fn ($value): bool => $value !== null);
if ($updates !== []) {
$ticket->forceFill($updates + ['last_activity_at' => now()])->save();
}
}
}