44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Modules\Helpdesk\Services;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Modules\Helpdesk\Models\Category;
|
|
|
|
final class AgentAssignmentService
|
|
{
|
|
/**
|
|
* Select the least-loaded available agent for a category.
|
|
*
|
|
* @param int|null $categoryId
|
|
* @return int|null
|
|
*/
|
|
public function selectAgentId(?int $categoryId): ?int
|
|
{
|
|
$query = User::query()
|
|
->where(static function (Builder $query): void {
|
|
$query->where('helpdesk_agent', true)->orWhere('helpdesk_admin', true);
|
|
})
|
|
->withCount(['helpdeskAssignedTickets as open_helpdesk_tickets_count' => static function (Builder $query): void {
|
|
$query->whereNull('completed_at');
|
|
}]);
|
|
|
|
if ($categoryId !== null) {
|
|
$category = Category::query()->find($categoryId);
|
|
$agentIds = $category?->agents()->pluck('users.id')->all() ?? [];
|
|
|
|
if ($agentIds !== []) {
|
|
$query->whereIn('id', $agentIds);
|
|
}
|
|
}
|
|
|
|
/** @var User|null $agent */
|
|
$agent = $query->orderBy('open_helpdesk_tickets_count')->orderBy('id')->first();
|
|
|
|
return $agent?->id;
|
|
}
|
|
}
|