继续补齐核心模块 Context 超时控制
This commit is contained in:
@@ -37,7 +37,7 @@ func (h *Handler) AdminList(c *gin.Context) {
|
||||
filter := c.DefaultQuery("filter", "all")
|
||||
page, pageSize := parsePagination(c)
|
||||
principal := Principal{Type: "admin", ID: adminID}
|
||||
result, err := h.service.ListConversationsWithFilter(principal, page, pageSize, filter)
|
||||
result, err := h.service.ListConversationsWithFilter(c.Request.Context(), principal, page, pageSize, filter)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -73,7 +73,7 @@ func (h *Handler) OrderConversation(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.service.FindOrderConversation(userID, orderID)
|
||||
item, err := h.service.FindOrderConversation(c.Request.Context(), userID, orderID)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -87,7 +87,7 @@ func (h *Handler) EnsureSupportConversation(c *gin.Context) {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
item, err := h.service.EnsureSupportConversation(userID)
|
||||
item, err := h.service.EnsureSupportConversation(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -165,7 +165,7 @@ func (h *Handler) AdminTransfer(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
principal := Principal{Type: "admin", ID: adminID}
|
||||
if err := h.service.TransferConversation(principal, id, req); err != nil {
|
||||
if err := h.service.TransferConversation(c.Request.Context(), principal, id, req); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func (h *Handler) AdminTransfer(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) AdminSupportAdmins(c *gin.Context) {
|
||||
admins, err := h.service.GetAvailableSupportAdmins()
|
||||
admins, err := h.service.GetAvailableSupportAdmins(c.Request.Context())
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -197,7 +197,7 @@ func (h *Handler) AdminUpdateRemark(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
principal := Principal{Type: "admin", ID: adminID}
|
||||
if err := h.service.UpdateRemark(principal, id, req); err != nil {
|
||||
if err := h.service.UpdateRemark(c.Request.Context(), principal, id, req); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -210,7 +210,7 @@ func (h *Handler) AdminListQuickReplies(c *gin.Context) {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
replies, err := h.service.ListQuickReplies(adminID)
|
||||
replies, err := h.service.ListQuickReplies(c.Request.Context(), adminID)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -229,7 +229,7 @@ func (h *Handler) AdminCreateQuickReply(c *gin.Context) {
|
||||
response.BadRequest(c, "标题和内容不能为空")
|
||||
return
|
||||
}
|
||||
reply, err := h.service.CreateQuickReply(adminID, req)
|
||||
reply, err := h.service.CreateQuickReply(c.Request.Context(), adminID, req)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -252,7 +252,7 @@ func (h *Handler) AdminUpdateQuickReply(c *gin.Context) {
|
||||
response.BadRequest(c, "请求参数错误")
|
||||
return
|
||||
}
|
||||
if err := h.service.UpdateQuickReply(adminID, id, req); err != nil {
|
||||
if err := h.service.UpdateQuickReply(c.Request.Context(), adminID, id, req); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -269,7 +269,7 @@ func (h *Handler) AdminDeleteQuickReply(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.service.DeleteQuickReply(adminID, id); err != nil {
|
||||
if err := h.service.DeleteQuickReply(c.Request.Context(), adminID, id); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -277,7 +277,7 @@ func (h *Handler) AdminDeleteQuickReply(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) AdminGetAutoWelcome(c *gin.Context) {
|
||||
message := h.service.GetAutoWelcomeMessage()
|
||||
message := h.service.GetAutoWelcomeMessage(c.Request.Context())
|
||||
response.OK(c, gin.H{"message": message})
|
||||
}
|
||||
|
||||
@@ -289,7 +289,7 @@ func (h *Handler) AdminUpdateAutoWelcome(c *gin.Context) {
|
||||
response.BadRequest(c, "话术内容不能为空")
|
||||
return
|
||||
}
|
||||
if err := h.service.UpdateAutoWelcomeMessage(req.Message); err != nil {
|
||||
if err := h.service.UpdateAutoWelcomeMessage(c.Request.Context(), req.Message); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -298,7 +298,7 @@ func (h *Handler) AdminUpdateAutoWelcome(c *gin.Context) {
|
||||
|
||||
func (h *Handler) list(c *gin.Context, principal Principal) {
|
||||
page, pageSize := parsePagination(c)
|
||||
result, err := h.service.ListConversations(principal, page, pageSize)
|
||||
result, err := h.service.ListConversations(c.Request.Context(), principal, page, pageSize)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -311,7 +311,7 @@ func (h *Handler) detail(c *gin.Context, principal Principal) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.service.FindConversation(principal, id)
|
||||
item, err := h.service.FindConversation(c.Request.Context(), principal, id)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -325,7 +325,7 @@ func (h *Handler) messages(c *gin.Context, principal Principal) {
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
result, err := h.service.Messages(principal, id, page, pageSize)
|
||||
result, err := h.service.Messages(c.Request.Context(), principal, id, page, pageSize)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -343,7 +343,7 @@ func (h *Handler) send(c *gin.Context, principal Principal) {
|
||||
response.BadRequest(c, "消息格式不正确")
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(principal, id, req)
|
||||
message, err := h.service.SendMessage(c.Request.Context(), principal, id, req)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
@@ -356,7 +356,7 @@ func (h *Handler) markRead(c *gin.Context, principal Principal) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.service.MarkRead(principal, id); err != nil {
|
||||
if err := h.service.MarkRead(c.Request.Context(), principal, id); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -118,10 +119,11 @@ func (r *Repository) NotifyNewConversation(conversationID uint64) {
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (r *Repository) ListConversations(ctx context.Context, principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||
page, pageSize = normalizePagination(page, pageSize)
|
||||
db := r.db.WithContext(ctx)
|
||||
var total int64
|
||||
countDB := r.db.Table("chat_conversations AS c").
|
||||
countDB := db.Table("chat_conversations AS c").
|
||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
||||
if err := countDB.Count(&total).Error; err != nil {
|
||||
@@ -130,7 +132,7 @@ func (r *Repository) ListConversations(principal Principal, page, pageSize int)
|
||||
|
||||
var rows []conversationRow
|
||||
offset := (page - 1) * pageSize
|
||||
err := r.conversationQuery(principal).
|
||||
err := r.conversationQuery(ctx, principal).
|
||||
Order("COALESCE(c.last_message_at, c.created_at) DESC, c.id DESC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
@@ -145,17 +147,18 @@ func (r *Repository) ListConversations(principal Principal, page, pageSize int)
|
||||
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindConversation(principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
func (r *Repository) FindConversation(ctx context.Context, principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
// 管理员可以查看任意会话,无需是 participant
|
||||
if principal.Type == "admin" {
|
||||
var conversation model.ChatConversation
|
||||
if err := r.db.First(&conversation, id).Error; err != nil {
|
||||
if err := db.First(&conversation, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
participants, err := r.participants(conversation.ID)
|
||||
participants, err := r.participants(ctx, conversation.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -179,14 +182,14 @@ func (r *Repository) FindConversation(principal Principal, id uint64) (*Conversa
|
||||
|
||||
// 普通用户需要是 participant
|
||||
var row conversationRow
|
||||
err := r.conversationQuery(principal).Where("c.id = ?", id).First(&row).Error
|
||||
err := r.conversationQuery(ctx, principal).Where("c.id = ?", id).First(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
participants, err := r.participants(row.ID)
|
||||
participants, err := r.participants(ctx, row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -194,17 +197,17 @@ func (r *Repository) FindConversation(principal Principal, id uint64) (*Conversa
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindOrderConversation(userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||
func (r *Repository) FindOrderConversation(ctx context.Context, userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||
var row conversationRow
|
||||
principal := Principal{Type: "user", ID: userID}
|
||||
err := r.conversationQuery(principal).Where("c.order_id = ?", orderID).First(&row).Error
|
||||
err := r.conversationQuery(ctx, principal).Where("c.order_id = ?", orderID).First(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
participants, err := r.participants(row.ID)
|
||||
participants, err := r.participants(ctx, row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -212,9 +215,9 @@ func (r *Repository) FindOrderConversation(userID uint64, orderID uint64) (*Conv
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) EnsureSupportConversation(userID uint64) (*ConversationDTO, error) {
|
||||
func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint64) (*ConversationDTO, error) {
|
||||
var conversationID uint64
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var existing model.ChatConversation
|
||||
err := tx.Table("chat_conversations AS c").
|
||||
Select("c.*").
|
||||
@@ -288,7 +291,7 @@ func (r *Repository) EnsureSupportConversation(userID uint64) (*ConversationDTO,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item, err := r.FindConversation(Principal{Type: "user", ID: userID}, conversationID)
|
||||
item, err := r.FindConversation(ctx, Principal{Type: "user", ID: userID}, conversationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -296,18 +299,19 @@ func (r *Repository) EnsureSupportConversation(userID uint64) (*ConversationDTO,
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Messages(principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (r *Repository) Messages(ctx context.Context, principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
page, pageSize = normalizePagination(page, pageSize)
|
||||
db := r.db.WithContext(ctx)
|
||||
|
||||
// 管理员可以查看任意会话的消息,普通用户需要是 participant
|
||||
if principal.Type != "admin" {
|
||||
if _, err := r.findParticipant(r.db, principal, conversationID, false); err != nil {
|
||||
if _, err := r.findParticipant(db, principal, conversationID, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// 管理员需要验证会话存在
|
||||
var count int64
|
||||
if err := r.db.Model(&model.ChatConversation{}).Where("id = ?", conversationID).Count(&count).Error; err != nil {
|
||||
if err := db.Model(&model.ChatConversation{}).Where("id = ?", conversationID).Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
@@ -316,28 +320,28 @@ func (r *Repository) Messages(principal Principal, conversationID uint64, page,
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := r.db.Model(&model.ChatMessage{}).Where("conversation_id = ?", conversationID).Count(&total).Error; err != nil {
|
||||
if err := db.Model(&model.ChatMessage{}).Where("conversation_id = ?", conversationID).Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
offset := (page - 1) * pageSize
|
||||
var rows []model.ChatMessage
|
||||
if err := r.db.Where("conversation_id = ?", conversationID).
|
||||
if err := db.Where("conversation_id = ?", conversationID).
|
||||
Order("id ASC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := r.toMessageDTOs(principal, rows)
|
||||
items, err := r.toMessageDTOs(ctx, principal, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PaginatedResult{Items: items, Total: total, Page: page, PageSize: pageSize}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SendMessage(principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
|
||||
func (r *Repository) SendMessage(ctx context.Context, principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
|
||||
var messageID uint64
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&conversation, conversationID).Error; err != nil {
|
||||
return err
|
||||
@@ -409,10 +413,10 @@ func (r *Repository) SendMessage(principal Principal, conversationID uint64, req
|
||||
return nil, err
|
||||
}
|
||||
var message model.ChatMessage
|
||||
if err := r.db.First(&message, messageID).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).First(&message, messageID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := r.toMessageDTOs(principal, []model.ChatMessage{message})
|
||||
items, err := r.toMessageDTOs(ctx, principal, []model.ChatMessage{message})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -442,8 +446,8 @@ func (r *Repository) SendMessage(principal Principal, conversationID uint64, req
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
func (r *Repository) MarkRead(principal Principal, conversationID uint64) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
func (r *Repository) MarkRead(ctx context.Context, principal Principal, conversationID uint64) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 管理员可以不是 participant,直接返回成功
|
||||
if principal.Type == "admin" {
|
||||
// 尝试查找 participant 记录,如果有就更新
|
||||
@@ -471,8 +475,8 @@ func (r *Repository) MarkRead(principal Principal, conversationID uint64) error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) conversationQuery(principal Principal) *gorm.DB {
|
||||
return r.db.Table("chat_conversations AS c").
|
||||
func (r *Repository) conversationQuery(ctx context.Context, principal Principal) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("chat_conversations AS c").
|
||||
Select(`c.id, c.order_id, c.type, c.title, c.status, c.last_message_id,
|
||||
c.last_message_preview, c.last_message_at, c.created_at, c.updated_at, cp.role,
|
||||
(
|
||||
@@ -503,12 +507,12 @@ func (r *Repository) findParticipant(tx *gorm.DB, principal Principal, conversat
|
||||
return &participant, nil
|
||||
}
|
||||
|
||||
func (r *Repository) participants(conversationID uint64) ([]ParticipantDTO, error) {
|
||||
func (r *Repository) participants(ctx context.Context, conversationID uint64) ([]ParticipantDTO, error) {
|
||||
var rows []model.ChatParticipant
|
||||
if err := r.db.Where("conversation_id = ?", conversationID).Order("id ASC").Find(&rows).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Where("conversation_id = ?", conversationID).Order("id ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userNames, userAvatars, adminNames, err := r.participantNames(rows)
|
||||
userNames, userAvatars, adminNames, err := r.participantNames(ctx, rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -538,7 +542,7 @@ func (r *Repository) participants(conversationID uint64) ([]ParticipantDTO, erro
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *Repository) toMessageDTOs(principal Principal, rows []model.ChatMessage) ([]MessageDTO, error) {
|
||||
func (r *Repository) toMessageDTOs(ctx context.Context, principal Principal, rows []model.ChatMessage) ([]MessageDTO, error) {
|
||||
userIDs := make([]uint64, 0)
|
||||
adminIDs := make([]uint64, 0)
|
||||
for _, row := range rows {
|
||||
@@ -549,11 +553,11 @@ func (r *Repository) toMessageDTOs(principal Principal, rows []model.ChatMessage
|
||||
adminIDs = append(adminIDs, row.SenderID)
|
||||
}
|
||||
}
|
||||
userNames, userAvatars, err := r.userNames(userIDs)
|
||||
userNames, userAvatars, err := r.userNames(ctx, userIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
adminNames, err := r.adminNames(adminIDs)
|
||||
adminNames, err := r.adminNames(ctx, adminIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -590,7 +594,7 @@ func (r *Repository) toMessageDTOs(principal Principal, rows []model.ChatMessage
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *Repository) participantNames(rows []model.ChatParticipant) (map[uint64]string, map[uint64]string, map[uint64]string, error) {
|
||||
func (r *Repository) participantNames(ctx context.Context, rows []model.ChatParticipant) (map[uint64]string, map[uint64]string, map[uint64]string, error) {
|
||||
userIDs := make([]uint64, 0)
|
||||
adminIDs := make([]uint64, 0)
|
||||
for _, row := range rows {
|
||||
@@ -601,25 +605,25 @@ func (r *Repository) participantNames(rows []model.ChatParticipant) (map[uint64]
|
||||
adminIDs = append(adminIDs, row.ParticipantID)
|
||||
}
|
||||
}
|
||||
userNames, userAvatars, err := r.userNames(userIDs)
|
||||
userNames, userAvatars, err := r.userNames(ctx, userIDs)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
adminNames, err := r.adminNames(adminIDs)
|
||||
adminNames, err := r.adminNames(ctx, adminIDs)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
return userNames, userAvatars, adminNames, nil
|
||||
}
|
||||
|
||||
func (r *Repository) userNames(ids []uint64) (map[uint64]string, map[uint64]string, error) {
|
||||
func (r *Repository) userNames(ctx context.Context, ids []uint64) (map[uint64]string, map[uint64]string, error) {
|
||||
names := map[uint64]string{}
|
||||
avatars := map[uint64]string{}
|
||||
if len(ids) == 0 {
|
||||
return names, avatars, nil
|
||||
}
|
||||
var users []model.User
|
||||
if err := r.db.Where("id IN ?", uniqueIDs(ids)).Find(&users).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Where("id IN ?", uniqueIDs(ids)).Find(&users).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, user := range users {
|
||||
@@ -633,13 +637,13 @@ func (r *Repository) userNames(ids []uint64) (map[uint64]string, map[uint64]stri
|
||||
return names, avatars, nil
|
||||
}
|
||||
|
||||
func (r *Repository) adminNames(ids []uint64) (map[uint64]string, error) {
|
||||
func (r *Repository) adminNames(ctx context.Context, ids []uint64) (map[uint64]string, error) {
|
||||
names := map[uint64]string{}
|
||||
if len(ids) == 0 {
|
||||
return names, nil
|
||||
}
|
||||
var admins []model.AdminUser
|
||||
if err := r.db.Where("id IN ?", uniqueIDs(ids)).Find(&admins).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Where("id IN ?", uniqueIDs(ids)).Find(&admins).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, admin := range admins {
|
||||
@@ -802,8 +806,8 @@ func messagePreview(content string, attachments []string) string {
|
||||
}
|
||||
|
||||
// TransferConversation 转接会话给其他客服
|
||||
func (r *Repository) TransferConversation(principal Principal, conversationID uint64, toAdminID uint64) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
func (r *Repository) TransferConversation(ctx context.Context, principal Principal, conversationID uint64, toAdminID uint64) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 验证当前操作者是会话参与者
|
||||
if _, err := r.findParticipant(tx, principal, conversationID, false); err != nil {
|
||||
return err
|
||||
@@ -855,7 +859,8 @@ func (r *Repository) TransferConversation(principal Principal, conversationID ui
|
||||
}
|
||||
|
||||
// GetAvailableSupportAdmins 获取可用客服列表及其会话数
|
||||
func (r *Repository) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
|
||||
func (r *Repository) GetAvailableSupportAdmins(ctx context.Context) ([]SupportAdminDTO, error) {
|
||||
db := r.db.WithContext(ctx)
|
||||
// 仅展示客服角色管理员,超级管理员即使有 chat:view 权限也不作为客服候选。
|
||||
type adminRow struct {
|
||||
ID uint64
|
||||
@@ -863,7 +868,7 @@ func (r *Repository) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
|
||||
SupportStatus string
|
||||
}
|
||||
var admins []adminRow
|
||||
err := r.db.Table("admin_users AS au").
|
||||
err := db.Table("admin_users AS au").
|
||||
Select("au.id, COALESCE(NULLIF(au.nickname, ''), au.username) AS nickname, au.support_status").
|
||||
Joins("JOIN admin_user_roles AS aur ON aur.admin_user_id = au.id").
|
||||
Joins("JOIN roles AS r ON r.id = aur.role_id").
|
||||
@@ -885,7 +890,7 @@ func (r *Repository) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
|
||||
adminIDs[i] = a.ID
|
||||
}
|
||||
if len(adminIDs) > 0 {
|
||||
r.db.Table("chat_participants").
|
||||
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").
|
||||
@@ -909,19 +914,20 @@ func (r *Repository) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
|
||||
}
|
||||
|
||||
// ListConversationsWithFilter 支持筛选的会话列表
|
||||
func (r *Repository) ListConversationsWithFilter(principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
|
||||
func (r *Repository) ListConversationsWithFilter(ctx context.Context, principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
|
||||
page, pageSize = normalizePagination(page, pageSize)
|
||||
db := r.db.WithContext(ctx)
|
||||
|
||||
// 管理员在"全部"模式下直接查询所有会话
|
||||
if principal.Type == "admin" && filter == "all" {
|
||||
var total int64
|
||||
if err := r.db.Model(&model.ChatConversation{}).Count(&total).Error; err != nil {
|
||||
if err := db.Model(&model.ChatConversation{}).Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var conversations []model.ChatConversation
|
||||
offset := (page - 1) * pageSize
|
||||
if err := r.db.Order("COALESCE(last_message_at, created_at) DESC, id DESC").
|
||||
if err := db.Order("COALESCE(last_message_at, created_at) DESC, id DESC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Find(&conversations).Error; err != nil {
|
||||
@@ -930,7 +936,7 @@ func (r *Repository) ListConversationsWithFilter(principal Principal, page, page
|
||||
|
||||
items := make([]ConversationDTO, 0, len(conversations))
|
||||
for _, conv := range conversations {
|
||||
participants, err := r.participants(conv.ID)
|
||||
participants, err := r.participants(ctx, conv.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -955,7 +961,7 @@ func (r *Repository) ListConversationsWithFilter(principal Principal, page, page
|
||||
|
||||
// 其他情况使用原有逻辑
|
||||
var total int64
|
||||
countDB := r.db.Table("chat_conversations AS c").
|
||||
countDB := db.Table("chat_conversations AS c").
|
||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id")
|
||||
|
||||
switch filter {
|
||||
@@ -965,7 +971,7 @@ func (r *Repository) ListConversationsWithFilter(principal Principal, page, page
|
||||
case "unassigned":
|
||||
// 未分配客服的会话
|
||||
countDB = countDB.Where("c.id NOT IN (?)",
|
||||
r.db.Table("chat_participants").Select("conversation_id").Where("participant_type = ? AND role = ?", "admin", "support"))
|
||||
db.Table("chat_participants").Select("conversation_id").Where("participant_type = ? AND role = ?", "admin", "support"))
|
||||
default:
|
||||
// 普通用户的全部会话
|
||||
countDB = countDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
||||
@@ -978,13 +984,13 @@ func (r *Repository) ListConversationsWithFilter(principal Principal, page, page
|
||||
var rows []conversationRow
|
||||
offset := (page - 1) * pageSize
|
||||
|
||||
queryDB := r.conversationQuery(principal)
|
||||
queryDB := r.conversationQuery(ctx, 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"))
|
||||
db.Table("chat_participants").Select("conversation_id").Where("participant_type = ? AND role = ?", "admin", "support"))
|
||||
default:
|
||||
// 普通用户的全部会话
|
||||
queryDB = queryDB.Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
||||
@@ -1001,7 +1007,7 @@ func (r *Repository) ListConversationsWithFilter(principal Principal, page, page
|
||||
|
||||
items := make([]ConversationDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
participants, err := r.participants(row.ID)
|
||||
participants, err := r.participants(ctx, row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1048,16 +1054,16 @@ func encodeStringList(items []string) datatypes.JSON {
|
||||
}
|
||||
|
||||
// UpdateRemark 更新会话备注
|
||||
func (r *Repository) UpdateRemark(principal Principal, conversationID uint64, remark string) error {
|
||||
return r.db.Model(&model.ChatParticipant{}).
|
||||
func (r *Repository) UpdateRemark(ctx context.Context, principal Principal, conversationID uint64, remark string) error {
|
||||
return r.db.WithContext(ctx).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) {
|
||||
func (r *Repository) ListQuickReplies(ctx context.Context, adminID uint64) ([]QuickReplyDTO, error) {
|
||||
var replies []model.ChatQuickReply
|
||||
err := r.db.Where("admin_user_id = ? OR admin_user_id = 0", adminID).
|
||||
err := r.db.WithContext(ctx).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 {
|
||||
@@ -1078,7 +1084,7 @@ func (r *Repository) ListQuickReplies(adminID uint64) ([]QuickReplyDTO, error) {
|
||||
}
|
||||
|
||||
// CreateQuickReply 创建快捷回复
|
||||
func (r *Repository) CreateQuickReply(adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
|
||||
func (r *Repository) CreateQuickReply(ctx context.Context, adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
|
||||
ownerID := adminID
|
||||
if req.IsGlobal {
|
||||
ownerID = 0
|
||||
@@ -1089,7 +1095,7 @@ func (r *Repository) CreateQuickReply(adminID uint64, req CreateQuickReplyReques
|
||||
Content: req.Content,
|
||||
SortOrder: req.SortOrder,
|
||||
}
|
||||
if err := r.db.Create(&reply).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Create(&reply).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &QuickReplyDTO{
|
||||
@@ -1103,8 +1109,8 @@ func (r *Repository) CreateQuickReply(adminID uint64, req CreateQuickReplyReques
|
||||
}
|
||||
|
||||
// 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)
|
||||
func (r *Repository) UpdateQuickReply(ctx context.Context, adminID uint64, replyID uint64, req UpdateQuickReplyRequest) error {
|
||||
query := r.db.WithContext(ctx).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
|
||||
@@ -1122,23 +1128,23 @@ func (r *Repository) UpdateQuickReply(adminID uint64, replyID uint64, req Update
|
||||
}
|
||||
|
||||
// DeleteQuickReply 删除快捷回复
|
||||
func (r *Repository) DeleteQuickReply(adminID uint64, replyID uint64) error {
|
||||
return r.db.Where("id = ? AND admin_user_id = ?", replyID, adminID).
|
||||
func (r *Repository) DeleteQuickReply(ctx context.Context, adminID uint64, replyID uint64) error {
|
||||
return r.db.WithContext(ctx).Where("id = ? AND admin_user_id = ?", replyID, adminID).
|
||||
Delete(&model.ChatQuickReply{}).Error
|
||||
}
|
||||
|
||||
// GetAutoWelcomeMessage 获取建群自动话术
|
||||
func (r *Repository) GetAutoWelcomeMessage() string {
|
||||
func (r *Repository) GetAutoWelcomeMessage(ctx context.Context) string {
|
||||
var cfg model.SystemConfig
|
||||
if err := r.db.Where("`key` = ?", "chat.auto_welcome_message").First(&cfg).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).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{}).
|
||||
func (r *Repository) UpdateAutoWelcomeMessage(ctx context.Context, message string) error {
|
||||
return r.db.WithContext(ctx).Model(&model.SystemConfig{}).
|
||||
Where("`key` = ?", "chat.auto_welcome_message").
|
||||
Update("value", message).Error
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
@@ -21,45 +22,45 @@ func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
func (s *Service) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (s *Service) ListConversations(ctx context.Context, principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ListConversations(principal, page, pageSize)
|
||||
return s.repo.ListConversations(ctx, principal, page, pageSize)
|
||||
}
|
||||
|
||||
func (s *Service) FindConversation(principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
func (s *Service) FindConversation(ctx context.Context, principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindConversation(principal, id)
|
||||
return s.repo.FindConversation(ctx, principal, id)
|
||||
}
|
||||
|
||||
func (s *Service) FindOrderConversation(userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||
func (s *Service) FindOrderConversation(ctx context.Context, userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindOrderConversation(userID, orderID)
|
||||
return s.repo.FindOrderConversation(ctx, userID, orderID)
|
||||
}
|
||||
|
||||
func (s *Service) EnsureSupportConversation(userID uint64) (*ConversationDTO, error) {
|
||||
func (s *Service) EnsureSupportConversation(ctx context.Context, userID uint64) (*ConversationDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
if userID == 0 {
|
||||
return nil, ErrPermissionDenied
|
||||
}
|
||||
return s.repo.EnsureSupportConversation(userID)
|
||||
return s.repo.EnsureSupportConversation(ctx, userID)
|
||||
}
|
||||
|
||||
func (s *Service) Messages(principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
func (s *Service) Messages(ctx context.Context, principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Messages(principal, conversationID, page, pageSize)
|
||||
return s.repo.Messages(ctx, principal, conversationID, page, pageSize)
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
|
||||
func (s *Service) SendMessage(ctx context.Context, principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
@@ -75,7 +76,7 @@ func (s *Service) SendMessage(principal Principal, conversationID uint64, req Se
|
||||
if !ok {
|
||||
return nil, ErrInvalidMessage
|
||||
}
|
||||
return s.repo.SendMessage(principal, conversationID, req)
|
||||
return s.repo.SendMessage(ctx, principal, conversationID, req)
|
||||
}
|
||||
|
||||
func normalizeAttachmentURLS(items []string) ([]string, bool) {
|
||||
@@ -112,52 +113,52 @@ func normalizeAttachmentURLS(items []string) ([]string, bool) {
|
||||
return result, true
|
||||
}
|
||||
|
||||
func (s *Service) MarkRead(principal Principal, conversationID uint64) error {
|
||||
func (s *Service) MarkRead(ctx context.Context, principal Principal, conversationID uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.MarkRead(principal, conversationID)
|
||||
return s.repo.MarkRead(ctx, principal, conversationID)
|
||||
}
|
||||
|
||||
func (s *Service) TransferConversation(principal Principal, conversationID uint64, req TransferRequest) error {
|
||||
func (s *Service) TransferConversation(ctx context.Context, principal Principal, conversationID uint64, req TransferRequest) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
if conversationID == 0 || req.ToAdminID == 0 {
|
||||
return ErrInvalidMessage
|
||||
}
|
||||
return s.repo.TransferConversation(principal, conversationID, req.ToAdminID)
|
||||
return s.repo.TransferConversation(ctx, principal, conversationID, req.ToAdminID)
|
||||
}
|
||||
|
||||
func (s *Service) GetAvailableSupportAdmins() ([]SupportAdminDTO, error) {
|
||||
func (s *Service) GetAvailableSupportAdmins(ctx context.Context) ([]SupportAdminDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.GetAvailableSupportAdmins()
|
||||
return s.repo.GetAvailableSupportAdmins(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) ListConversationsWithFilter(principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
|
||||
func (s *Service) ListConversationsWithFilter(ctx context.Context, principal Principal, page, pageSize int, filter string) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ListConversationsWithFilter(principal, page, pageSize, filter)
|
||||
return s.repo.ListConversationsWithFilter(ctx, principal, page, pageSize, filter)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateRemark(principal Principal, conversationID uint64, req UpdateRemarkRequest) error {
|
||||
func (s *Service) UpdateRemark(ctx context.Context, principal Principal, conversationID uint64, req UpdateRemarkRequest) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.UpdateRemark(principal, conversationID, req.Remark)
|
||||
return s.repo.UpdateRemark(ctx, principal, conversationID, req.Remark)
|
||||
}
|
||||
|
||||
func (s *Service) ListQuickReplies(adminID uint64) ([]QuickReplyDTO, error) {
|
||||
func (s *Service) ListQuickReplies(ctx context.Context, adminID uint64) ([]QuickReplyDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ListQuickReplies(adminID)
|
||||
return s.repo.ListQuickReplies(ctx, adminID)
|
||||
}
|
||||
|
||||
func (s *Service) CreateQuickReply(adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
|
||||
func (s *Service) CreateQuickReply(ctx context.Context, adminID uint64, req CreateQuickReplyRequest) (*QuickReplyDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
@@ -166,33 +167,33 @@ func (s *Service) CreateQuickReply(adminID uint64, req CreateQuickReplyRequest)
|
||||
if req.Title == "" || req.Content == "" {
|
||||
return nil, ErrInvalidMessage
|
||||
}
|
||||
return s.repo.CreateQuickReply(adminID, req)
|
||||
return s.repo.CreateQuickReply(ctx, adminID, req)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateQuickReply(adminID uint64, replyID uint64, req UpdateQuickReplyRequest) error {
|
||||
func (s *Service) UpdateQuickReply(ctx context.Context, adminID uint64, replyID uint64, req UpdateQuickReplyRequest) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.UpdateQuickReply(adminID, replyID, req)
|
||||
return s.repo.UpdateQuickReply(ctx, adminID, replyID, req)
|
||||
}
|
||||
|
||||
func (s *Service) DeleteQuickReply(adminID uint64, replyID uint64) error {
|
||||
func (s *Service) DeleteQuickReply(ctx context.Context, adminID uint64, replyID uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.DeleteQuickReply(adminID, replyID)
|
||||
return s.repo.DeleteQuickReply(ctx, adminID, replyID)
|
||||
}
|
||||
|
||||
func (s *Service) GetAutoWelcomeMessage() string {
|
||||
func (s *Service) GetAutoWelcomeMessage(ctx context.Context) string {
|
||||
if s.repo == nil {
|
||||
return ""
|
||||
}
|
||||
return s.repo.GetAutoWelcomeMessage()
|
||||
return s.repo.GetAutoWelcomeMessage(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateAutoWelcomeMessage(message string) error {
|
||||
func (s *Service) UpdateAutoWelcomeMessage(ctx context.Context, message string) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.UpdateAutoWelcomeMessage(message)
|
||||
return s.repo.UpdateAutoWelcomeMessage(ctx, message)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user