fix(chat): 分销站点客服会话按归属租户可见
This commit is contained in:
@@ -28,7 +28,7 @@ type adminChatCountsSnapshot struct {
|
||||
|
||||
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:v4:%s:%d:%s:%s:%s:%s", principal.Type, principal.ID, tenancy.ScopeKey(ctx), filter, stage, hex.EncodeToString(sum[:8]))
|
||||
return fmt.Sprintf("admin-chat:counts:v5:%s:%d:%s:%s:%s:%s", principal.Type, principal.ID, tenancy.ScopeKey(ctx), filter, stage, hex.EncodeToString(sum[:8]))
|
||||
}
|
||||
|
||||
func adminChatCountsGenerationKey(scope string) string {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -49,8 +50,9 @@ func TestAdminConversationCountsUsesFreshSnapshot(t *testing.T) {
|
||||
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: 1})
|
||||
principal := Principal{Type: "admin", ID: admin.ID}
|
||||
cacheKey := repo.adminChatCountsCacheKey(ctx, principal, adminChatFilterMine, adminChatStageAll, "")
|
||||
_ = client.Del(context.Background(), cacheKey).Err()
|
||||
t.Cleanup(func() {
|
||||
_ = client.Del(t.Context(), cacheKey).Err()
|
||||
_ = client.Del(context.Background(), cacheKey).Err()
|
||||
})
|
||||
|
||||
first, err := repo.AdminConversationCounts(ctx, principal, adminChatFilterMine, adminChatStageAll, "")
|
||||
|
||||
@@ -22,6 +22,7 @@ func setupAdminListTestDB(t *testing.T) *gorm.DB {
|
||||
&model.ChatParticipant{},
|
||||
&model.ChatAdminConversationState{},
|
||||
&model.ChatMessage{},
|
||||
&model.ChatSiteTenantLink{},
|
||||
); err != nil {
|
||||
t.Fatalf("迁移测试数据库失败: %v", err)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chatext"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -257,6 +258,15 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
return nil, err
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if site != nil {
|
||||
mappedTenantID, mapErr := chatext.TenantIDForSite(r.db.WithContext(ctx), site.ID)
|
||||
if mapErr != nil {
|
||||
return nil, mapErr
|
||||
}
|
||||
if mappedTenantID > 0 {
|
||||
tenantID = mappedTenantID
|
||||
}
|
||||
}
|
||||
|
||||
scene, title, groupCode, welcome := resolveSupportScene(scene)
|
||||
if tenantID > 0 && site == nil {
|
||||
@@ -288,7 +298,12 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
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)
|
||||
if site != nil {
|
||||
// 历史分销客服会话可能仍为 tenant_id=0,按站点映射兼容并逐步归正。
|
||||
existingQuery = existingQuery.Where("(c.tenant_id = ? OR c.tenant_id = 0)", tenantID)
|
||||
} else {
|
||||
existingQuery = existingQuery.Where("c.tenant_id = ?", tenantID)
|
||||
}
|
||||
}
|
||||
|
||||
err := existingQuery.Order("c.id ASC").Limit(1).Find(&existing).Error
|
||||
@@ -338,6 +353,11 @@ func (r *Repository) EnsureSupportConversation(ctx context.Context, userID uint6
|
||||
}
|
||||
}
|
||||
if existing.ID > 0 {
|
||||
if tenantID > 0 && existing.TenantID == 0 {
|
||||
if err := tx.Model(&existing).Update("tenant_id", tenantID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
conversationID = existing.ID
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ func setupConversationTestDB(t *testing.T) *gorm.DB {
|
||||
&model.ChatParticipant{},
|
||||
&model.ChatAdminConversationState{},
|
||||
&model.ChatMessage{},
|
||||
&model.ChatSiteTenantLink{},
|
||||
&model.DistributionSite{},
|
||||
); err != nil {
|
||||
t.Fatalf("数据库迁移失败: %v", err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chatext"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
@@ -32,8 +33,19 @@ func conversationTenantAccessCondition(alias string) (string, []any) {
|
||||
WHERE rlo.listing_id = ` + alias + `.listing_id
|
||||
AND rlo.buyer_tenant_id = ?
|
||||
)
|
||||
OR (
|
||||
` + alias + `.distribution_site_id IS NOT NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_site_tenant_links st
|
||||
JOIN tenants t ON t.id = st.tenant_id AND t.status = 'active'
|
||||
WHERE st.site_id = ` + alias + `.distribution_site_id
|
||||
AND st.enabled = 1
|
||||
AND st.tenant_id = ?
|
||||
)
|
||||
)
|
||||
)`
|
||||
return condition, []any{0, 0, 0, 0, 0}
|
||||
return condition, []any{0, 0, 0, 0, 0, 0}
|
||||
}
|
||||
|
||||
func tenantConversationScope(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
@@ -89,10 +101,15 @@ func ensureAdminConversationAccess(ctx context.Context, tx *gorm.DB, adminID, co
|
||||
|
||||
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 {
|
||||
if err := tx.Select("id", "tenant_id", "order_id", "listing_id", "type", "distribution_site_id").First(&conversation, conversationID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := []uint64{conversation.TenantID}
|
||||
if conversation.DistributionSiteID != nil {
|
||||
if tenantID, err := chatext.TenantIDForSite(tx, *conversation.DistributionSiteID); err == nil {
|
||||
ids = append(ids, 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 {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chathub"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -146,6 +147,8 @@ func setupTenantChatTestDB(t *testing.T) *gorm.DB {
|
||||
&model.ChatParticipant{},
|
||||
&model.ChatAdminConversationState{},
|
||||
&model.ChatMessage{},
|
||||
&model.ChatSiteTenantLink{},
|
||||
&model.DistributionSite{},
|
||||
); err != nil {
|
||||
t.Fatalf("迁移租户聊天测试库: %v", err)
|
||||
}
|
||||
@@ -194,3 +197,142 @@ func createSupportConversation(t *testing.T, db *gorm.DB, tenantID, adminID uint
|
||||
}
|
||||
return conversation
|
||||
}
|
||||
|
||||
func TestLegacyDistributionSupportConversationVisibleToMappedTenant(t *testing.T) {
|
||||
db := setupTenantChatTestDB(t)
|
||||
tenantA := model.Tenant{Code: "tenant-dachui-map", Name: "大锤映射", Status: "active"}
|
||||
tenantB := model.Tenant{Code: "tenant-jieyou-map", 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, _ := tenantChatRoles(t, db)
|
||||
adminA := createTenantAdmin(t, db, "cs-map-a", csRole.ID, tenantA.ID)
|
||||
adminB := createTenantAdmin(t, db, "cs-map-b", csRole.ID, tenantB.ID)
|
||||
site := model.DistributionSite{SiteCode: "map_site", SiteName: "映射分销", Domain: "map.example.com", Status: "active"}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatalf("创建分销站点: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ChatSiteTenantLink{SiteID: site.ID, TenantID: tenantA.ID, Enabled: true}).Error; err != nil {
|
||||
t.Fatalf("创建站点租户映射: %v", err)
|
||||
}
|
||||
conversation := createSupportConversation(t, db, 0, adminA.ID, "【映射分销】平台客服")
|
||||
if err := db.Model(&conversation).Updates(map[string]any{
|
||||
"distribution_site_id": site.ID,
|
||||
"type": ConversationTypeGeneralSupport,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("补充会话站点: %v", err)
|
||||
}
|
||||
listingConversation := createSupportConversation(t, db, 0, adminA.ID, "映射分销账号群")
|
||||
if err := db.Model(&listingConversation).Updates(map[string]any{
|
||||
"distribution_site_id": site.ID,
|
||||
"type": ConversationTypeListingGroup,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("补充账号群站点: %v", err)
|
||||
}
|
||||
siteB := model.DistributionSite{SiteCode: "map_site_b", SiteName: "解忧映射分销", Domain: "map-b.example.com", Status: "active"}
|
||||
if err := db.Create(&siteB).Error; err != nil {
|
||||
t.Fatalf("创建解忧分销站点: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ChatSiteTenantLink{SiteID: siteB.ID, TenantID: tenantB.ID, Enabled: true}).Error; err != nil {
|
||||
t.Fatalf("创建解忧站点映射: %v", err)
|
||||
}
|
||||
conversationB := createSupportConversation(t, db, 0, adminB.ID, "【解忧映射分销】平台客服")
|
||||
if err := db.Model(&conversationB).Updates(map[string]any{
|
||||
"distribution_site_id": siteB.ID,
|
||||
"type": ConversationTypeGeneralSupport,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("补充解忧会话站点: %v", err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db, nil, nil)
|
||||
ctxA := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantA.ID})
|
||||
listA, err := repo.ListConversationsWithFilter(ctxA, Principal{Type: "admin", ID: adminA.ID}, 1, 20, adminChatFilterMine, adminChatStageAll, "")
|
||||
if err != nil {
|
||||
t.Fatalf("查询映射租户客服会话: %v", err)
|
||||
}
|
||||
if listA.Total != 2 {
|
||||
t.Fatalf("映射租户 mine 会话数 = %d, want 2", listA.Total)
|
||||
}
|
||||
seen := map[uint64]bool{}
|
||||
for _, item := range listA.Items.([]ConversationDTO) {
|
||||
seen[item.ID] = true
|
||||
}
|
||||
if !seen[conversation.ID] || !seen[listingConversation.ID] {
|
||||
t.Fatalf("映射租户 mine 会话 = %+v, want 包含 %d 和 %d", listA.Items, conversation.ID, listingConversation.ID)
|
||||
}
|
||||
if _, err := repo.FindConversation(ctxA, Principal{Type: "admin", ID: adminA.ID}, conversation.ID); err != nil {
|
||||
t.Fatalf("映射租户读取会话详情: %v", err)
|
||||
}
|
||||
|
||||
ctxB := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantB.ID})
|
||||
listB, err := repo.ListConversationsWithFilter(ctxB, Principal{Type: "admin", ID: adminB.ID}, 1, 20, adminChatFilterAll, adminChatStageAll, "")
|
||||
if err != nil {
|
||||
t.Fatalf("查询其他租户会话: %v", err)
|
||||
}
|
||||
if listB.Total != 1 || listB.Items.([]ConversationDTO)[0].ID != conversationB.ID {
|
||||
t.Fatalf("解忧映射租户会话 = %+v, want only %d", listB.Items, conversationB.ID)
|
||||
}
|
||||
if _, err := repo.FindConversation(ctxA, Principal{Type: "admin", ID: adminA.ID}, conversationB.ID); err != ErrConversationNotFound {
|
||||
t.Fatalf("大锤客服读取解忧映射会话 error = %v, want not found", err)
|
||||
}
|
||||
|
||||
event := tenantScopedEvent(db, &chathub.ChatEvent{Type: "conversation_updated", ConversationID: conversation.ID})
|
||||
if !containsTenantID(event.TenantIDs, tenantA.ID) {
|
||||
t.Fatalf("事件租户 = %v, want 包含 %d", event.TenantIDs, tenantA.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureSupportConversationUsesMappedTenant(t *testing.T) {
|
||||
db := setupTenantChatTestDB(t)
|
||||
tenant := model.Tenant{Code: "tenant-support-map", Name: "大锤客服", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("创建租户: %v", err)
|
||||
}
|
||||
csRole, _ := tenantChatRoles(t, db)
|
||||
support := createTenantAdmin(t, db, "cs-mapped-support", csRole.ID, tenant.ID)
|
||||
site := model.DistributionSite{SiteCode: "mapped_site", SiteName: "映射站点", Domain: "mapped.example.com", Status: "active"}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatalf("创建分销站点: %v", err)
|
||||
}
|
||||
if err := db.Create(&model.ChatSiteTenantLink{SiteID: site.ID, TenantID: tenant.ID, Enabled: true}).Error; err != nil {
|
||||
t.Fatalf("创建映射: %v", err)
|
||||
}
|
||||
user := model.User{TenantID: 0, DistributionSiteID: site.ID, Phone: "13900009999", Nickname: "分销咨询用户", Status: "active"}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatalf("创建用户: %v", err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db, nil, nil)
|
||||
item, err := repo.EnsureSupportConversation(t.Context(), user.ID, "general", site.SiteCode)
|
||||
if err != nil {
|
||||
t.Fatalf("创建映射客服会话: %v", err)
|
||||
}
|
||||
var conversation model.ChatConversation
|
||||
if err := db.First(&conversation, item.ID).Error; err != nil {
|
||||
t.Fatalf("读取会话: %v", err)
|
||||
}
|
||||
if conversation.TenantID != tenant.ID {
|
||||
t.Fatalf("会话 tenant_id = %d, want %d", conversation.TenantID, tenant.ID)
|
||||
}
|
||||
var supportCount int64
|
||||
if err := db.Model(&model.ChatParticipant{}).
|
||||
Where("conversation_id = ? AND participant_type = ? AND role = ? AND participant_id = ?", conversation.ID, "admin", "support", support.ID).
|
||||
Count(&supportCount).Error; err != nil {
|
||||
t.Fatalf("查询客服参与者: %v", err)
|
||||
}
|
||||
if supportCount != 1 {
|
||||
t.Fatalf("映射租户客服参与者数量 = %d, want 1", supportCount)
|
||||
}
|
||||
}
|
||||
|
||||
func containsTenantID(ids []uint64, target uint64) bool {
|
||||
for _, id := range ids {
|
||||
if id == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user