Files
WMS/Modules/Helpdesk/Services/AutomationRuleService.php
T
2026-06-15 13:47:58 +01:00

67 lines
2.4 KiB
PHP

<?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;
}
$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();
}
});
return $ticket->fresh() ?? $ticket;
}
private function matches(AutomationRule $rule, Ticket $ticket, string $sender, string $mailbox): bool
{
if ($rule->match_sender && ! Str::contains(Str::lower($sender), Str::lower($rule->match_sender))) {
return false;
}
if ($rule->match_subject && ! Str::contains(Str::lower($ticket->subject), Str::lower($rule->match_subject))) {
return false;
}
if ($rule->match_mailbox && ! Str::contains(Str::lower($mailbox), Str::lower($rule->match_mailbox))) {
return false;
}
if ($rule->match_category_id && (int) $ticket->category_id !== (int) $rule->match_category_id) {
return false;
}
return true;
}
}