feat(tenant): 隔离客服通知文件与后台任务
This commit is contained in:
@@ -7,20 +7,22 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
const adminChatCountsCacheTTL = 5 * time.Second
|
||||
|
||||
func (r *Repository) adminChatCountsCacheKey(principal Principal, filter, stage, keyword string) string {
|
||||
func (r *Repository) adminChatCountsCacheKey(ctx context.Context, principal Principal, filter, stage, keyword string) string {
|
||||
sum := sha256.Sum256([]byte(keyword))
|
||||
return fmt.Sprintf("admin-chat:counts:v2:%s:%d:%s:%s:%s", principal.Type, principal.ID, filter, stage, hex.EncodeToString(sum[:8]))
|
||||
return fmt.Sprintf("admin-chat:counts:v3:%s:%d:%s:%s:%s:%s", principal.Type, principal.ID, tenancy.ScopeKey(ctx), filter, stage, hex.EncodeToString(sum[:8]))
|
||||
}
|
||||
|
||||
func (r *Repository) loadAdminChatCountsCache(ctx context.Context, principal Principal, filter, stage, keyword string) *AdminConversationCountsDTO {
|
||||
if r.redis == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := r.redis.Get(ctx, r.adminChatCountsCacheKey(principal, filter, stage, keyword)).Bytes()
|
||||
raw, err := r.redis.Get(ctx, r.adminChatCountsCacheKey(ctx, principal, filter, stage, keyword)).Bytes()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
@@ -39,5 +41,5 @@ func (r *Repository) storeAdminChatCountsCache(ctx context.Context, principal Pr
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = r.redis.Set(ctx, r.adminChatCountsCacheKey(principal, filter, stage, keyword), raw, adminChatCountsCacheTTL).Err()
|
||||
_ = r.redis.Set(ctx, r.adminChatCountsCacheKey(ctx, principal, filter, stage, keyword), raw, adminChatCountsCacheTTL).Err()
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
@@ -137,7 +138,11 @@ func (r *Repository) FindConversation(ctx context.Context, principal Principal,
|
||||
// 管理员可以查看任意会话,无需是 participant
|
||||
if principal.Type == "admin" {
|
||||
var conversation model.ChatConversation
|
||||
if err := db.First(&conversation, id).Error; err != nil {
|
||||
query, err := adminConversationScope(ctx, db, principal.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := query.Table("chat_conversations AS c").Select("c.*").Where("c.id = ?", id).First(&conversation).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
@@ -251,8 +256,16 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
|
||||
scene, title, groupCode, welcome := resolveSupportScene(scene)
|
||||
if tenantID > 0 && site == nil {
|
||||
if scope, ok := tenancy.FromContext(ctx); ok && strings.TrimSpace(scope.TenantName) != "" {
|
||||
title = fmt.Sprintf("【%s】%s", scope.TenantName, title)
|
||||
welcome = fmt.Sprintf("您好,欢迎咨询【%s】在线客服!请直接描述您遇到的问题,客服会尽快回复。", scope.TenantName)
|
||||
}
|
||||
}
|
||||
|
||||
if site != nil {
|
||||
title = fmt.Sprintf("【%s】%s", site.SiteName, title)
|
||||
welcome = fmt.Sprintf("您好,欢迎咨询【%s】在线客服!请直接描述您遇到的问题,客服会尽快回复。", site.SiteName)
|
||||
@@ -274,6 +287,9 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
} else {
|
||||
existingQuery = existingQuery.Where("c.distribution_site_id IS NULL OR c.distribution_site_id = 0")
|
||||
}
|
||||
if tenantID > 0 {
|
||||
existingQuery = existingQuery.Where("c.tenant_id = ?", tenantID)
|
||||
}
|
||||
|
||||
err := existingQuery.Order("c.id ASC").Limit(1).Find(&existing).Error
|
||||
if err != nil {
|
||||
@@ -295,6 +311,9 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.ID > 0 && tenantID > 0 && existing.TenantID != tenantID {
|
||||
existing = model.ChatConversation{}
|
||||
}
|
||||
if existing.ID > 0 && existing.SupportScene == "" {
|
||||
_ = tx.Model(&existing).Update("support_scene", SupportSceneGeneral).Error
|
||||
}
|
||||
@@ -314,6 +333,9 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.ID > 0 && tenantID > 0 && existing.TenantID != tenantID {
|
||||
existing = model.ChatConversation{}
|
||||
}
|
||||
}
|
||||
if existing.ID > 0 {
|
||||
conversationID = existing.ID
|
||||
@@ -322,6 +344,7 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
|
||||
now := time.Now()
|
||||
conversation := model.ChatConversation{
|
||||
TenantID: tenantID,
|
||||
Type: ConversationTypeGeneralSupport,
|
||||
SupportScene: scene,
|
||||
Title: title,
|
||||
@@ -347,12 +370,12 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
var supportID uint64
|
||||
if site != nil && site.DefaultSupportGroupID != nil && *site.DefaultSupportGroupID > 0 {
|
||||
var member model.ChatSupportGroupMember
|
||||
if err := tx.Where("group_id = ?", *site.DefaultSupportGroupID).Order("id ASC").First(&member).Error; err == nil && member.AdminID > 0 {
|
||||
if err := tx.Where("group_id = ?", *site.DefaultSupportGroupID).Order("id ASC").First(&member).Error; err == nil && member.AdminID > 0 && adminIsSupport(tx, member.AdminID, tenantID) {
|
||||
supportID = member.AdminID
|
||||
}
|
||||
}
|
||||
if supportID == 0 {
|
||||
supportID = pickSupportAdminForScene(tx, groupCode)
|
||||
supportID = pickSupportAdminForScene(tx, groupCode, tenantID)
|
||||
}
|
||||
|
||||
if supportID > 0 {
|
||||
|
||||
@@ -2,13 +2,14 @@ package chat
|
||||
|
||||
import (
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DefaultSupportAdminID 导出默认客服选择逻辑,供其他业务模块建群时复用。
|
||||
func DefaultSupportAdminID(tx *gorm.DB) uint64 {
|
||||
return defaultSupportAdminID(tx)
|
||||
return defaultSupportAdminID(tx, tenancy.IDFromContext(tx.Statement.Context))
|
||||
}
|
||||
|
||||
// SendSystemMessageForTx 在事务内发送系统文本消息。
|
||||
|
||||
@@ -46,6 +46,7 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
|
||||
// 2. 建会话
|
||||
now := time.Now()
|
||||
conversation := model.ChatConversation{
|
||||
TenantID: listing.SourceTenantID,
|
||||
ListingID: &listing.ID,
|
||||
Type: ConversationTypeListingGroup,
|
||||
Title: listingConversationTitle(listing),
|
||||
@@ -70,16 +71,19 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
|
||||
}
|
||||
|
||||
// 获取收号组客服。分组未配置时回退到开放上传管理员或默认客服。
|
||||
supportID, err := supportgroup.PickSupportAdmin(tx, supportgroup.GroupCodeOwnerOnboarding)
|
||||
supportID, err := supportgroup.PickSupportAdminForTenant(tx, supportgroup.GroupCodeOwnerOnboarding, conversation.TenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if supportID <= 0 {
|
||||
supportID = preferredSupportAdminID
|
||||
if supportID <= 0 {
|
||||
supportID = defaultSupportAdminID(tx)
|
||||
supportID = defaultSupportAdminID(tx, conversation.TenantID)
|
||||
}
|
||||
}
|
||||
if supportID > 0 && conversation.TenantID > 0 && !adminIsSupport(tx, supportID, conversation.TenantID) {
|
||||
supportID = defaultSupportAdminID(tx, conversation.TenantID)
|
||||
}
|
||||
if supportID > 0 {
|
||||
participants = append(participants, model.ChatParticipant{
|
||||
ConversationID: conversation.ID,
|
||||
@@ -97,7 +101,7 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
|
||||
}
|
||||
|
||||
// 4. 取二维码:主站只用主站池,分站只用自己的池。池空则稍后补发,不跨池借用。
|
||||
qrcode, qrcodeImageURL, err := resolveListingQrCode(tx, siteID)
|
||||
qrcode, qrcodeImageURL, err := resolveListingQrCode(tx, siteID, conversation.TenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -108,7 +112,7 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
|
||||
}
|
||||
|
||||
// 5. 发欢迎语
|
||||
welcomeMessage := getListingGroupWelcomeMessage(tx)
|
||||
welcomeMessage := getListingGroupWelcomeMessage(tx, conversation.TenantID)
|
||||
if err := sendSystemMessage(tx, conversation.ID, welcomeMessage); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -124,7 +128,7 @@ func EnsureListingConversation(tx *gorm.DB, listing model.RentalListing, preferr
|
||||
if err := sendSystemMessage(tx, conversation.ID, noQrTip); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := createQrCodeDeliveryTask(tx, conversation.ID); err != nil {
|
||||
if err := createQrCodeDeliveryTask(tx, conversation.ID, conversation.TenantID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -176,7 +180,7 @@ func AddRenterToListingConversation(tx *gorm.DB, listingID uint64, renterID uint
|
||||
}
|
||||
|
||||
// 3. 支付后由卖号组客服接入跟进交接和售后。
|
||||
handoffSupportID, err := supportgroup.PickSupportAdmin(tx, supportgroup.GroupCodeRenterHandoff)
|
||||
handoffSupportID, err := supportgroup.PickSupportAdminForTenant(tx, supportgroup.GroupCodeRenterHandoff, conv.TenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -241,9 +245,13 @@ func listingConversationTitle(listing model.RentalListing) string {
|
||||
return "账号群 " + listing.ListingNo
|
||||
}
|
||||
|
||||
func getListingGroupWelcomeMessage(tx *gorm.DB) string {
|
||||
func getListingGroupWelcomeMessage(tx *gorm.DB, tenantID uint64) string {
|
||||
var cfg model.SystemConfig
|
||||
if err := tx.Where("`key` = ?", listingGroupWelcomeConfigKey).First(&cfg).Error; err == nil && cfg.Value != "" {
|
||||
query := tx.Where("`key` = ?", listingGroupWelcomeConfigKey)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&cfg).Error; err == nil && cfg.Value != "" {
|
||||
return cfg.Value
|
||||
}
|
||||
|
||||
@@ -309,7 +317,7 @@ func updateConversationLastMessage(tx *gorm.DB, conversationID uint64, message *
|
||||
}
|
||||
|
||||
func fetchUnusedQrCode(tx *gorm.DB) (*model.ChatQrCode, error) {
|
||||
return fetchUnusedQrCodeForSite(tx, nil)
|
||||
return fetchUnusedQrCodeForSite(tx, nil, 0)
|
||||
}
|
||||
|
||||
func resolveListingDistributionSiteID(tx *gorm.DB, listing model.RentalListing) (uint64, error) {
|
||||
@@ -337,19 +345,19 @@ func resolveListingDistributionSiteID(tx *gorm.DB, listing model.RentalListing)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func resolveListingQrCode(tx *gorm.DB, siteID uint64) (*model.ChatQrCode, string, error) {
|
||||
func resolveListingQrCode(tx *gorm.DB, siteID, tenantID uint64) (*model.ChatQrCode, string, error) {
|
||||
var scope *uint64
|
||||
if siteID > 0 {
|
||||
scope = &siteID
|
||||
}
|
||||
qrcode, err := fetchUnusedQrCodeForSite(tx, scope)
|
||||
qrcode, err := fetchUnusedQrCodeForSite(tx, scope, tenantID)
|
||||
if err != nil || qrcode == nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return qrcode, qrcode.ImageURL, nil
|
||||
}
|
||||
|
||||
func fetchUnusedQrCodeForSite(tx *gorm.DB, siteID *uint64) (*model.ChatQrCode, error) {
|
||||
func fetchUnusedQrCodeForSite(tx *gorm.DB, siteID *uint64, tenantID uint64) (*model.ChatQrCode, error) {
|
||||
var qrcode model.ChatQrCode
|
||||
now := time.Now()
|
||||
query := tx.Where("status = ?", QrCodeStatusUnused).
|
||||
@@ -360,6 +368,9 @@ func fetchUnusedQrCodeForSite(tx *gorm.DB, siteID *uint64) (*model.ChatQrCode, e
|
||||
} else {
|
||||
query = query.Where("distribution_site_id = ?", *siteID)
|
||||
}
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
err := query.
|
||||
Limit(1).
|
||||
Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
@@ -377,14 +388,14 @@ func fetchUnusedQrCodeForSite(tx *gorm.DB, siteID *uint64) (*model.ChatQrCode, e
|
||||
|
||||
func fetchUnusedQrCodeForConversation(tx *gorm.DB, conversationID uint64) (*model.ChatQrCode, error) {
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.Select("id", "distribution_site_id").First(&conversation, conversationID).Error; err != nil {
|
||||
if err := tx.Select("id", "tenant_id", "distribution_site_id").First(&conversation, conversationID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var siteID *uint64
|
||||
if conversation.DistributionSiteID != nil && *conversation.DistributionSiteID > 0 {
|
||||
siteID = conversation.DistributionSiteID
|
||||
}
|
||||
return fetchUnusedQrCodeForSite(tx, siteID)
|
||||
return fetchUnusedQrCodeForSite(tx, siteID, conversation.TenantID)
|
||||
}
|
||||
|
||||
func markQrCodeAsUsed(tx *gorm.DB, qrcodeID uint64, conversationID uint64) error {
|
||||
@@ -398,8 +409,9 @@ func markQrCodeAsUsed(tx *gorm.DB, qrcodeID uint64, conversationID uint64) error
|
||||
}).Error
|
||||
}
|
||||
|
||||
func createQrCodeDeliveryTask(tx *gorm.DB, conversationID uint64) error {
|
||||
func createQrCodeDeliveryTask(tx *gorm.DB, conversationID, tenantID uint64) error {
|
||||
task := model.ChatQrCodeDeliveryTask{
|
||||
TenantID: tenantID,
|
||||
ConversationID: conversationID,
|
||||
Status: "pending",
|
||||
}
|
||||
@@ -448,6 +460,9 @@ func checkQrCodeStockAndAlert(tx *gorm.DB, conversation *model.ChatConversation)
|
||||
} else {
|
||||
countQuery = countQuery.Where("distribution_site_id IS NULL")
|
||||
}
|
||||
if conversation != nil && conversation.TenantID > 0 {
|
||||
countQuery = countQuery.Where("tenant_id = ?", conversation.TenantID)
|
||||
}
|
||||
var count int64
|
||||
if err := countQuery.Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -459,12 +474,14 @@ func checkQrCodeStockAndAlert(tx *gorm.DB, conversation *model.ChatConversation)
|
||||
|
||||
// 低于阈值:写入站内信(事务内)
|
||||
var csAdmins []model.AdminUser
|
||||
if err := tx.Table("admin_users").
|
||||
adminQuery := tx.Table("admin_users").
|
||||
Joins("JOIN admin_user_roles ON admin_users.id = admin_user_roles.admin_user_id").
|
||||
Joins("JOIN roles ON admin_user_roles.role_id = roles.id").
|
||||
Where("roles.code = ? AND admin_users.status = ?", "cs", "active").
|
||||
Select("admin_users.id").
|
||||
Find(&csAdmins).Error; err != nil {
|
||||
Where("roles.code = ? AND admin_users.status = ?", "cs", "active")
|
||||
if conversation != nil && conversation.TenantID > 0 {
|
||||
adminQuery = adminQuery.Where("admin_user_roles.tenant_id = ?", conversation.TenantID)
|
||||
}
|
||||
if err := adminQuery.Select("admin_users.id").Find(&csAdmins).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -477,6 +494,7 @@ func checkQrCodeStockAndAlert(tx *gorm.DB, conversation *model.ChatConversation)
|
||||
now := time.Now()
|
||||
for _, admin := range csAdmins {
|
||||
entries = append(entries, map[string]interface{}{
|
||||
"tenant_id": conversation.TenantID,
|
||||
"admin_user_id": admin.ID,
|
||||
"type": "system",
|
||||
"title": "二维码库存预警",
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"gorm.io/gorm/clause"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -19,15 +20,18 @@ func (r *Repository) Messages(ctx context.Context, principal Principal, conversa
|
||||
if _, err := r.findParticipant(db, principal, conversationID, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// 管理员需要验证会话存在
|
||||
var count int64
|
||||
if err := db.Model(&model.ChatConversation{}).Where("id = ?", conversationID).Count(&count).Error; err != nil {
|
||||
query := tenantConversationScope(ctx, db.Table("chat_conversations AS c")).Where("c.id = ?", conversationID)
|
||||
if err := query.Count(&count).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, ErrConversationNotFound
|
||||
}
|
||||
} else {
|
||||
if err := ensureAdminConversationAccess(ctx, db, principal.ID, conversationID, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 构建查询
|
||||
@@ -59,7 +63,20 @@ func (r *Repository) SendMessage(ctx context.Context, principal Principal, conve
|
||||
var messageID uint64
|
||||
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 {
|
||||
query := tx.Table("chat_conversations AS c").Select("c.*")
|
||||
if principal.Type == "admin" {
|
||||
var err error
|
||||
query, err = adminConversationScope(ctx, query, principal.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
query = tenantConversationScope(ctx, query)
|
||||
}
|
||||
if err := query.Clauses(clause.Locking{Strength: "UPDATE"}).Where("c.id = ?", conversationID).First(&conversation).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConversationNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if conversation.Status != "active" {
|
||||
@@ -168,6 +185,7 @@ func (r *Repository) SendMessage(ctx context.Context, principal Principal, conve
|
||||
CreatedAt: msg.CreatedAt.Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
tenantScopedEvent(r.db.WithContext(ctx), event)
|
||||
r.hub.NotifyConversation(conversationID, event)
|
||||
// 同时广播给所有在线客服,使「未分配 / 全部」视图实时刷新;
|
||||
// 参与者客服会重复收到,由前端按消息 id 去重。
|
||||
@@ -180,6 +198,9 @@ func (r *Repository) MarkRead(ctx context.Context, principal Principal, conversa
|
||||
updated := false
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if principal.Type == "admin" {
|
||||
if err := ensureAdminConversationAccess(ctx, tx, principal.ID, conversationID, true); err != nil {
|
||||
return err
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.Select("id", "last_message_id").First(&conversation, conversationID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -224,6 +245,15 @@ func (r *Repository) MarkRead(ctx context.Context, principal Principal, conversa
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var count int64
|
||||
if err := tenantConversationScope(ctx, tx.Table("chat_conversations AS c")).
|
||||
Where("c.id = ?", conversationID).
|
||||
Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return ErrConversationNotFound
|
||||
}
|
||||
updated = true
|
||||
return tx.Model(participant).Update("last_read_at", now).Error
|
||||
})
|
||||
@@ -239,6 +269,7 @@ func (r *Repository) MarkRead(ctx context.Context, principal Principal, conversa
|
||||
ReaderID: principal.ID,
|
||||
ReadAt: now.Format(time.RFC3339),
|
||||
}
|
||||
tenantScopedEvent(r.db.WithContext(ctx), event)
|
||||
r.hub.NotifyConversation(conversationID, event)
|
||||
// 同时广播给所有在线客服,覆盖未分配会话中非参与者客服的「已读」刷新。
|
||||
r.hub.NotifyAllAdmins(event)
|
||||
@@ -250,6 +281,19 @@ func (r *Repository) MarkRead(ctx context.Context, principal Principal, conversa
|
||||
func (r *Repository) MarkAllAdminConversationsRead(ctx context.Context, adminID uint64) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
platform, err := adminHasPlatformScope(tx, adminID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
accessSQL := ""
|
||||
accessArgs := make([]any, 0)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 && !platform {
|
||||
condition, args := conversationTenantAccessCondition("c")
|
||||
accessSQL = " AND " + condition
|
||||
for range args {
|
||||
accessArgs = append(accessArgs, tenantID)
|
||||
}
|
||||
}
|
||||
// 先补齐状态行,再更新游标。拆成两步可兼容本地 MySQL/MariaDB 对
|
||||
// INSERT ... SELECT 同表读取并 ON DUPLICATE KEY UPDATE 的限制。
|
||||
if err := tx.Exec(`
|
||||
@@ -259,7 +303,9 @@ func (r *Repository) MarkAllAdminConversationsRead(ctx context.Context, adminID
|
||||
FROM chat_conversations AS c
|
||||
LEFT JOIN chat_admin_conversation_states AS existing
|
||||
ON existing.conversation_id = c.id AND existing.admin_user_id = ?
|
||||
WHERE existing.id IS NULL`, adminID, now, adminID).Error; err != nil {
|
||||
WHERE existing.id IS NULL`+accessSQL,
|
||||
append([]any{adminID, now, adminID}, accessArgs...)...,
|
||||
).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Exec(`
|
||||
@@ -270,6 +316,8 @@ func (r *Repository) MarkAllAdminConversationsRead(ctx context.Context, adminID
|
||||
cas.updated_at = CURRENT_TIMESTAMP
|
||||
WHERE cas.admin_user_id = ?
|
||||
AND c.last_message_id IS NOT NULL
|
||||
AND cas.last_read_message_id < c.last_message_id`, now, adminID).Error
|
||||
AND cas.last_read_message_id < c.last_message_id`+accessSQL,
|
||||
append([]any{now, adminID}, accessArgs...)...,
|
||||
).Error
|
||||
})
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ type conversationRow struct {
|
||||
}
|
||||
|
||||
func (r *Repository) conversationQuery(ctx context.Context, principal Principal) *gorm.DB {
|
||||
return r.db.WithContext(ctx).Table("chat_conversations AS c").
|
||||
query := r.db.WithContext(ctx).Table("chat_conversations AS c").
|
||||
Select(`c.id, c.order_id, c.listing_id, c.distribution_site_id, c.type, c.support_scene, c.title, c.status, c.last_message_id,
|
||||
c.last_message_preview, c.last_message_at, c.created_at, c.updated_at, cp.role,
|
||||
(
|
||||
@@ -53,6 +53,7 @@ func (r *Repository) conversationQuery(ctx context.Context, principal Principal)
|
||||
) 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)
|
||||
return tenantConversationScope(ctx, query)
|
||||
}
|
||||
|
||||
func (r *Repository) CountUnreadMessages(ctx context.Context, principal Principal, siteCode ...string) (int64, error) {
|
||||
@@ -82,6 +83,7 @@ func (r *Repository) CountUnreadMessages(ctx context.Context, principal Principa
|
||||
filter, args := userSiteConversationFilter(siteID, principal.ID)
|
||||
query = query.Where(filter, args...)
|
||||
}
|
||||
query = tenantConversationScope(ctx, query)
|
||||
|
||||
var total int64
|
||||
err = query.Count(&total).Error
|
||||
@@ -360,12 +362,12 @@ func (row conversationRow) toDTO(participants []ParticipantDTO) ConversationDTO
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
}
|
||||
func defaultSupportAdminID(tx *gorm.DB) uint64 {
|
||||
if supportID := configuredDefaultSupportAdminID(tx); supportID > 0 {
|
||||
func defaultSupportAdminID(tx *gorm.DB, tenantID uint64) uint64 {
|
||||
if supportID := configuredDefaultSupportAdminID(tx, tenantID); supportID > 0 {
|
||||
return supportID
|
||||
}
|
||||
|
||||
adminIDs, err := supportAdminIDs(tx)
|
||||
adminIDs, err := supportAdminIDs(tx, tenantID)
|
||||
if err != nil || len(adminIDs) == 0 {
|
||||
return 0
|
||||
}
|
||||
@@ -402,33 +404,44 @@ func defaultSupportAdminID(tx *gorm.DB) uint64 {
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func configuredDefaultSupportAdminID(tx *gorm.DB) uint64 {
|
||||
func configuredDefaultSupportAdminID(tx *gorm.DB, tenantID uint64) uint64 {
|
||||
var cfg model.SystemConfig
|
||||
if err := tx.Where("`key` = ?", "chat.default_support_admin_id").First(&cfg).Error; err == nil {
|
||||
query := tx.Where("`key` = ?", "chat.default_support_admin_id")
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&cfg).Error; err == nil {
|
||||
id, parseErr := strconv.ParseUint(cfg.Value, 10, 64)
|
||||
if parseErr == nil && id > 0 && adminIsSupport(tx, id) {
|
||||
if parseErr == nil && id > 0 && adminIsSupport(tx, id, tenantID) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func supportAdminIDs(tx *gorm.DB) ([]uint64, error) {
|
||||
func supportAdminIDs(tx *gorm.DB, tenantID uint64) ([]uint64, error) {
|
||||
var adminIDs []uint64
|
||||
err := tx.Table("admin_users AS au").
|
||||
query := tx.Table("admin_users AS au").
|
||||
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").
|
||||
Where("au.status = ? AND r.code = ?", "active", defaultSupportRoleCode).
|
||||
Where("au.status = ? AND r.code = ?", "active", defaultSupportRoleCode)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("aur.tenant_id = ?", tenantID)
|
||||
}
|
||||
err := query.
|
||||
Order("CASE au.support_status WHEN 'online' THEN 0 WHEN 'busy' THEN 1 ELSE 2 END, au.id ASC").
|
||||
Pluck("au.id", &adminIDs).Error
|
||||
return adminIDs, err
|
||||
}
|
||||
func adminIsSupport(tx *gorm.DB, id uint64) bool {
|
||||
func adminIsSupport(tx *gorm.DB, id, tenantID uint64) bool {
|
||||
var count int64
|
||||
if err := tx.Table("admin_users AS au").
|
||||
query := tx.Table("admin_users AS au").
|
||||
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").
|
||||
Where("au.id = ? AND au.status = ? AND r.code = ?", id, "active", defaultSupportRoleCode).
|
||||
Count(&count).Error; err != nil {
|
||||
Where("au.id = ? AND au.status = ? AND r.code = ?", id, "active", defaultSupportRoleCode)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("aur.tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.Count(&count).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
return count > 0
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"gorm.io/gorm/clause"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
// QrCodeStatus 二维码状态常量
|
||||
@@ -97,10 +98,12 @@ type QrCodeOCRConfig struct {
|
||||
|
||||
// CreateQrCode 创建二维码
|
||||
func (r *Repository) CreateQrCode(ctx context.Context, adminID uint64, req CreateQrCodeRequest) (*model.ChatQrCode, error) {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var qrcode model.ChatQrCode
|
||||
var deliveredMessages []model.ChatMessage
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
qrcode = model.ChatQrCode{
|
||||
TenantID: tenantID,
|
||||
ImageURL: req.ImageURL,
|
||||
GroupName: req.GroupName,
|
||||
Status: QrCodeStatusUnused,
|
||||
@@ -119,7 +122,7 @@ func (r *Repository) CreateQrCode(ctx context.Context, adminID uint64, req Creat
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx)
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx, tenantID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -132,6 +135,7 @@ func (r *Repository) CreateQrCode(ctx context.Context, adminID uint64, req Creat
|
||||
|
||||
// BatchCreateQrCode 批量创建二维码
|
||||
func (r *Repository) BatchCreateQrCode(ctx context.Context, adminID uint64, req BatchCreateQrCodeRequest) ([]model.ChatQrCode, error) {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
var qrcodes []model.ChatQrCode
|
||||
var deliveredMessages []model.ChatMessage
|
||||
defaultExpires := time.Now().Add(7 * 24 * time.Hour)
|
||||
@@ -139,6 +143,7 @@ func (r *Repository) BatchCreateQrCode(ctx context.Context, adminID uint64, req
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, item := range req.Items {
|
||||
qr := model.ChatQrCode{
|
||||
TenantID: tenantID,
|
||||
ImageURL: item.ImageURL,
|
||||
GroupName: item.GroupName,
|
||||
Status: QrCodeStatusUnused,
|
||||
@@ -156,7 +161,7 @@ func (r *Repository) BatchCreateQrCode(ctx context.Context, adminID uint64, req
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx)
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx, tenantID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -177,12 +182,17 @@ func (r *Repository) ListQrCodes(ctx context.Context, req QrCodeListRequest) ([]
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
baseQuery := func() *gorm.DB {
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id IS NULL")
|
||||
if tenantID > 0 {
|
||||
query = query.Where("q.tenant_id = ?", tenantID)
|
||||
}
|
||||
return applyQrCodeListFilters(
|
||||
r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id IS NULL"),
|
||||
query,
|
||||
req,
|
||||
now,
|
||||
)
|
||||
@@ -295,25 +305,40 @@ func parseQrCodeFilterTime(value string) (time.Time, bool) {
|
||||
func (r *Repository) GetQrCodeStats(ctx context.Context) (*QrCodeStats, error) {
|
||||
stats := &QrCodeStats{}
|
||||
now := time.Now()
|
||||
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
mainPool := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Where("distribution_site_id IS NULL")
|
||||
if tenantID > 0 {
|
||||
mainPool = mainPool.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := mainPool.Count(&stats.TotalCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
usedQuery := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL")
|
||||
if tenantID > 0 {
|
||||
usedQuery = usedQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := usedQuery.
|
||||
Where("status = ?", QrCodeStatusUsed).
|
||||
Count(&stats.UsedCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
disabledQuery := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL")
|
||||
if tenantID > 0 {
|
||||
disabledQuery = disabledQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := disabledQuery.
|
||||
Where("status = ?", QrCodeStatusDisabled).
|
||||
Count(&stats.DisabledCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL").
|
||||
unusedQuery := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).
|
||||
Where("distribution_site_id IS NULL")
|
||||
if tenantID > 0 {
|
||||
unusedQuery = unusedQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := unusedQuery.
|
||||
Where("status = ?", QrCodeStatusUnused).
|
||||
Where("expires_at IS NULL OR expires_at > ?", now).
|
||||
Count(&stats.UnusedCount).Error; err != nil {
|
||||
@@ -331,7 +356,11 @@ func (r *Repository) GetQrCodeOCRConfig(ctx context.Context) (*QrCodeOCRConfig,
|
||||
}
|
||||
var rows []model.SystemConfig
|
||||
keys := []string{qrCodeOCRTokenConfigKey, qrCodeOCRJobURLConfigKey, qrCodeOCRModelConfigKey}
|
||||
if err := r.db.WithContext(ctx).Where("`key` IN ?", keys).Find(&rows).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("`key` IN ?", keys)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
@@ -354,7 +383,11 @@ func (r *Repository) GetQrCodeOCRConfig(ctx context.Context) (*QrCodeOCRConfig,
|
||||
// UpdateQrCode 更新二维码
|
||||
func (r *Repository) UpdateQrCode(ctx context.Context, id uint64, req UpdateQrCodeRequest) error {
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id IS NULL").First(&qrcode, id).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("distribution_site_id IS NULL")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
@@ -409,7 +442,11 @@ func qrcodeWasIssued(qrcode model.ChatQrCode) bool {
|
||||
// DeleteQrCode 删除二维码
|
||||
func (r *Repository) DeleteQrCode(ctx context.Context, id uint64) error {
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id IS NULL").First(&qrcode, id).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("distribution_site_id IS NULL")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
@@ -425,7 +462,11 @@ func (r *Repository) BatchDeleteQrCodes(ctx context.Context, ids []uint64) (int6
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
result := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id IS NULL", ids).Delete(&model.ChatQrCode{})
|
||||
query := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id IS NULL", ids)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
result := query.Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
@@ -466,13 +507,16 @@ func (r *Repository) markQrCodeAsUsed(tx *gorm.DB, qrcodeID uint64, conversation
|
||||
}).Error
|
||||
}
|
||||
|
||||
func deliverPendingQrCodes(tx *gorm.DB) ([]model.ChatMessage, error) {
|
||||
func deliverPendingQrCodes(tx *gorm.DB, tenantID uint64) ([]model.ChatMessage, error) {
|
||||
deliveredMessages := make([]model.ChatMessage, 0)
|
||||
skipped := make([]uint64, 0)
|
||||
for {
|
||||
var task model.ChatQrCodeDeliveryTask
|
||||
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("status = ?", "pending")
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if len(skipped) > 0 {
|
||||
query = query.Where("id NOT IN ?", skipped)
|
||||
}
|
||||
@@ -548,12 +592,17 @@ func (r *Repository) ListSiteQrCodes(ctx context.Context, siteID uint64, req QrC
|
||||
req.Limit = 20
|
||||
}
|
||||
now := time.Now()
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
baseQuery := func() *gorm.DB {
|
||||
query := r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id = ?", siteID)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("q.tenant_id = ?", tenantID)
|
||||
}
|
||||
return applyQrCodeListFilters(
|
||||
r.db.WithContext(ctx).
|
||||
Table("chat_qrcode_pool AS q").
|
||||
Joins("LEFT JOIN chat_conversations AS c ON c.id = q.conversation_id").
|
||||
Where("q.distribution_site_id = ?", siteID),
|
||||
query,
|
||||
req,
|
||||
now,
|
||||
)
|
||||
@@ -580,8 +629,13 @@ func (r *Repository) GetSiteQrCodeStats(ctx context.Context, siteID uint64) (*Qr
|
||||
}
|
||||
stats := &QrCodeStats{}
|
||||
now := time.Now()
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
base := func() *gorm.DB {
|
||||
return r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Where("distribution_site_id = ?", siteID)
|
||||
query := r.db.WithContext(ctx).Model(&model.ChatQrCode{}).Where("distribution_site_id = ?", siteID)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query
|
||||
}
|
||||
if err := base().Count(&stats.TotalCount).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -608,9 +662,11 @@ func (r *Repository) BatchCreateSiteQrCode(ctx context.Context, adminID, siteID
|
||||
var qrcodes []model.ChatQrCode
|
||||
var deliveredMessages []model.ChatMessage
|
||||
defaultExpires := time.Now().Add(7 * 24 * time.Hour)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for _, item := range req.Items {
|
||||
qr := model.ChatQrCode{
|
||||
TenantID: tenantID,
|
||||
ImageURL: item.ImageURL,
|
||||
GroupName: item.GroupName,
|
||||
DistributionSiteID: &siteID,
|
||||
@@ -629,7 +685,7 @@ func (r *Repository) BatchCreateSiteQrCode(ctx context.Context, adminID, siteID
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx)
|
||||
deliveredMessages, err = deliverPendingQrCodes(tx, tenantID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -644,7 +700,11 @@ func (r *Repository) UpdateSiteQrCode(ctx context.Context, siteID, id uint64, re
|
||||
return err
|
||||
}
|
||||
var qrcode model.ChatQrCode
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).First(&qrcode, id).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&qrcode, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrQrCodeNotFound
|
||||
}
|
||||
@@ -691,7 +751,11 @@ func (r *Repository) DeleteSiteQrCode(ctx context.Context, siteID, id uint64) er
|
||||
if err := r.ensureDistributionSite(ctx, siteID); err != nil {
|
||||
return err
|
||||
}
|
||||
result := r.db.WithContext(ctx).Where("id = ? AND distribution_site_id = ?", id, siteID).Delete(&model.ChatQrCode{})
|
||||
query := r.db.WithContext(ctx).Where("id = ? AND distribution_site_id = ?", id, siteID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
result := query.Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
@@ -708,7 +772,11 @@ func (r *Repository) BatchDeleteSiteQrCodes(ctx context.Context, siteID uint64,
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
result := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id = ?", ids, siteID).Delete(&model.ChatQrCode{})
|
||||
query := r.db.WithContext(ctx).Where("id IN ? AND distribution_site_id = ?", ids, siteID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
result := query.Delete(&model.ChatQrCode{})
|
||||
if result.Error != nil {
|
||||
return 0, result.Error
|
||||
}
|
||||
@@ -736,6 +804,7 @@ func (r *Repository) notifyDeliveredQrCodeMessages(messages []model.ChatMessage)
|
||||
CreatedAt: msg.CreatedAt.Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
tenantScopedEvent(r.db, event)
|
||||
r.hub.NotifyConversation(msg.ConversationID, event)
|
||||
r.hub.NotifyAllAdmins(event)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -480,6 +481,55 @@ func TestBatchCreateQrCodeDeliversPendingTask(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestQrCodeReplenishmentDoesNotCrossTenant(t *testing.T) {
|
||||
db := setupQrCodeTestDB(t)
|
||||
tenantA := model.Tenant{Code: "qr-a", Name: "二维码 A", Status: "active"}
|
||||
tenantB := model.Tenant{Code: "qr-b", Name: "二维码 B", Status: "active"}
|
||||
if err := db.Create(&tenantA).Error; err != nil {
|
||||
t.Fatalf("创建租户 A: %v", err)
|
||||
}
|
||||
if err := db.Create(&tenantB).Error; err != nil {
|
||||
t.Fatalf("创建租户 B: %v", err)
|
||||
}
|
||||
convA := model.ChatConversation{TenantID: tenantA.ID, Title: "A 账号群", Type: ConversationTypeListingGroup, Status: "active"}
|
||||
convB := model.ChatConversation{TenantID: tenantB.ID, Title: "B 账号群", Type: ConversationTypeListingGroup, Status: "active"}
|
||||
if err := db.Create(&convA).Error; err != nil {
|
||||
t.Fatalf("创建会话 A: %v", err)
|
||||
}
|
||||
if err := db.Create(&convB).Error; err != nil {
|
||||
t.Fatalf("创建会话 B: %v", err)
|
||||
}
|
||||
taskA := model.ChatQrCodeDeliveryTask{TenantID: tenantA.ID, ConversationID: convA.ID, Status: "pending"}
|
||||
taskB := model.ChatQrCodeDeliveryTask{TenantID: tenantB.ID, ConversationID: convB.ID, Status: "pending"}
|
||||
if err := db.Create(&[]model.ChatQrCodeDeliveryTask{taskA, taskB}).Error; err != nil {
|
||||
t.Fatalf("创建补发任务: %v", err)
|
||||
}
|
||||
repo := NewRepository(db, nil, nil)
|
||||
ctxA := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantA.ID})
|
||||
qrcodes, err := repo.BatchCreateQrCode(ctxA, 1, BatchCreateQrCodeRequest{
|
||||
Items: []CreateQrCodeRequest{{ImageURL: "/api/files/object?key=qrcode/tenant-a.png", GroupName: "A 群"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("创建租户 A 二维码: %v", err)
|
||||
}
|
||||
if len(qrcodes) != 1 || qrcodes[0].TenantID != tenantA.ID {
|
||||
t.Fatalf("二维码租户 = %+v", qrcodes)
|
||||
}
|
||||
var savedA, savedB model.ChatQrCodeDeliveryTask
|
||||
if err := db.Where("conversation_id = ?", convA.ID).First(&savedA).Error; err != nil {
|
||||
t.Fatalf("查询任务 A: %v", err)
|
||||
}
|
||||
if err := db.Where("conversation_id = ?", convB.ID).First(&savedB).Error; err != nil {
|
||||
t.Fatalf("查询任务 B: %v", err)
|
||||
}
|
||||
if savedA.Status != "sent" {
|
||||
t.Fatalf("任务 A 状态 = %q, want sent", savedA.Status)
|
||||
}
|
||||
if savedB.Status != "pending" {
|
||||
t.Fatalf("任务 B 状态 = %q, want pending", savedB.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureListingConversationIgnoresFixedQrAndUsesSitePool(t *testing.T) {
|
||||
db := setupQrCodeTestDB(t)
|
||||
site := model.DistributionSite{
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -22,6 +23,9 @@ func (r *Repository) UpdateRemark(ctx context.Context, principal Principal, conv
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
db := r.db.WithContext(ctx)
|
||||
if err := ensureAdminConversationAccess(ctx, db, principal.ID, conversationID, false); err != nil {
|
||||
return err
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := db.Select("id").First(&conversation, conversationID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
@@ -41,7 +45,11 @@ func (r *Repository) UpdateRemark(ctx context.Context, principal Principal, conv
|
||||
}
|
||||
func (r *Repository) ListQuickReplies(ctx context.Context, adminID uint64) ([]QuickReplyDTO, error) {
|
||||
var replies []model.ChatQuickReply
|
||||
err := r.db.WithContext(ctx).Where("admin_user_id = ? OR admin_user_id = 0", adminID).
|
||||
query := r.db.WithContext(ctx).Where("admin_user_id = ? OR admin_user_id = 0", adminID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
err := query.
|
||||
Order("admin_user_id DESC, sort_order ASC, id ASC").
|
||||
Find(&replies).Error
|
||||
if err != nil {
|
||||
@@ -66,6 +74,7 @@ func (r *Repository) CreateQuickReply(ctx context.Context, adminID uint64, req C
|
||||
ownerID = 0
|
||||
}
|
||||
reply := model.ChatQuickReply{
|
||||
TenantID: tenancy.IDFromContext(ctx),
|
||||
AdminUserID: ownerID,
|
||||
Title: req.Title,
|
||||
Content: req.Content,
|
||||
@@ -85,6 +94,9 @@ func (r *Repository) CreateQuickReply(ctx context.Context, adminID uint64, req C
|
||||
}
|
||||
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)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
updates := map[string]interface{}{}
|
||||
if req.Title != "" {
|
||||
updates["title"] = req.Title
|
||||
@@ -101,32 +113,51 @@ func (r *Repository) UpdateQuickReply(ctx context.Context, adminID uint64, reply
|
||||
return query.Updates(updates).Error
|
||||
}
|
||||
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
|
||||
query := r.db.WithContext(ctx).Where("id = ? AND admin_user_id = ?", replyID, adminID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query.Delete(&model.ChatQuickReply{}).Error
|
||||
}
|
||||
func (r *Repository) GetAutoWelcomeMessage(ctx context.Context) string {
|
||||
var cfg model.SystemConfig
|
||||
if err := r.db.WithContext(ctx).Where("`key` = ?", autoWelcomeConfigKey).First(&cfg).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("`key` = ?", autoWelcomeConfigKey)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&cfg).Error; err != nil {
|
||||
return defaultAutoWelcomeMessage
|
||||
}
|
||||
return cfg.Value
|
||||
}
|
||||
func (r *Repository) UpdateAutoWelcomeMessage(ctx context.Context, message string) error {
|
||||
return r.db.WithContext(ctx).Model(&model.SystemConfig{}).
|
||||
Where("`key` = ?", autoWelcomeConfigKey).
|
||||
query := r.db.WithContext(ctx).Model(&model.SystemConfig{}).
|
||||
Where("`key` = ?", autoWelcomeConfigKey)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query.
|
||||
Update("value", message).Error
|
||||
}
|
||||
|
||||
func (r *Repository) GetListingGroupWelcomeMessage(ctx context.Context) string {
|
||||
var cfg model.SystemConfig
|
||||
if err := r.db.WithContext(ctx).Where("`key` = ?", listingGroupWelcomeConfigKey).First(&cfg).Error; err != nil {
|
||||
query := r.db.WithContext(ctx).Where("`key` = ?", listingGroupWelcomeConfigKey)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&cfg).Error; err != nil {
|
||||
return defaultListingGroupWelcome
|
||||
}
|
||||
return cfg.Value
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateListingGroupWelcomeMessage(ctx context.Context, message string) error {
|
||||
return r.db.WithContext(ctx).Model(&model.SystemConfig{}).
|
||||
Where("`key` = ?", listingGroupWelcomeConfigKey).
|
||||
query := r.db.WithContext(ctx).Model(&model.SystemConfig{}).
|
||||
Where("`key` = ?", listingGroupWelcomeConfigKey)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query.
|
||||
Update("value", message).Error
|
||||
}
|
||||
|
||||
@@ -92,7 +92,12 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
|
||||
siteID = order.DistributionSiteID
|
||||
}
|
||||
now := time.Now()
|
||||
tenantID := order.BuyerTenantID
|
||||
if tenantID == 0 {
|
||||
tenantID = order.SourceTenantID
|
||||
}
|
||||
conversation := model.ChatConversation{
|
||||
TenantID: tenantID,
|
||||
OrderID: &order.ID,
|
||||
DistributionSiteID: siteID,
|
||||
Type: "order_group",
|
||||
@@ -119,7 +124,7 @@ func EnsureOrderConversation(tx *gorm.DB, order model.RentalOrder) (*model.ChatC
|
||||
JoinedAt: now,
|
||||
},
|
||||
}
|
||||
if supportID := defaultSupportAdminID(tx); supportID > 0 {
|
||||
if supportID := defaultSupportAdminID(tx, tenantID); supportID > 0 {
|
||||
participants = append(participants, model.ChatParticipant{
|
||||
ConversationID: conversation.ID,
|
||||
ParticipantType: "admin",
|
||||
@@ -137,7 +142,11 @@ 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 != "" {
|
||||
configQuery := tx.Where("`key` = ?", "chat.auto_welcome_message")
|
||||
if tenantID > 0 {
|
||||
configQuery = configQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := configQuery.First(&cfg).Error; err == nil && cfg.Value != "" {
|
||||
autoMessage = cfg.Value
|
||||
}
|
||||
message := model.ChatMessage{
|
||||
@@ -167,6 +176,7 @@ func (r *Repository) NotifyNewConversation(conversationID uint64) {
|
||||
Type: "conversation_updated",
|
||||
ConversationID: conversationID,
|
||||
}
|
||||
tenantScopedEvent(r.db, event)
|
||||
r.hub.NotifyConversation(conversationID, event)
|
||||
// 新会话(如未分配的平台咨询)需让所有在线客服的列表实时出现。
|
||||
r.hub.NotifyAllAdmins(event)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -38,15 +39,19 @@ func (r *Repository) TransferConversation(ctx context.Context, principal Princip
|
||||
if principal.Type != "admin" {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
query, err := adminConversationScope(ctx, tx, principal.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.First(&conversation, conversationID).Error; err != nil {
|
||||
if err := query.Table("chat_conversations AS c").Select("c.*").Where("c.id = ?", conversationID).First(&conversation).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConversationNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
// 验证目标客服存在、活跃且拥有客服角色,避免转接给超级管理员。
|
||||
if !adminIsSupport(tx, toAdminID) {
|
||||
if !adminIsSupport(tx, toAdminID, conversation.TenantID) {
|
||||
return fmt.Errorf("目标客服不存在、已禁用或不是客服角色")
|
||||
}
|
||||
// 检查目标客服是否已有该会话
|
||||
@@ -94,8 +99,9 @@ func (r *Repository) TransferConversation(ctx context.Context, principal Princip
|
||||
return nil
|
||||
})
|
||||
if err == nil && r.hub != nil {
|
||||
r.hub.NotifyConversation(conversationID, &chathub.ChatEvent{Type: "conversation_updated", ConversationID: conversationID})
|
||||
r.hub.NotifyAllAdmins(&chathub.ChatEvent{Type: "conversation_updated", ConversationID: conversationID})
|
||||
event := tenantScopedEvent(r.db.WithContext(ctx), &chathub.ChatEvent{Type: "conversation_updated", ConversationID: conversationID})
|
||||
r.hub.NotifyConversation(conversationID, event)
|
||||
r.hub.NotifyAllAdmins(event)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -108,11 +114,16 @@ func (r *Repository) GetAvailableSupportAdmins(ctx context.Context) ([]SupportAd
|
||||
SupportStatus string
|
||||
}
|
||||
var admins []adminRow
|
||||
err := db.Table("admin_users AS au").
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
query := 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").
|
||||
Where("au.status = ? AND r.code = ?", "active", defaultSupportRoleCode).
|
||||
Where("au.status = ? AND r.code = ?", "active", defaultSupportRoleCode)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("aur.tenant_id = ?", tenantID)
|
||||
}
|
||||
err := query.
|
||||
Order("CASE au.support_status WHEN 'online' THEN 0 WHEN 'busy' THEN 1 ELSE 2 END, au.id ASC").
|
||||
Scan(&admins).Error
|
||||
if err != nil {
|
||||
@@ -305,6 +316,12 @@ func (r *Repository) adminConversationBase(ctx context.Context, principal Princi
|
||||
Joins("LEFT JOIN chat_admin_conversation_states AS cas ON cas.conversation_id = c.id AND cas.admin_user_id = ?", principal.ID).
|
||||
Joins("LEFT JOIN rental_orders AS explicit_lo ON explicit_lo.id = c.order_id").
|
||||
Joins("LEFT JOIN rental_listings AS l ON l.id = COALESCE(explicit_lo.listing_id, c.listing_id)")
|
||||
scoped, err := adminConversationScope(ctx, db, principal.ID)
|
||||
if err == nil {
|
||||
db = scoped
|
||||
} else {
|
||||
db = tenantConversationScope(ctx, db)
|
||||
}
|
||||
if keyword != "" {
|
||||
upper := strings.ToUpper(keyword)
|
||||
if isPhoneKeyword(keyword) {
|
||||
|
||||
@@ -35,12 +35,12 @@ func resolveSupportScene(raw string) (scene, title, groupCode, welcome string) {
|
||||
}
|
||||
|
||||
// pickSupportAdminForScene 按分组选人;分组无成员或失败时回退默认客服逻辑。
|
||||
func pickSupportAdminForScene(tx *gorm.DB, groupCode string) uint64 {
|
||||
func pickSupportAdminForScene(tx *gorm.DB, groupCode string, tenantID uint64) uint64 {
|
||||
groupCode = strings.TrimSpace(groupCode)
|
||||
if groupCode != "" {
|
||||
if id, err := supportgroup.PickSupportAdmin(tx, groupCode); err == nil && id > 0 {
|
||||
if id, err := supportgroup.PickSupportAdminForTenant(tx, groupCode, tenantID); err == nil && id > 0 {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return defaultSupportAdminID(tx)
|
||||
return defaultSupportAdminID(tx, tenantID)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// conversationTenantAccessCondition 让跨站订单的买方租户和货源租户都能访问同一会话。
|
||||
// 发布群还可能通过后续订单被买方租客加入,因此额外检查 listing_id 关联订单。
|
||||
func conversationTenantAccessCondition(alias string) (string, []any) {
|
||||
condition := `(
|
||||
` + alias + `.tenant_id = ?
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM rental_orders ro
|
||||
WHERE ro.id = ` + alias + `.order_id
|
||||
AND (ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM rental_listings rl
|
||||
WHERE rl.id = ` + alias + `.listing_id
|
||||
AND rl.source_tenant_id = ?
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM rental_orders rlo
|
||||
WHERE rlo.listing_id = ` + alias + `.listing_id
|
||||
AND rlo.buyer_tenant_id = ?
|
||||
)
|
||||
)`
|
||||
return condition, []any{0, 0, 0, 0, 0}
|
||||
}
|
||||
|
||||
func tenantConversationScope(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return db
|
||||
}
|
||||
condition, args := conversationTenantAccessCondition("c")
|
||||
for index := range args {
|
||||
args[index] = tenantID
|
||||
}
|
||||
return db.Where(condition, args...)
|
||||
}
|
||||
|
||||
func adminHasPlatformScope(db *gorm.DB, adminID uint64) (bool, error) {
|
||||
if db == nil || adminID == 0 {
|
||||
return false, nil
|
||||
}
|
||||
var count int64
|
||||
err := db.Session(&gorm.Session{NewDB: true}).Table("admin_user_roles AS aur").
|
||||
Joins("JOIN roles AS r ON r.id = aur.role_id").
|
||||
Where("aur.admin_user_id = ? AND aur.tenant_id = 0 AND r.code = ?", adminID, "super_admin").
|
||||
Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func adminConversationScope(ctx context.Context, db *gorm.DB, adminID uint64) (*gorm.DB, error) {
|
||||
platform, err := adminHasPlatformScope(db, adminID)
|
||||
if err != nil || platform {
|
||||
return db, err
|
||||
}
|
||||
return tenantConversationScope(ctx, db), nil
|
||||
}
|
||||
|
||||
func ensureAdminConversationAccess(ctx context.Context, tx *gorm.DB, adminID, conversationID uint64, lock bool) error {
|
||||
query, err := adminConversationScope(ctx, tx, adminID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
query = query.Table("chat_conversations AS c").Select("c.id").Where("c.id = ?", conversationID)
|
||||
if lock {
|
||||
query = query.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := query.First(&conversation).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConversationNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func conversationTenantIDs(tx *gorm.DB, conversationID uint64) ([]uint64, error) {
|
||||
var conversation model.ChatConversation
|
||||
if err := tx.Select("id", "tenant_id", "order_id", "listing_id").First(&conversation, conversationID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := []uint64{conversation.TenantID}
|
||||
if conversation.OrderID != nil {
|
||||
var order model.RentalOrder
|
||||
if err := tx.Select("buyer_tenant_id", "source_tenant_id").First(&order, *conversation.OrderID).Error; err == nil {
|
||||
ids = append(ids, order.BuyerTenantID, order.SourceTenantID)
|
||||
}
|
||||
}
|
||||
if conversation.ListingID != nil {
|
||||
var listing model.RentalListing
|
||||
if err := tx.Select("source_tenant_id").First(&listing, *conversation.ListingID).Error; err == nil {
|
||||
ids = append(ids, listing.SourceTenantID)
|
||||
}
|
||||
}
|
||||
return uniqueIDs(ids), nil
|
||||
}
|
||||
|
||||
func tenantScopedEvent(tx *gorm.DB, event *chathub.ChatEvent) *chathub.ChatEvent {
|
||||
if event == nil || tx == nil || event.ConversationID == 0 {
|
||||
return event
|
||||
}
|
||||
ids, err := conversationTenantIDs(tx, event.ConversationID)
|
||||
if err == nil {
|
||||
event.TenantIDs = ids
|
||||
}
|
||||
return event
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAdminConversationListIsTenantScopedAndPlatformCanSeeAll(t *testing.T) {
|
||||
db := setupTenantChatTestDB(t)
|
||||
tenantA := model.Tenant{Code: "tenant-chat-a", Name: "大锤测试", Status: "active"}
|
||||
tenantB := model.Tenant{Code: "tenant-chat-b", Name: "解忧测试", Status: "active"}
|
||||
if err := db.Create(&tenantA).Error; err != nil {
|
||||
t.Fatalf("创建租户 A: %v", err)
|
||||
}
|
||||
if err := db.Create(&tenantB).Error; err != nil {
|
||||
t.Fatalf("创建租户 B: %v", err)
|
||||
}
|
||||
csRole, superRole := tenantChatRoles(t, db)
|
||||
adminA := createTenantAdmin(t, db, "cs-a", csRole.ID, tenantA.ID)
|
||||
adminB := createTenantAdmin(t, db, "cs-b", csRole.ID, tenantB.ID)
|
||||
superAdmin := createTenantAdmin(t, db, "platform", superRole.ID, 0)
|
||||
|
||||
convA := createSupportConversation(t, db, tenantA.ID, adminA.ID, "大锤咨询")
|
||||
createSupportConversation(t, db, tenantB.ID, adminB.ID, "解忧咨询")
|
||||
repo := NewRepository(db, nil, nil)
|
||||
|
||||
ctxA := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantA.ID})
|
||||
ctxB := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantB.ID})
|
||||
listA, err := repo.ListConversationsWithFilter(ctxA, Principal{Type: "admin", ID: adminA.ID}, 1, 20, adminChatFilterAll, adminChatStageAll, "")
|
||||
if err != nil {
|
||||
t.Fatalf("查询租户 A 会话: %v", err)
|
||||
}
|
||||
if listA.Total != 1 || listA.Items.([]ConversationDTO)[0].ID != convA.ID {
|
||||
t.Fatalf("租户 A 会话 = %+v, want only %d", listA.Items, convA.ID)
|
||||
}
|
||||
listB, err := repo.ListConversationsWithFilter(ctxB, Principal{Type: "admin", ID: adminB.ID}, 1, 20, adminChatFilterAll, adminChatStageAll, "")
|
||||
if err != nil {
|
||||
t.Fatalf("查询租户 B 会话: %v", err)
|
||||
}
|
||||
if listB.Total != 1 {
|
||||
t.Fatalf("租户 B 会话数 = %d, want 1", listB.Total)
|
||||
}
|
||||
listPlatform, err := repo.ListConversationsWithFilter(ctxA, Principal{Type: "admin", ID: superAdmin.ID}, 1, 20, adminChatFilterAll, adminChatStageAll, "")
|
||||
if err != nil {
|
||||
t.Fatalf("查询平台会话: %v", err)
|
||||
}
|
||||
if listPlatform.Total != 2 {
|
||||
t.Fatalf("平台会话数 = %d, want 2", listPlatform.Total)
|
||||
}
|
||||
|
||||
if _, err := repo.FindConversation(ctxB, Principal{Type: "admin", ID: adminB.ID}, convA.ID); err != ErrConversationNotFound {
|
||||
t.Fatalf("租户 B 读取租户 A 会话 error = %v, want not found", err)
|
||||
}
|
||||
if _, err := repo.FindConversation(ctxA, Principal{Type: "admin", ID: superAdmin.ID}, convA.ID); err != nil {
|
||||
t.Fatalf("平台超管读取会话: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossTenantOrderConversationIsVisibleToBothSides(t *testing.T) {
|
||||
db := setupTenantChatTestDB(t)
|
||||
buyerTenant := model.Tenant{Code: "tenant-buyer", Name: "买方", Status: "active"}
|
||||
sourceTenant := model.Tenant{Code: "tenant-source", Name: "货源方", Status: "active"}
|
||||
if err := db.Create(&buyerTenant).Error; err != nil {
|
||||
t.Fatalf("创建买方租户: %v", err)
|
||||
}
|
||||
if err := db.Create(&sourceTenant).Error; err != nil {
|
||||
t.Fatalf("创建货源租户: %v", err)
|
||||
}
|
||||
owner := model.User{TenantID: sourceTenant.ID, Phone: "13900000001", Nickname: "号主"}
|
||||
renter := model.User{TenantID: buyerTenant.ID, Phone: "13900000002", Nickname: "租客"}
|
||||
if err := db.Create(&owner).Error; err != nil {
|
||||
t.Fatalf("创建号主: %v", err)
|
||||
}
|
||||
if err := db.Create(&renter).Error; err != nil {
|
||||
t.Fatalf("创建租客: %v", err)
|
||||
}
|
||||
order := model.RentalOrder{
|
||||
OrderNo: "CROSS-TENANT-CHAT",
|
||||
ListingID: 88,
|
||||
AccountID: 88,
|
||||
OwnerID: owner.ID,
|
||||
RenterID: renter.ID,
|
||||
BuyerTenantID: buyerTenant.ID,
|
||||
SourceTenantID: sourceTenant.ID,
|
||||
Status: "renting",
|
||||
}
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
t.Fatalf("创建跨站订单: %v", err)
|
||||
}
|
||||
conversation := model.ChatConversation{
|
||||
TenantID: buyerTenant.ID,
|
||||
OrderID: &order.ID,
|
||||
Type: ConversationTypeOrderGroup,
|
||||
Title: "跨站订单群",
|
||||
Status: "active",
|
||||
}
|
||||
if err := db.Create(&conversation).Error; err != nil {
|
||||
t.Fatalf("创建跨站会话: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
if err := db.Create(&[]model.ChatParticipant{
|
||||
{ConversationID: conversation.ID, ParticipantType: "user", ParticipantID: renter.ID, Role: "renter", JoinedAt: now},
|
||||
{ConversationID: conversation.ID, ParticipantType: "user", ParticipantID: owner.ID, Role: "owner", JoinedAt: now},
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("创建跨站会话成员: %v", err)
|
||||
}
|
||||
repo := NewRepository(db, nil, nil)
|
||||
for name, tc := range map[string]struct {
|
||||
user uint64
|
||||
scope tenancy.Scope
|
||||
}{
|
||||
"buyer": {user: renter.ID, scope: tenancy.Scope{TenantID: buyerTenant.ID}},
|
||||
"source": {user: owner.ID, scope: tenancy.Scope{TenantID: sourceTenant.ID}},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := tenancy.WithScope(t.Context(), tc.scope)
|
||||
got, err := repo.FindOrderConversation(ctx, tc.user, order.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("读取跨站会话: %v", err)
|
||||
}
|
||||
if got.ID != conversation.ID {
|
||||
t.Fatalf("conversation = %d, want %d", got.ID, conversation.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func setupTenantChatTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.Tenant{},
|
||||
&model.User{},
|
||||
&model.Role{},
|
||||
&model.AdminUser{},
|
||||
&model.AdminUserRole{},
|
||||
&model.RentalListing{},
|
||||
&model.RentalOrder{},
|
||||
&model.ChatConversation{},
|
||||
&model.ChatParticipant{},
|
||||
&model.ChatAdminConversationState{},
|
||||
&model.ChatMessage{},
|
||||
); err != nil {
|
||||
t.Fatalf("迁移租户聊天测试库: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func tenantChatRoles(t *testing.T, db *gorm.DB) (model.Role, model.Role) {
|
||||
t.Helper()
|
||||
csRole := model.Role{Code: "cs", Name: "客服"}
|
||||
superRole := model.Role{Code: "super_admin", Name: "超级管理员"}
|
||||
if err := db.Create(&csRole).Error; err != nil {
|
||||
t.Fatalf("创建客服角色: %v", err)
|
||||
}
|
||||
if err := db.Create(&superRole).Error; err != nil {
|
||||
t.Fatalf("创建超管角色: %v", err)
|
||||
}
|
||||
return csRole, superRole
|
||||
}
|
||||
|
||||
func createTenantAdmin(t *testing.T, db *gorm.DB, username string, roleID, tenantID uint64) model.AdminUser {
|
||||
t.Helper()
|
||||
admin := model.AdminUser{Username: username, Status: "active"}
|
||||
if err := db.Create(&admin).Error; err != nil {
|
||||
t.Fatalf("创建管理员 %s: %v", username, err)
|
||||
}
|
||||
if err := db.Create(&model.AdminUserRole{AdminID: admin.ID, RoleID: roleID, TenantID: tenantID}).Error; err != nil {
|
||||
t.Fatalf("绑定管理员角色 %s: %v", username, err)
|
||||
}
|
||||
return admin
|
||||
}
|
||||
|
||||
func createSupportConversation(t *testing.T, db *gorm.DB, tenantID, adminID uint64, title string) model.ChatConversation {
|
||||
t.Helper()
|
||||
conversation := model.ChatConversation{TenantID: tenantID, Type: ConversationTypeGeneralSupport, Title: title, Status: "active"}
|
||||
if err := db.Create(&conversation).Error; err != nil {
|
||||
t.Fatalf("创建会话 %s: %v", title, err)
|
||||
}
|
||||
if err := db.Create(&model.ChatParticipant{
|
||||
ConversationID: conversation.ID,
|
||||
ParticipantType: "admin",
|
||||
ParticipantID: adminID,
|
||||
Role: "support",
|
||||
JoinedAt: time.Now(),
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("创建会话成员 %s: %v", title, err)
|
||||
}
|
||||
return conversation
|
||||
}
|
||||
Reference in New Issue
Block a user