fix(chat): 分销站点客服会话按归属租户可见
This commit is contained in:
@@ -43,6 +43,7 @@ func MigrateRentalTransactionTestSchema(db *gorm.DB) error {
|
||||
&model.ChatParticipant{},
|
||||
&model.ChatAdminConversationState{},
|
||||
&model.ChatMessage{},
|
||||
&model.ChatSiteTenantLink{},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,20 @@ func (ChatAdminConversationState) TableName() string {
|
||||
return "chat_admin_conversation_states"
|
||||
}
|
||||
|
||||
// ChatSiteTenantLink 将历史分销站点的平台客服会话归属到负责接待的经营租户。
|
||||
// 该表只服务聊天权限,不改变 distribution_sites 的原有分销语义。
|
||||
type ChatSiteTenantLink struct {
|
||||
SiteID uint64 `gorm:"primaryKey" json:"site_id"`
|
||||
TenantID uint64 `gorm:"not null;index:idx_chat_site_tenant_links_tenant" json:"tenant_id"`
|
||||
Enabled bool `gorm:"not null;default:true" json:"enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (ChatSiteTenantLink) TableName() string {
|
||||
return "chat_site_tenant_links"
|
||||
}
|
||||
|
||||
type ChatMessage struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
ConversationID uint64 `gorm:"not null;index" json:"conversation_id"`
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package chatext
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// DefaultSupportTenantCode 是历史分销站点默认归属的经营租户编码。
|
||||
// 当前业务口径:大锤商行下的分销网站由大锤客服接待。
|
||||
const DefaultSupportTenantCode = "dachui"
|
||||
|
||||
// EnsureSiteMappingForContext 为新创建的分销站点写入客服归属租户。
|
||||
// 优先使用当前经营站点上下文;平台后台或旧分销后台无租户上下文时回退大锤。
|
||||
func EnsureSiteMappingForContext(db *gorm.DB, siteID uint64, contextTenantID uint64) error {
|
||||
if contextTenantID > 0 {
|
||||
return EnsureSiteMapping(db, siteID, contextTenantID)
|
||||
}
|
||||
return EnsureDefaultSiteMapping(db, siteID)
|
||||
}
|
||||
|
||||
// EnsureDefaultSiteMapping 为新创建的分销站点补充默认客服租户映射。
|
||||
// 租户不存在时保持兼容:不阻断分销站点创建,由迁移或人工配置补齐。
|
||||
func EnsureDefaultSiteMapping(db *gorm.DB, siteID uint64) error {
|
||||
if db == nil || siteID == 0 {
|
||||
return nil
|
||||
}
|
||||
var tenant model.Tenant
|
||||
err := db.Select("id").
|
||||
Where("code = ? AND status = ?", DefaultSupportTenantCode, "active").
|
||||
First(&tenant).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return EnsureSiteMapping(db, siteID, tenant.ID)
|
||||
}
|
||||
|
||||
// EnsureSiteMapping 幂等写入站点与租户的客服归属关系,不覆盖已有配置。
|
||||
func EnsureSiteMapping(db *gorm.DB, siteID, tenantID uint64) error {
|
||||
if db == nil || siteID == 0 || tenantID == 0 {
|
||||
return nil
|
||||
}
|
||||
row := model.ChatSiteTenantLink{
|
||||
SiteID: siteID,
|
||||
TenantID: tenantID,
|
||||
Enabled: true,
|
||||
}
|
||||
return db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "site_id"}},
|
||||
DoNothing: true,
|
||||
}).Create(&row).Error
|
||||
}
|
||||
|
||||
// UpsertSiteMapping 显式覆盖站点与租户的客服归属关系。
|
||||
func UpsertSiteMapping(db *gorm.DB, siteID, tenantID uint64) error {
|
||||
if db == nil || siteID == 0 || tenantID == 0 {
|
||||
return nil
|
||||
}
|
||||
row := model.ChatSiteTenantLink{
|
||||
SiteID: siteID,
|
||||
TenantID: tenantID,
|
||||
Enabled: true,
|
||||
}
|
||||
return db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "site_id"}},
|
||||
DoUpdates: clause.Assignments(map[string]any{
|
||||
"tenant_id": tenantID,
|
||||
"enabled": true,
|
||||
"updated_at": time.Now(),
|
||||
}),
|
||||
}).Create(&row).Error
|
||||
}
|
||||
|
||||
// TenantIDForSite 返回启用中的分销站点客服归属租户;无映射时返回 0。
|
||||
func TenantIDForSite(db *gorm.DB, siteID uint64) (uint64, error) {
|
||||
if db == nil || siteID == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
var row struct {
|
||||
TenantID uint64 `gorm:"column:tenant_id"`
|
||||
}
|
||||
err := db.Table("chat_site_tenant_links AS st").
|
||||
Select("st.tenant_id").
|
||||
Joins("JOIN tenants AS t ON t.id = st.tenant_id AND t.status = ?", "active").
|
||||
Where("st.site_id = ? AND st.enabled = ?", siteID, true).
|
||||
Take(&row).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return row.TenantID, nil
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chatext"
|
||||
listingpkg "hfb_sys/backend/internal/modules/listing"
|
||||
"hfb_sys/backend/internal/modules/systemconfig"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
@@ -484,18 +485,23 @@ func (r *Repository) CreateSite(ctx context.Context, req CreateSiteRequest) (*Si
|
||||
// 模型上带 default 标签的布尔/整型字段(display_account_enabled、tax_enabled、
|
||||
// settlement_hold_days)在零值(false/0)时会被 GORM 忽略并回落数据库默认值,
|
||||
// 因此显式传 false/0 的配置必须在插入后补写,否则会被静默改掉。
|
||||
if err := r.db.WithContext(ctx).Create(&row).Error; err != nil {
|
||||
if err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&row).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if explicitZeros := explicitZeroSiteColumns(req); len(explicitZeros) > 0 {
|
||||
if err := tx.Model(&model.DistributionSite{}).Where("id = ?", row.ID).
|
||||
Updates(explicitZeros).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.First(&row, row.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return chatext.EnsureSiteMappingForContext(tx, row.ID, tenancy.IDFromContext(ctx))
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if explicitZeros := explicitZeroSiteColumns(req); len(explicitZeros) > 0 {
|
||||
if err := r.db.WithContext(ctx).Model(&model.DistributionSite{}).Where("id = ?", row.ID).
|
||||
Updates(explicitZeros).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.WithContext(ctx).First(&row, row.ID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := wallet.EnsureAccountTx(r.db.WithContext(ctx), 0, row.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2454,6 +2460,9 @@ func (r *Repository) OnboardSite(ctx context.Context, req OnboardSiteRequest) (*
|
||||
if err := tx.Create(&site).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := chatext.EnsureSiteMappingForContext(tx, site.ID, tenancy.IDFromContext(ctx)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nickname := req.AdminNickname
|
||||
if nickname == "" {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
@@ -18,7 +19,8 @@ func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.AdminUser{}, &model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
||||
&model.ChatConversation{}, &model.RentalOrder{},
|
||||
&model.ChatConversation{},
|
||||
&model.ChatSiteTenantLink{}, &model.Tenant{}, &model.RentalOrder{},
|
||||
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
||||
&model.DistributionSiteMember{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{},
|
||||
&model.DistributionOrderParty{}, &model.DistributionSiteAccount{}, &model.DistributionSitePaymentChannel{},
|
||||
@@ -1884,3 +1886,75 @@ func TestListOrdersPerformanceAndScoping(t *testing.T) {
|
||||
t.Fatalf("expected 1 receive order for site2, got %d", recvPage.Total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSiteAddsDefaultSupportTenantMapping(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("创建大锤租户: %v", err)
|
||||
}
|
||||
site, err := NewRepository(db).CreateSite(t.Context(), CreateSiteRequest{
|
||||
SiteCode: "auto_map_site",
|
||||
SiteName: "自动映射站点",
|
||||
Domain: "auto-map.example.com",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("创建分销站点: %v", err)
|
||||
}
|
||||
var link model.ChatSiteTenantLink
|
||||
if err := db.Where("site_id = ?", site.ID).First(&link).Error; err != nil {
|
||||
t.Fatalf("查询客服租户映射: %v", err)
|
||||
}
|
||||
if link.TenantID != tenant.ID || !link.Enabled {
|
||||
t.Fatalf("映射 = %+v, want tenant=%d enabled=true", link, tenant.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnboardSiteAddsDefaultSupportTenantMapping(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("创建大锤租户: %v", err)
|
||||
}
|
||||
resp, err := NewRepository(db).OnboardSite(t.Context(), OnboardSiteRequest{
|
||||
SiteCode: "onboard_map_site",
|
||||
SiteName: "开通映射站点",
|
||||
Domain: "onboard-map.example.com",
|
||||
AdminUsername: "onboard_map_admin",
|
||||
AdminPassword: "password123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("开通分销站点: %v", err)
|
||||
}
|
||||
var link model.ChatSiteTenantLink
|
||||
if err := db.Where("site_id = ?", resp.Site.ID).First(&link).Error; err != nil {
|
||||
t.Fatalf("查询客服租户映射: %v", err)
|
||||
}
|
||||
if link.TenantID != tenant.ID || !link.Enabled {
|
||||
t.Fatalf("映射 = %+v, want tenant=%d enabled=true", link, tenant.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSiteUsesCurrentTenantForSupportMapping(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
tenant := model.Tenant{Code: "jieyou", Name: "解忧商行", Status: "active"}
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatalf("创建解忧租户: %v", err)
|
||||
}
|
||||
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenant.ID})
|
||||
site, err := NewRepository(db).CreateSite(ctx, CreateSiteRequest{
|
||||
SiteCode: "jieyou_map_site",
|
||||
SiteName: "解忧映射站点",
|
||||
Domain: "jieyou-map.example.com",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("创建分销站点: %v", err)
|
||||
}
|
||||
var link model.ChatSiteTenantLink
|
||||
if err := db.Where("site_id = ?", site.ID).First(&link).Error; err != nil {
|
||||
t.Fatalf("查询客服租户映射: %v", err)
|
||||
}
|
||||
if link.TenantID != tenant.ID {
|
||||
t.Fatalf("映射 tenant_id = %d, want %d", link.TenantID, tenant.ID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
-- +goose Up
|
||||
|
||||
-- 历史分销站点的平台客服会话统一由大锤商行客服接待。
|
||||
-- 该映射仅用于聊天租户归属,不改变 distribution_sites 的分销业务语义。
|
||||
CREATE TABLE chat_site_tenant_links (
|
||||
site_id BIGINT UNSIGNED NOT NULL,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (site_id),
|
||||
KEY idx_chat_site_tenant_links_tenant (tenant_id, enabled),
|
||||
CONSTRAINT fk_chat_site_tenant_links_site FOREIGN KEY (site_id) REFERENCES distribution_sites (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_chat_site_tenant_links_tenant FOREIGN KEY (tenant_id) REFERENCES tenants (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='分销站点平台客服归属经营租户';
|
||||
|
||||
-- 现有分销站点全部归入大锤商行客服;后续新建站点由应用层自动补映射。
|
||||
INSERT INTO chat_site_tenant_links (site_id, tenant_id, enabled, created_at, updated_at)
|
||||
SELECT ds.id, t.id, 1, NOW(), NOW()
|
||||
FROM distribution_sites AS ds
|
||||
JOIN tenants AS t ON t.code = 'dachui' AND t.status = 'active'
|
||||
ON DUPLICATE KEY UPDATE
|
||||
enabled = 1,
|
||||
updated_at = NOW();
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS chat_site_tenant_links;
|
||||
Reference in New Issue
Block a user