优化发布群租客清退与历史消息

This commit is contained in:
yml
2026-06-18 09:39:23 +08:00
parent 233920025e
commit f4361c9804
10 changed files with 325 additions and 33 deletions
+12 -8
View File
@@ -150,7 +150,8 @@ func AddRenterToListingConversation(tx *gorm.DB, listingID uint64, renterID uint
ParticipantType: "user",
ParticipantID: renterID,
Role: "renter",
JoinedAt: now, // 关键: 记录加入时间,用于消息可见性过滤
JoinedAt: now,
LastReadAt: &now,
}
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&participant).Error; err != nil {
@@ -183,17 +184,17 @@ func AddRenterToListingConversation(tx *gorm.DB, listingID uint64, renterID uint
return sendSystemMessage(tx, conv.ID, message)
}
// RemoveRenterFromListingConversation 移出租客
func RemoveRenterFromListingConversation(tx *gorm.DB, listingID uint64, renterID uint64) error {
// RemoveRenterFromListingConversation 移出租客,返回是否真的删除了租客成员记录。
func RemoveRenterFromListingConversation(tx *gorm.DB, listingID uint64, renterID uint64) (bool, error) {
// 1. 查找发布群
var conv model.ChatConversation
err := tx.Where("listing_id = ?", listingID).First(&conv).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// 无发布群,跳过
return nil
return false, nil
}
return err
return false, err
}
// 2. 删除租客参与者记录
@@ -202,16 +203,19 @@ func RemoveRenterFromListingConversation(tx *gorm.DB, listingID uint64, renterID
Delete(&model.ChatParticipant{})
if result.Error != nil {
return result.Error
return false, result.Error
}
// 3. 发系统消息(如果确实删除了)
if result.RowsAffected > 0 {
message := "订单已结束,租客已退出群聊"
return sendSystemMessage(tx, conv.ID, message)
if err := sendSystemMessage(tx, conv.ID, message); err != nil {
return false, err
}
return true, nil
}
return nil
return false, nil
}
// 辅助函数
+1 -10
View File
@@ -14,15 +14,11 @@ func (r *Repository) Messages(ctx context.Context, principal Principal, conversa
page, pageSize = normalizePagination(page, pageSize)
db := r.db.WithContext(ctx)
var participant *model.ChatParticipant
// 管理员可以查看任意会话的消息,普通用户需要是 participant
if principal.Type != "admin" {
p, err := r.findParticipant(db, principal, conversationID, false)
if err != nil {
if _, err := r.findParticipant(db, principal, conversationID, false); err != nil {
return nil, err
}
participant = p
} else {
// 管理员需要验证会话存在
var count int64
@@ -37,11 +33,6 @@ func (r *Repository) Messages(ctx context.Context, principal Principal, conversa
// 构建查询
query := db.Model(&model.ChatMessage{}).Where("conversation_id = ?", conversationID)
// 租客只能看到加入时间之后的消息
if principal.Type == "user" && participant != nil && participant.Role == "renter" {
query = query.Where("created_at >= ?", participant.JoinedAt)
}
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, err