新增订单群聊
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package chat
|
||||
|
||||
import "time"
|
||||
|
||||
type Principal struct {
|
||||
Type string
|
||||
ID uint64
|
||||
}
|
||||
|
||||
type ConversationDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Role string `json:"role"`
|
||||
Participants []ParticipantDTO `json:"participants,omitempty"`
|
||||
LastMessageID *uint64 `json:"last_message_id"`
|
||||
LastMessagePreview string `json:"last_message_preview"`
|
||||
LastMessageAt *time.Time `json:"last_message_at"`
|
||||
UnreadCount int64 `json:"unread_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ParticipantDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
ConversationID uint64 `json:"conversation_id"`
|
||||
ParticipantType string `json:"participant_type"`
|
||||
ParticipantID uint64 `json:"participant_id"`
|
||||
Role string `json:"role"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
LastReadAt *time.Time `json:"last_read_at"`
|
||||
JoinedAt time.Time `json:"joined_at"`
|
||||
}
|
||||
|
||||
type MessageDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
ConversationID uint64 `json:"conversation_id"`
|
||||
SenderType string `json:"sender_type"`
|
||||
SenderID uint64 `json:"sender_id"`
|
||||
SenderRole string `json:"sender_role"`
|
||||
SenderName string `json:"sender_name"`
|
||||
SenderAvatar string `json:"sender_avatar"`
|
||||
IsSelf bool `json:"is_self"`
|
||||
ContentType string `json:"content_type"`
|
||||
Content string `json:"content"`
|
||||
AttachmentURLS []string `json:"attachment_urls"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type SendMessageRequest struct {
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
|
||||
type PaginatedResult struct {
|
||||
Items interface{} `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
h.list(c, Principal{Type: "user", ID: userID})
|
||||
}
|
||||
|
||||
func (h *Handler) AdminList(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
h.list(c, Principal{Type: "admin", ID: adminID})
|
||||
}
|
||||
|
||||
func (h *Handler) Detail(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
h.detail(c, Principal{Type: "user", ID: userID})
|
||||
}
|
||||
|
||||
func (h *Handler) AdminDetail(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
h.detail(c, Principal{Type: "admin", ID: adminID})
|
||||
}
|
||||
|
||||
func (h *Handler) OrderConversation(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
orderID, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.service.FindOrderConversation(userID, orderID)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
func (h *Handler) Messages(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
h.messages(c, Principal{Type: "user", ID: userID})
|
||||
}
|
||||
|
||||
func (h *Handler) AdminMessages(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
h.messages(c, Principal{Type: "admin", ID: adminID})
|
||||
}
|
||||
|
||||
func (h *Handler) Send(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
h.send(c, Principal{Type: "user", ID: userID})
|
||||
}
|
||||
|
||||
func (h *Handler) AdminSend(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
h.send(c, Principal{Type: "admin", ID: adminID})
|
||||
}
|
||||
|
||||
func (h *Handler) MarkRead(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
return
|
||||
}
|
||||
h.markRead(c, Principal{Type: "user", ID: userID})
|
||||
}
|
||||
|
||||
func (h *Handler) AdminMarkRead(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
h.markRead(c, Principal{Type: "admin", ID: adminID})
|
||||
}
|
||||
|
||||
func (h *Handler) list(c *gin.Context, principal Principal) {
|
||||
page, pageSize := parsePagination(c)
|
||||
result, err := h.service.ListConversations(principal, page, pageSize)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) detail(c *gin.Context, principal Principal) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := h.service.FindConversation(principal, id)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
func (h *Handler) messages(c *gin.Context, principal Principal) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, pageSize := parsePagination(c)
|
||||
result, err := h.service.Messages(principal, id, page, pageSize)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
func (h *Handler) send(c *gin.Context, principal Principal) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req SendMessageRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "消息内容不能为空")
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(principal, id, req)
|
||||
if err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.Created(c, message)
|
||||
}
|
||||
|
||||
func (h *Handler) markRead(c *gin.Context, principal Principal) {
|
||||
id, ok := parseID(c, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.service.MarkRead(principal, id); err != nil {
|
||||
writeChatError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"read": true})
|
||||
}
|
||||
|
||||
func parsePagination(c *gin.Context) (int, int) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
return normalizePagination(page, pageSize)
|
||||
}
|
||||
|
||||
func parseID(c *gin.Context, key string) (uint64, bool) {
|
||||
id, err := strconv.ParseUint(c.Param(key), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
response.BadRequest(c, "ID 不正确")
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (uint64, bool) {
|
||||
value, ok := c.Get(middleware.ContextUserID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
userID, ok := value.(uint64)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
func currentAdminID(c *gin.Context) (uint64, bool) {
|
||||
value, ok := c.Get(middleware.ContextAdminID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
adminID, ok := value.(uint64)
|
||||
return adminID, ok
|
||||
}
|
||||
|
||||
func writeChatError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, ErrDependencyUnavailable):
|
||||
response.ServiceUnavailable(c, "聊天服务暂时不可用")
|
||||
case errors.Is(err, ErrConversationNotFound):
|
||||
response.Error(c, http.StatusNotFound, "chat_not_found", "会话不存在")
|
||||
case errors.Is(err, ErrPermissionDenied):
|
||||
response.Error(c, http.StatusForbidden, "permission_denied", "无权访问该会话")
|
||||
case errors.Is(err, ErrInvalidMessage):
|
||||
response.BadRequest(c, "消息内容不符合规则")
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "聊天服务暂时不可用")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
const (
|
||||
defaultSupportUsername = "admin"
|
||||
defaultSupportPassword = "admin123456"
|
||||
defaultSupportNickname = "超级管理员"
|
||||
)
|
||||
|
||||
func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatConversation, error) {
|
||||
var existing model.ChatConversation
|
||||
err := tx.Where("order_id = ?", order.ID).First(&existing).Error
|
||||
if err == nil {
|
||||
return &existing, nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
conversation := model.ChatConversation{
|
||||
OrderID: order.ID,
|
||||
Type: "order_group",
|
||||
Title: orderConversationTitle(order),
|
||||
Status: "active",
|
||||
}
|
||||
if err := tx.Create(&conversation).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
participants := []model.ChatParticipant{
|
||||
{
|
||||
ConversationID: conversation.ID,
|
||||
ParticipantType: "user",
|
||||
ParticipantID: order.RenterID,
|
||||
Role: "renter",
|
||||
JoinedAt: now,
|
||||
},
|
||||
{
|
||||
ConversationID: conversation.ID,
|
||||
ParticipantType: "user",
|
||||
ParticipantID: order.OwnerID,
|
||||
Role: "owner",
|
||||
JoinedAt: now,
|
||||
},
|
||||
}
|
||||
if supportID := defaultSupportAdminID(tx); supportID > 0 {
|
||||
participants = append(participants, model.ChatParticipant{
|
||||
ConversationID: conversation.ID,
|
||||
ParticipantType: "admin",
|
||||
ParticipantID: supportID,
|
||||
Role: "support",
|
||||
JoinedAt: now,
|
||||
})
|
||||
}
|
||||
for _, participant := range participants {
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&participant).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
message := model.ChatMessage{
|
||||
ConversationID: conversation.ID,
|
||||
SenderType: "system",
|
||||
SenderRole: "system",
|
||||
ContentType: "system",
|
||||
Content: "订单已支付,群聊已创建。租客、号主和客服可在这里沟通交接与结账问题。",
|
||||
AttachmentURLS: emptyJSONList(),
|
||||
}
|
||||
if err := tx.Create(&message).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conversation.LastMessageID = &message.ID
|
||||
conversation.LastMessagePreview = truncatePreview(message.Content)
|
||||
conversation.LastMessageAt = &message.CreatedAt
|
||||
if err := tx.Save(&conversation).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &conversation, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListConversations(principal Principal, page, pageSize int) (*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").
|
||||
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
|
||||
err := r.conversationQuery(principal).
|
||||
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 (r *Repository) FindConversation(principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
var row conversationRow
|
||||
err := r.conversationQuery(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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTO(participants)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindOrderConversation(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
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
participants, err := r.participants(row.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto := row.toDTO(participants)
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Messages(principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
page, pageSize = normalizePagination(page, pageSize)
|
||||
if _, err := r.findParticipant(r.db, principal, conversationID, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var total int64
|
||||
if err := r.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).
|
||||
Order("id ASC").
|
||||
Offset(offset).
|
||||
Limit(pageSize).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := r.toMessageDTOs(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) {
|
||||
var messageID uint64
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
participant, err := r.findParticipant(tx, principal, conversationID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&conversation, conversationID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if conversation.Status != "active" {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
message := model.ChatMessage{
|
||||
ConversationID: conversation.ID,
|
||||
SenderType: principal.Type,
|
||||
SenderID: principal.ID,
|
||||
SenderRole: participant.Role,
|
||||
ContentType: "text",
|
||||
Content: req.Content,
|
||||
AttachmentURLS: emptyJSONList(),
|
||||
}
|
||||
if err := tx.Create(&message).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
conversation.LastMessageID = &message.ID
|
||||
conversation.LastMessagePreview = truncatePreview(message.Content)
|
||||
conversation.LastMessageAt = &message.CreatedAt
|
||||
if err := tx.Save(&conversation).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
if err := tx.Model(participant).Update("last_read_at", now).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
messageID = message.ID
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var message model.ChatMessage
|
||||
if err := r.db.First(&message, messageID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := r.toMessageDTOs(principal, []model.ChatMessage{message})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
return &items[0], nil
|
||||
}
|
||||
|
||||
func (r *Repository) MarkRead(principal Principal, conversationID uint64) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
participant, err := r.findParticipant(tx, principal, conversationID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
return tx.Model(participant).Update("last_read_at", now).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) conversationQuery(principal Principal) *gorm.DB {
|
||||
return r.db.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,
|
||||
(
|
||||
SELECT COUNT(1)
|
||||
FROM chat_messages AS cm
|
||||
WHERE cm.conversation_id = c.id
|
||||
AND NOT (cm.sender_type = ? AND cm.sender_id = ?)
|
||||
AND (cp.last_read_at IS NULL OR cm.created_at > cp.last_read_at)
|
||||
) AS unread_count`, principal.Type, principal.ID).
|
||||
Joins("JOIN chat_participants AS cp ON cp.conversation_id = c.id").
|
||||
Where("cp.participant_type = ? AND cp.participant_id = ?", principal.Type, principal.ID)
|
||||
}
|
||||
|
||||
func (r *Repository) findParticipant(tx *gorm.DB, principal Principal, conversationID uint64, lock bool) (*model.ChatParticipant, error) {
|
||||
var participant model.ChatParticipant
|
||||
db := tx
|
||||
if lock {
|
||||
db = db.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
err := db.Where("conversation_id = ? AND participant_type = ? AND participant_id = ?", conversationID, principal.Type, principal.ID).
|
||||
First(&participant).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrPermissionDenied
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &participant, nil
|
||||
}
|
||||
|
||||
func (r *Repository) participants(conversationID uint64) ([]ParticipantDTO, error) {
|
||||
var rows []model.ChatParticipant
|
||||
if err := r.db.Where("conversation_id = ?", conversationID).Order("id ASC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userNames, userAvatars, adminNames, err := r.participantNames(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]ParticipantDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
name := "系统"
|
||||
avatar := ""
|
||||
if row.ParticipantType == "user" {
|
||||
name = userNames[row.ParticipantID]
|
||||
avatar = userAvatars[row.ParticipantID]
|
||||
}
|
||||
if row.ParticipantType == "admin" {
|
||||
name = adminNames[row.ParticipantID]
|
||||
}
|
||||
items = append(items, ParticipantDTO{
|
||||
ID: row.ID,
|
||||
ConversationID: row.ConversationID,
|
||||
ParticipantType: row.ParticipantType,
|
||||
ParticipantID: row.ParticipantID,
|
||||
Role: row.Role,
|
||||
DisplayName: fallbackName(row.ParticipantType, row.ParticipantID, name),
|
||||
AvatarURL: avatar,
|
||||
LastReadAt: row.LastReadAt,
|
||||
JoinedAt: row.JoinedAt,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *Repository) toMessageDTOs(principal Principal, rows []model.ChatMessage) ([]MessageDTO, error) {
|
||||
userIDs := make([]uint64, 0)
|
||||
adminIDs := make([]uint64, 0)
|
||||
for _, row := range rows {
|
||||
if row.SenderType == "user" && row.SenderID > 0 {
|
||||
userIDs = append(userIDs, row.SenderID)
|
||||
}
|
||||
if row.SenderType == "admin" && row.SenderID > 0 {
|
||||
adminIDs = append(adminIDs, row.SenderID)
|
||||
}
|
||||
}
|
||||
userNames, userAvatars, err := r.userNames(userIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
adminNames, err := r.adminNames(adminIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]MessageDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
name := "系统"
|
||||
avatar := ""
|
||||
if row.SenderType == "user" {
|
||||
name = userNames[row.SenderID]
|
||||
avatar = userAvatars[row.SenderID]
|
||||
}
|
||||
if row.SenderType == "admin" {
|
||||
name = adminNames[row.SenderID]
|
||||
}
|
||||
items = append(items, MessageDTO{
|
||||
ID: row.ID,
|
||||
ConversationID: row.ConversationID,
|
||||
SenderType: row.SenderType,
|
||||
SenderID: row.SenderID,
|
||||
SenderRole: row.SenderRole,
|
||||
SenderName: fallbackName(row.SenderType, row.SenderID, name),
|
||||
SenderAvatar: avatar,
|
||||
IsSelf: row.SenderType == principal.Type && row.SenderID == principal.ID,
|
||||
ContentType: row.ContentType,
|
||||
Content: row.Content,
|
||||
AttachmentURLS: decodeStringList(row.AttachmentURLS),
|
||||
CreatedAt: row.CreatedAt,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (r *Repository) participantNames(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 {
|
||||
if row.ParticipantType == "user" {
|
||||
userIDs = append(userIDs, row.ParticipantID)
|
||||
}
|
||||
if row.ParticipantType == "admin" {
|
||||
adminIDs = append(adminIDs, row.ParticipantID)
|
||||
}
|
||||
}
|
||||
userNames, userAvatars, err := r.userNames(userIDs)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
adminNames, err := r.adminNames(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) {
|
||||
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 {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, user := range users {
|
||||
name := user.Nickname
|
||||
if name == "" {
|
||||
name = user.Phone
|
||||
}
|
||||
names[user.ID] = name
|
||||
avatars[user.ID] = user.AvatarURL
|
||||
}
|
||||
return names, avatars, nil
|
||||
}
|
||||
|
||||
func (r *Repository) adminNames(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 {
|
||||
return nil, err
|
||||
}
|
||||
for _, admin := range admins {
|
||||
name := admin.Nickname
|
||||
if name == "" {
|
||||
name = admin.Username
|
||||
}
|
||||
names[admin.ID] = name
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
type conversationRow struct {
|
||||
ID uint64
|
||||
OrderID uint64
|
||||
Type string
|
||||
Title string
|
||||
Status string
|
||||
Role string
|
||||
LastMessageID *uint64
|
||||
LastMessagePreview string
|
||||
LastMessageAt *time.Time
|
||||
UnreadCount int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (row conversationRow) toDTO(participants []ParticipantDTO) ConversationDTO {
|
||||
return ConversationDTO{
|
||||
ID: row.ID,
|
||||
OrderID: row.OrderID,
|
||||
Type: row.Type,
|
||||
Title: row.Title,
|
||||
Status: row.Status,
|
||||
Role: row.Role,
|
||||
Participants: participants,
|
||||
LastMessageID: row.LastMessageID,
|
||||
LastMessagePreview: row.LastMessagePreview,
|
||||
LastMessageAt: row.LastMessageAt,
|
||||
UnreadCount: row.UnreadCount,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func defaultSupportAdminID(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)
|
||||
if parseErr == nil && id > 0 && adminActive(tx, id) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
var admin model.AdminUser
|
||||
if err := tx.Where("status = ?", "active").Order("id ASC").First(&admin).Error; err != nil {
|
||||
return ensureDefaultSupportAdmin(tx)
|
||||
}
|
||||
return admin.ID
|
||||
}
|
||||
|
||||
func ensureDefaultSupportAdmin(tx *gorm.DB) uint64 {
|
||||
var count int64
|
||||
if err := tx.Model(&model.AdminUser{}).Count(&count).Error; err != nil || count > 0 {
|
||||
return 0
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(defaultSupportPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
admin := model.AdminUser{
|
||||
Username: defaultSupportUsername,
|
||||
PasswordHash: string(hash),
|
||||
Nickname: defaultSupportNickname,
|
||||
Status: "active",
|
||||
}
|
||||
if err := tx.Create(&admin).Error; err != nil {
|
||||
return 0
|
||||
}
|
||||
return admin.ID
|
||||
}
|
||||
|
||||
func adminActive(tx *gorm.DB, id uint64) bool {
|
||||
var count int64
|
||||
if err := tx.Model(&model.AdminUser{}).Where("id = ? AND status = ?", id, "active").Count(&count).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
return count > 0
|
||||
}
|
||||
|
||||
func orderConversationTitle(order model.RentalOrder) string {
|
||||
if order.OrderNo == "" {
|
||||
return fmt.Sprintf("订单群聊 #%d", order.ID)
|
||||
}
|
||||
return "订单群聊 " + order.OrderNo
|
||||
}
|
||||
|
||||
func normalizePagination(page, pageSize int) (int, int) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
func truncatePreview(content string) string {
|
||||
runes := []rune(content)
|
||||
if len(runes) <= 80 {
|
||||
return content
|
||||
}
|
||||
return string(runes[:80])
|
||||
}
|
||||
|
||||
func fallbackName(participantType string, id uint64, name string) string {
|
||||
if name != "" {
|
||||
return name
|
||||
}
|
||||
switch participantType {
|
||||
case "admin":
|
||||
return "客服"
|
||||
case "system":
|
||||
return "系统"
|
||||
default:
|
||||
return fmt.Sprintf("用户%d", id)
|
||||
}
|
||||
}
|
||||
|
||||
func uniqueIDs(ids []uint64) []uint64 {
|
||||
seen := map[uint64]bool{}
|
||||
result := make([]uint64, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id == 0 || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
result = append(result, id)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func emptyJSONList() datatypes.JSON {
|
||||
raw, _ := json.Marshal([]string{})
|
||||
return datatypes.JSON(raw)
|
||||
}
|
||||
|
||||
func decodeStringList(raw datatypes.JSON) []string {
|
||||
if len(raw) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
var items []string
|
||||
if err := json.Unmarshal(raw, &items); err != nil {
|
||||
return []string{}
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrConversationNotFound = errors.New("conversation not found")
|
||||
ErrPermissionDenied = errors.New("permission denied")
|
||||
ErrInvalidMessage = errors.New("invalid message")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
func (s *Service) ListConversations(principal Principal, page, pageSize int) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.ListConversations(principal, page, pageSize)
|
||||
}
|
||||
|
||||
func (s *Service) FindConversation(principal Principal, id uint64) (*ConversationDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindConversation(principal, id)
|
||||
}
|
||||
|
||||
func (s *Service) FindOrderConversation(userID uint64, orderID uint64) (*ConversationDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.FindOrderConversation(userID, orderID)
|
||||
}
|
||||
|
||||
func (s *Service) Messages(principal Principal, conversationID uint64, page, pageSize int) (*PaginatedResult, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.Messages(principal, conversationID, page, pageSize)
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(principal Principal, conversationID uint64, req SendMessageRequest) (*MessageDTO, error) {
|
||||
if s.repo == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
}
|
||||
req.Content = strings.TrimSpace(req.Content)
|
||||
if conversationID == 0 || req.Content == "" {
|
||||
return nil, ErrInvalidMessage
|
||||
}
|
||||
if len([]rune(req.Content)) > 1000 {
|
||||
return nil, ErrInvalidMessage
|
||||
}
|
||||
return s.repo.SendMessage(principal, conversationID, req)
|
||||
}
|
||||
|
||||
func (s *Service) MarkRead(principal Principal, conversationID uint64) error {
|
||||
if s.repo == nil {
|
||||
return ErrDependencyUnavailable
|
||||
}
|
||||
return s.repo.MarkRead(principal, conversationID)
|
||||
}
|
||||
Reference in New Issue
Block a user