feat(capacity): enforce inbox assignment limits
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
package autoassignment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
)
|
||||
|
||||
func setupCapacityAssignmentDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.User{},
|
||||
&model.AccountUser{},
|
||||
&model.Inbox{},
|
||||
&model.InboxMember{},
|
||||
&model.Contact{},
|
||||
&model.Conversation{},
|
||||
&model.AgentCapacityPolicy{},
|
||||
&model.InboxCapacityLimit{},
|
||||
))
|
||||
return db
|
||||
}
|
||||
|
||||
func TestAssignmentService_SkipsAgentsAtInboxCapacity(t *testing.T) {
|
||||
_, rdb := setupTestRedis(t)
|
||||
db := setupCapacityAssignmentDB(t)
|
||||
svc := NewAssignmentService(db, rdb)
|
||||
ctx := context.Background()
|
||||
|
||||
account := &model.Account{Name: "Capacity Account"}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Capacity Inbox", ChannelType: string(model.InboxChannelTypeWebWidget), EnableAutoAssignment: true}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
contact := &model.Contact{AccountID: account.ID, Name: "Capacity Contact"}
|
||||
require.NoError(t, db.Create(contact).Error)
|
||||
|
||||
agentAtCapacity := createCapacityUser(t, db, account.ID, "full@test.com")
|
||||
agentWithCapacity := createCapacityUser(t, db, account.ID, "available@test.com")
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: agentAtCapacity.ID}).Error)
|
||||
require.NoError(t, db.Create(&model.InboxMember{InboxID: inbox.ID, UserID: agentWithCapacity.ID}).Error)
|
||||
|
||||
policy := &model.AgentCapacityPolicy{AccountID: account.ID, Name: "Capacity", AssignmentLogic: "round_robin", ExclusionRules: []byte(`{}`)}
|
||||
require.NoError(t, db.Create(policy).Error)
|
||||
require.NoError(t, db.Model(&model.AccountUser{}).
|
||||
Where("account_id = ? AND user_id = ?", account.ID, agentAtCapacity.ID).
|
||||
Update("agent_capacity_policy_id", policy.ID).Error)
|
||||
require.NoError(t, db.Create(&model.InboxCapacityLimit{AgentCapacityPolicyID: policy.ID, InboxID: inbox.ID, ConversationLimit: 1}).Error)
|
||||
|
||||
now := time.Now().Unix()
|
||||
existing := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, AssigneeID: &agentAtCapacity.ID, Status: string(model.ConversationStatusOpen), ChannelType: "web_widget", Channel: "web_widget", LastActivityAt: &now}
|
||||
unassigned := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, Status: string(model.ConversationStatusOpen), ChannelType: "web_widget", Channel: "web_widget", LastActivityAt: &now}
|
||||
require.NoError(t, db.Create(existing).Error)
|
||||
require.NoError(t, db.Create(unassigned).Error)
|
||||
|
||||
agentID, err := svc.AssignConversation(ctx, unassigned.ID, inbox.ID, account.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, agentWithCapacity.ID, agentID)
|
||||
}
|
||||
|
||||
func createCapacityUser(t *testing.T, db *gorm.DB, accountID uint, email string) *model.User {
|
||||
t.Helper()
|
||||
user := &model.User{AccountID: accountID, Name: email, Email: email, Password: "hashed", Active: true, Available: true}
|
||||
require.NoError(t, db.Create(user).Error)
|
||||
require.NoError(t, db.Create(&model.AccountUser{AccountID: accountID, UserID: user.ID, Role: "agent", Availability: "online"}).Error)
|
||||
return user
|
||||
}
|
||||
@@ -16,12 +16,13 @@ package autoassignment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
)
|
||||
|
||||
// AssignmentService handles auto-assignment of conversations to agents.
|
||||
@@ -52,11 +53,11 @@ func NewAssignmentService(db *gorm.DB, rdb *redis.Client) *AssignmentService {
|
||||
// Reference: Chatwoot AssignmentService.assign_unassigned_conversations
|
||||
//
|
||||
// Steps:
|
||||
// 1. Find all unassigned open conversations for the inbox
|
||||
// 2. Get the inbox's assignment policy and rate limits
|
||||
// 3. Get the list of eligible agents (online + members of the inbox)
|
||||
// 4. For each conversation, select an agent via round-robin + rate limit
|
||||
// 5. Assign the conversation to the selected agent
|
||||
// 1. Find all unassigned open conversations for the inbox
|
||||
// 2. Get the inbox's assignment policy and rate limits
|
||||
// 3. Get the list of eligible agents (online + members of the inbox)
|
||||
// 4. For each conversation, select an agent via round-robin + rate limit
|
||||
// 5. Assign the conversation to the selected agent
|
||||
func (s *AssignmentService) AssignUnassignedConversations(ctx context.Context, inboxID uint, accountID uint) ([]uint, error) {
|
||||
// Step 1: Check if auto-assignment is enabled for this inbox
|
||||
inbox, err := s.getInbox(ctx, inboxID)
|
||||
@@ -129,9 +130,9 @@ func (s *AssignmentService) AssignUnassignedConversations(ctx context.Context, i
|
||||
// Reference: Chatwoot AgentAssignmentService.assign_conversation
|
||||
//
|
||||
// Steps:
|
||||
// 1. Get eligible agents for the conversation's inbox
|
||||
// 2. Select an agent via round-robin + rate limit
|
||||
// 3. Assign the conversation
|
||||
// 1. Get eligible agents for the conversation's inbox
|
||||
// 2. Select an agent via round-robin + rate limit
|
||||
// 3. Assign the conversation
|
||||
func (s *AssignmentService) AssignConversation(ctx context.Context, conversationID uint, inboxID uint, accountID uint) (uint, error) {
|
||||
// Check if auto-assignment is enabled
|
||||
inbox, err := s.getInbox(ctx, inboxID)
|
||||
@@ -266,7 +267,57 @@ func (s *AssignmentService) getEligibleAgents(ctx context.Context, inboxID uint,
|
||||
Where("inbox_members.inbox_id = ? AND users.available = ? AND users.active = ?",
|
||||
inboxID, true, true).
|
||||
Pluck("inbox_members.user_id", &agentIDs).Error
|
||||
return agentIDs, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
availableIDs := make([]uint, 0, len(agentIDs))
|
||||
for _, agentID := range agentIDs {
|
||||
hasCapacity, err := s.agentHasInboxCapacity(ctx, accountID, inboxID, agentID, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if hasCapacity {
|
||||
availableIDs = append(availableIDs, agentID)
|
||||
}
|
||||
}
|
||||
return availableIDs, nil
|
||||
}
|
||||
|
||||
func (s *AssignmentService) agentHasInboxCapacity(ctx context.Context, accountID, inboxID, agentID, excludeConversationID uint) (bool, error) {
|
||||
var accountUser model.AccountUser
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("account_id = ? AND user_id = ?", accountID, agentID).
|
||||
First(&accountUser).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("load account user capacity policy: %w", err)
|
||||
}
|
||||
if accountUser.AgentCapacityPolicyID == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
var limit model.InboxCapacityLimit
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("agent_capacity_policy_id = ? AND inbox_id = ?", *accountUser.AgentCapacityPolicyID, inboxID).
|
||||
First(&limit).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("load inbox capacity limit: %w", err)
|
||||
}
|
||||
|
||||
q := s.db.WithContext(ctx).Model(&model.Conversation{}).
|
||||
Where("account_id = ? AND inbox_id = ? AND assignee_id = ? AND status = ?", accountID, inboxID, agentID, model.ConversationStatusOpen)
|
||||
if excludeConversationID != 0 {
|
||||
q = q.Where("id <> ?", excludeConversationID)
|
||||
}
|
||||
var assignedOpenCount int64
|
||||
if err := q.Count(&assignedOpenCount).Error; err != nil {
|
||||
return false, fmt.Errorf("count assigned open conversations: %w", err)
|
||||
}
|
||||
return assignedOpenCount < int64(limit.ConversationLimit), nil
|
||||
}
|
||||
|
||||
// getInbox fetches the inbox by ID.
|
||||
@@ -308,4 +359,4 @@ func (s *AssignmentService) assignConversation(ctx context.Context, conversation
|
||||
Model(&model.Conversation{}).
|
||||
Where("id = ?", conversationID).
|
||||
Update("assignee_id", agentID).Error
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user