| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Models; |
| 4 |
|
| 5 |
class AgentGroup extends Tag |
| 6 |
{ |
| 7 |
protected static $type = 'agent_group'; |
| 8 |
|
| 9 |
public static function boot() |
| 10 |
{ |
| 11 |
parent::boot(); |
| 12 |
|
| 13 |
static::creating(function ($model) { |
| 14 |
$model->tag_type = static::$type; |
| 15 |
if (empty($model->created_by) && $userId = get_current_user_id()) { |
| 16 |
$model->created_by = $userId; |
| 17 |
} |
| 18 |
|
| 19 |
$model->slug = static::slugify($model->title); |
| 20 |
}); |
| 21 |
|
| 22 |
static::addGlobalScope(function ($builder) { |
| 23 |
$builder->where('tag_type', static::$type); |
| 24 |
}); |
| 25 |
} |
| 26 |
|
| 27 |
public static function slugify($title) |
| 28 |
{ |
| 29 |
$slug = sanitize_title($title, 'agent-group', 'display'); |
| 30 |
if (static::where('slug', $slug)->first()) { |
| 31 |
$slug .= '-' . time(); |
| 32 |
} |
| 33 |
return $slug; |
| 34 |
} |
| 35 |
|
| 36 |
public function agents() |
| 37 |
{ |
| 38 |
return $this->belongsToMany( |
| 39 |
Agent::class, 'fs_tag_pivot', 'tag_id', 'source_id' |
| 40 |
)->wherePivot('source_type', 'agent_group'); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Get the least-loaded agent in this group, respecting mailbox restrictions. |
| 45 |
* |
| 46 |
* @param int|null $mailboxId |
| 47 |
* @param array $currentCounts Optional pre-loaded counts [agent_id => count] |
| 48 |
* @return Agent|null |
| 49 |
*/ |
| 50 |
public function getLeastLoadedAgent($mailboxId = null, array &$currentCounts = []) |
| 51 |
{ |
| 52 |
$agents = $this->agents()->get(); |
| 53 |
|
| 54 |
if ($agents->isEmpty()) { |
| 55 |
return null; |
| 56 |
} |
| 57 |
|
| 58 |
if (empty($currentCounts)) { |
| 59 |
$agentIds = $agents->pluck('id')->toArray(); |
| 60 |
$currentCounts = Ticket::whereIn('agent_id', $agentIds) |
| 61 |
->where('status', '!=', 'closed') |
| 62 |
->selectRaw('agent_id, COUNT(*) as cnt') |
| 63 |
->groupBy('agent_id') |
| 64 |
->pluck('cnt', 'agent_id') |
| 65 |
->toArray(); |
| 66 |
} |
| 67 |
|
| 68 |
$selectedAgent = null; |
| 69 |
$minCount = PHP_INT_MAX; |
| 70 |
|
| 71 |
foreach ($agents as $agent) { |
| 72 |
if ($mailboxId) { |
| 73 |
$restrictions = $agent->getMeta('agent_restrictions', []); |
| 74 |
if (!empty($restrictions['restrictedBusinessBoxes']) && in_array($mailboxId, $restrictions['restrictedBusinessBoxes'])) { |
| 75 |
continue; |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
$count = $currentCounts[$agent->id] ?? 0; |
| 80 |
if ($count < $minCount) { |
| 81 |
$minCount = $count; |
| 82 |
$selectedAgent = $agent; |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
return $selectedAgent; |
| 87 |
} |
| 88 |
} |
| 89 |
|