客服可以给会话设置个人备注, 设置 快捷回复

建群自动话术
This commit is contained in:
yml2213
2026-05-27 06:43:24 +08:00
parent a002987784
commit 138f0514a9
15 changed files with 1462 additions and 34 deletions
+316 -1
View File
@@ -83,12 +83,18 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
}
}
// 获取自动话术
autoMessage := "订单已支付,群聊已创建。租客、号主和客服可在这里沟通交接与结账问题。"
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", "chat.auto_welcome_message").First(&cfg).Error; err == nil && cfg.Value != "" {
autoMessage = cfg.Value
}
message := model.ChatMessage{
ConversationID: conversation.ID,
SenderType: "system",
SenderRole: "system",
ContentType: "system",
Content: "订单已支付,群聊已创建。租客、号主和客服可在这里沟通交接与结账问题。",
Content: autoMessage,
AttachmentURLS: emptyJSONList(),
}
if err := tx.Create(&message).Error; err != nil {
@@ -499,6 +505,54 @@ func (row conversationRow) toDTO(participants []ParticipantDTO) ConversationDTO
}
func defaultSupportAdminID(tx *gorm.DB) uint64 {
// 查询所有有 chat:view 权限且状态为 active 的管理员
var adminIDs []uint64
err := tx.Table("admin_users AS au").
Joins("JOIN admin_user_roles AS aur ON aur.admin_user_id = au.id").
Joins("JOIN role_permissions AS rp ON rp.role_id = aur.role_id").
Joins("JOIN permissions AS p ON p.id = rp.permission_id").
Where("au.status = ? AND p.code = ?", "active", "chat:view").
Distinct("au.id").
Pluck("au.id", &adminIDs).Error
if err != nil || len(adminIDs) == 0 {
// 回退到原有逻辑
return fallbackSupportAdminID(tx)
}
// 统计每个客服当前负责的会话数,选择负载最少的
type adminLoad struct {
AdminID uint64
Count int64
}
var loads []adminLoad
tx.Table("chat_participants AS cp").
Select("cp.participant_id AS admin_id, COUNT(*) AS count").
Where("cp.participant_type = ? AND cp.role = ? AND cp.participant_id IN ?", "admin", "support", adminIDs).
Group("cp.participant_id").
Scan(&loads)
loadMap := make(map[uint64]int64)
for _, l := range loads {
loadMap[l.AdminID] = l.Count
}
// 找到负载最少的客服
var minLoad int64 = -1
var selectedID uint64
for _, id := range adminIDs {
count := loadMap[id]
if minLoad < 0 || count < minLoad {
minLoad = count
selectedID = id
}
}
if selectedID > 0 {
return selectedID
}
return fallbackSupportAdminID(tx)
}
func fallbackSupportAdminID(tx *gorm.DB) uint64 {
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", "chat.default_support_admin_id").First(&cfg).Error; err == nil {
id, parseErr := strconv.ParseUint(cfg.Value, 10, 64)
@@ -570,6 +624,175 @@ func truncatePreview(content string) string {
return string(runes[:80])
}
// TransferConversation 转接会话给其他客服
func (r *Repository) TransferConversation(principal Principal, conversationID uint64, toAdminID uint64) error {
return r.db.Transaction(func(tx *gorm.DB) error {
// 验证当前操作者是会话参与者
if _, err := r.findParticipant(tx, principal, conversationID, false); err != nil {
return err
}
// 验证目标客服存在且活跃
if !adminActive(tx, toAdminID) {
return fmt.Errorf("目标客服不存在或已禁用")
}
// 检查目标客服是否已有该会话
var count int64
if err := tx.Model(&model.ChatParticipant{}).
Where("conversation_id = ? AND participant_type = ? AND participant_id = ?", conversationID, "admin", toAdminID).
Count(&count).Error; err != nil {
return err
}
if count > 0 {
return fmt.Errorf("该客服已在会话中")
}
// 删除原客服参与者
if err := tx.Where("conversation_id = ? AND participant_type = ? AND role = ?", conversationID, "admin", "support").
Delete(&model.ChatParticipant{}).Error; err != nil {
return err
}
// 添加新客服参与者
participant := model.ChatParticipant{
ConversationID: conversationID,
ParticipantType: "admin",
ParticipantID: toAdminID,
Role: "support",
JoinedAt: time.Now(),
}
if err := tx.Create(&participant).Error; err != nil {
return err
}
// 添加系统消息记录转接
message := model.ChatMessage{
ConversationID: conversationID,
SenderType: "system",
SenderRole: "system",
ContentType: "system",
Content: "会话已转接给其他客服",
AttachmentURLS: emptyJSONList(),
}
if err := tx.Create(&message).Error; err != nil {
return err
}
return nil
})
}
// GetAvailableSupportAdmins 获取可用客服列表及其会话数
func (r *Repository) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
// 查询所有有 chat:view 权限且状态为 active 的管理员
type adminRow struct {
ID uint64
Nickname string
}
var admins []adminRow
err := r.db.Table("admin_users AS au").
Select("au.id, au.nickname").
Joins("JOIN admin_user_roles AS aur ON aur.admin_user_id = au.id").
Joins("JOIN role_permissions AS rp ON rp.role_id = aur.role_id").
Joins("JOIN permissions AS p ON p.id = rp.permission_id").
Where("au.status = ? AND p.code = ?", "active", "chat:view").
Distinct("au.id").
Scan(&admins).Error
if err != nil {
return nil, err
}
// 统计每个客服的会话数
type loadRow struct {
AdminID uint64
Count int64
}
var loads []loadRow
adminIDs := make([]uint64, len(admins))
for i, a := range admins {
adminIDs[i] = a.ID
}
if len(adminIDs) > 0 {
r.db.Table("chat_participants").
Select("participant_id AS admin_id, COUNT(*) AS count").
Where("participant_type = ? AND role = ? AND participant_id IN ?", "admin", "support", adminIDs).
Group("participant_id").
Scan(&loads)
}
loadMap := make(map[uint64]int64)
for _, l := range loads {
loadMap[l.AdminID] = l.Count
}
result := make([]SupportAdminDTO, len(admins))
for i, a := range admins {
result[i] = SupportAdminDTO{
ID: a.ID,
Nickname: a.Nickname,
ChatCount: loadMap[a.ID],
}
}
return result, nil
}
// ListConversationsWithFilter 支持筛选的会话列表
func (r *Repository) ListConversationsWithFilter(principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
page, pageSize = normalizePagination(page, pageSize)
var total int64
countDB := r.db.Table("chat_conversations AS c").
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id")
switch filter {
case "mine":
// 只看我的会话
countDB = countDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
case "unassigned":
// 未分配客服的会话
countDB = countDB.Where("c.id NOT IN (?)",
r.db.Table("chat_participants").Select("conversation_id").Where("participant_type = ? AND role = ?", "admin", "support"))
default:
// 全部会话(admin 可以看所有)
if principal.Type == "admin" {
// 管理员看所有会话
} else {
countDB = countDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
}
}
if err := countDB.Count(&total).Error; err != nil {
return nil, err
}
var rows []conversationRow
offset := (page - 1) * pageSize
queryDB := r.conversationQuery(principal)
switch filter {
case "mine":
queryDB = queryDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
case "unassigned":
queryDB = queryDB.Where("c.id NOT IN (?)",
r.db.Table("chat_participants").Select("conversation_id").Where("participant_type = ? AND role = ?", "admin", "support"))
default:
if principal.Type == "admin" {
// 管理员看所有会话
} else {
queryDB = queryDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
}
}
err := queryDB.
Order("COALESCE(c.last_message_at, c.created_at) DESC, c.id DESC").
Offset(offset).
Limit(pageSize).
Scan(&rows).Error
if err != nil {
return nil, err
}
items := make([]ConversationDTO, 0, len(rows))
for _, row := range rows {
items = append(items, row.toDTO(nil))
}
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
}
func fallbackName(participantType string, id uint64, name string) string {
if name != "" {
return name
@@ -602,6 +825,98 @@ func emptyJSONList() datatypes.JSON {
return datatypes.JSON(raw)
}
// UpdateRemark 更新会话备注
func (r *Repository) UpdateRemark(principal Principal, conversationID uint64, remark string) error {
return r.db.Model(&model.ChatParticipant{}).
Where("conversation_id = ? AND participant_type = ? AND participant_id = ?", conversationID, principal.Type, principal.ID).
Update("remark", remark).Error
}
// ListQuickReplies 获取快捷回复列表(个人 + 全局)
func (r *Repository) ListQuickReplies(adminID uint64) ([]QuickReplyDTO, error) {
var replies []model.ChatQuickReply
err := r.db.Where("admin_user_id = ? OR admin_user_id = 0", adminID).
Order("admin_user_id DESC, sort_order ASC, id ASC").
Find(&replies).Error
if err != nil {
return nil, err
}
result := make([]QuickReplyDTO, len(replies))
for i, reply := range replies {
result[i] = QuickReplyDTO{
ID: reply.ID,
AdminUserID: reply.AdminUserID,
Title: reply.Title,
Content: reply.Content,
SortOrder: reply.SortOrder,
IsGlobal: reply.AdminUserID == 0,
}
}
return result, nil
}
// CreateQuickReply 创建快捷回复
func (r *Repository) CreateQuickReply(adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
reply := model.ChatQuickReply{
AdminUserID: adminID,
Title: req.Title,
Content: req.Content,
SortOrder: req.SortOrder,
}
if err := r.db.Create(&reply).Error; err != nil {
return nil, err
}
return &QuickReplyDTO{
ID: reply.ID,
AdminUserID: reply.AdminUserID,
Title: reply.Title,
Content: reply.Content,
SortOrder: reply.SortOrder,
IsGlobal: false,
}, nil
}
// UpdateQuickReply 更新快捷回复
func (r *Repository) UpdateQuickReply(adminID uint64, replyID uint64, req UpdateQuickReplyRequest) error {
query := r.db.Model(&model.ChatQuickReply{}).Where("id = ? AND (admin_user_id = ? OR admin_user_id = 0)", replyID, adminID)
updates := map[string]interface{}{}
if req.Title != "" {
updates["title"] = req.Title
}
if req.Content != "" {
updates["content"] = req.Content
}
if req.SortOrder != nil {
updates["sort_order"] = *req.SortOrder
}
if len(updates) == 0 {
return nil
}
return query.Updates(updates).Error
}
// DeleteQuickReply 删除快捷回复
func (r *Repository) DeleteQuickReply(adminID uint64, replyID uint64) error {
return r.db.Where("id = ? AND admin_user_id = ?", replyID, adminID).
Delete(&model.ChatQuickReply{}).Error
}
// GetAutoWelcomeMessage 获取建群自动话术
func (r *Repository) GetAutoWelcomeMessage() string {
var cfg model.SystemConfig
if err := r.db.Where("`key` = ?", "chat.auto_welcome_message").First(&cfg).Error; err != nil {
return "欢迎加入订单群聊!如有任何问题,请随时沟通。"
}
return cfg.Value
}
// UpdateAutoWelcomeMessage 更新建群自动话术
func (r *Repository) UpdateAutoWelcomeMessage(message string) error {
return r.db.Model(&model.SystemConfig{}).
Where("`key` = ?", "chat.auto_welcome_message").
Update("value", message).Error
}
func decodeStringList(raw datatypes.JSON) []string {
if len(raw) == 0 {
return []string{}