feat(tenant): 隔离客服通知文件与后台任务

This commit is contained in:
yml
2026-11-15 16:23:28 +08:00
parent c7dacfa025
commit e994fd9166
52 changed files with 1670 additions and 254 deletions
+41 -7
View File
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/sms"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -77,13 +78,32 @@ func (j *Job) run(ctx context.Context) {
}
defer release()
enqueued, err := j.RunOnce(ctx)
tenantIDs, err := j.activeTenantIDs(ctx)
if err != nil {
j.logger.Warn("上架未成交降价提醒扫描失败", zap.Error(err))
j.logger.Warn("读取经营租户失败", zap.Error(err))
return
}
if enqueued > 0 {
j.logger.Info("上架未成交降价提醒已入队", zap.Int("count", enqueued))
total := 0
if len(tenantIDs) == 0 {
tenantIDs = []uint64{0}
}
for _, tenantID := range tenantIDs {
tenantCtx := ctx
if tenantID > 0 {
tenantCtx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: tenantID})
}
enqueued, err := j.RunOnce(tenantCtx)
if err != nil {
j.logger.Warn("上架未成交降价提醒扫描失败",
zap.Uint64("tenant_id", tenantID),
zap.Error(err),
)
continue
}
total += enqueued
}
if total > 0 {
j.logger.Info("上架未成交降价提醒已入队", zap.Int("count", total))
}
}
@@ -106,14 +126,18 @@ func (j *Job) RunOnce(ctx context.Context) (int, error) {
// NOT EXISTS 排除已提醒过的账号,否则已入队的记录会一直占满 LIMIT 名额:
// 候选窗口有 24 小时,任务每小时跑一次,若窗口内候选超过 batchSize,
// 每次都会查回同一批「已提醒」的账号,排在后面的账号会在窗口结束后被永久漏发。
err = j.db.WithContext(ctx).
Select("id", "owner_id", "distribution_site_id", "published_at").
query := j.db.WithContext(ctx).
Select("id", "owner_id", "source_tenant_id", "distribution_site_id", "published_at").
Where("status = ? AND in_transaction = ?", "published", false).
Where("published_at IS NOT NULL AND published_at <= ? AND published_at > ?", threshold, windowStart).
Where(`NOT EXISTS (
SELECT 1 FROM sms_messages sm
WHERE sm.node = ? AND sm.biz_type = ? AND sm.biz_id = rental_listings.id
)`, sms.NodeListingStalePriceSuggestion, "listing").
)`, sms.NodeListingStalePriceSuggestion, "listing")
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("source_tenant_id = ?", tenantID)
}
err = query.
Order("id ASC").
Limit(j.batchSize).
Find(&rows).Error
@@ -130,6 +154,7 @@ func (j *Job) RunOnce(ctx context.Context) (int, error) {
continue
}
inserted, err := sms.Enqueue(j.db.WithContext(ctx), sms.Entry{
TenantID: row.SourceTenantID,
UserID: row.OwnerID,
Node: sms.NodeListingStalePriceSuggestion,
BizType: "listing",
@@ -150,6 +175,15 @@ func (j *Job) RunOnce(ctx context.Context) (int, error) {
return enqueued, nil
}
func (j *Job) activeTenantIDs(ctx context.Context) ([]uint64, error) {
var ids []uint64
err := j.db.WithContext(ctx).Table("tenants").
Where("status = ?", "active").
Order("id ASC").
Pluck("id", &ids).Error
return ids, err
}
func (j *Job) acquireLock(ctx context.Context) (func(), bool) {
if j.redis == nil {
return func() {}, true
+88 -36
View File
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/modules/adminnotification"
"hfb_sys/backend/internal/modules/chat"
"hfb_sys/backend/internal/modules/notification"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -124,6 +125,22 @@ func newInstanceID() string {
return hex.EncodeToString(b)
}
func (j *Job) activeTenantIDs(ctx context.Context) ([]uint64, error) {
var ids []uint64
err := j.db.WithContext(ctx).Table("tenants").
Where("status = ?", "active").
Order("id ASC").
Pluck("id", &ids).Error
return ids, err
}
func applyOrderTenantScope(ctx context.Context, db *gorm.DB, column string) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where(column+" = ?", tenantID)
}
return db
}
func (j *Job) Start(ctx context.Context) {
if j == nil || j.db == nil {
return
@@ -153,28 +170,52 @@ func (j *Job) run(ctx context.Context) {
}
defer release()
cfg, err := j.loadThresholds(ctx)
now := time.Now()
handlers := []struct {
name string
run func(context.Context, time.Time, thresholds) (int, error)
}{
{name: "pending_payment", run: j.handlePendingPaymentTimeout},
{name: "owner_submit", run: j.handleOwnerSubmitTimeout},
{name: "renter_confirm", run: j.handleRenterConfirmTimeout},
{name: "return_overdue", run: j.handleReturnOverdue},
{name: "owner_return_confirm", run: j.handleOwnerReturnConfirmTimeout},
{name: "renter_retention", run: j.handleEndedOrderRenterRetention},
}
tenantIDs, err := j.activeTenantIDs(ctx)
if err != nil {
j.logger.Warn("订单超时任务加载配置失败", zap.Error(err))
j.logger.Warn("订单超时任务读取经营租户失败", zap.Error(err))
return
}
now := time.Now()
handlers := []func(context.Context, time.Time, thresholds) (int, error){
j.handlePendingPaymentTimeout,
j.handleOwnerSubmitTimeout,
j.handleRenterConfirmTimeout,
j.handleReturnOverdue,
j.handleOwnerReturnConfirmTimeout,
j.handleEndedOrderRenterRetention,
if len(tenantIDs) == 0 {
tenantIDs = []uint64{0}
}
total := 0
for _, handler := range handlers {
count, err := handler(ctx, now, cfg)
if err != nil {
j.logger.Warn("订单超时处理失败", zap.Error(err))
continue
for _, tenantID := range tenantIDs {
tenantCtx := ctx
if tenantID > 0 {
tenantCtx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: tenantID})
}
cfg, err := j.loadThresholds(tenantCtx)
if err != nil {
j.logger.Warn("订单超时任务加载租户配置失败",
zap.Uint64("tenant_id", tenantID),
zap.Error(err),
)
continue
}
count, err := handler.run(tenantCtx, now, cfg)
if err != nil {
j.logger.Warn("订单超时处理失败",
zap.String("handler", handler.name),
zap.Uint64("tenant_id", tenantID),
zap.Error(err),
)
continue
}
total += count
}
total += count
}
if total > 0 {
j.logger.Info("订单超时处理完成", zap.Int("count", total))
@@ -191,7 +232,7 @@ func (j *Job) loadThresholds(ctx context.Context) (thresholds, error) {
RenterRetentionDaysAfterOrderEnd: defaultRenterRetentionDaysAfterOrderEnd,
}
var rows []model.SystemConfig
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where("`key` IN ?", []string{
"handoff.owner_submit_timeout_minutes",
"handoff.renter_confirm_timeout_minutes",
@@ -199,8 +240,11 @@ func (j *Job) loadThresholds(ctx context.Context) (thresholds, error) {
"order.return_overdue_grace_minutes",
"handoff.owner_return_confirm_timeout_minutes",
"chat.renter_retention_days_after_order_end",
}).
Find(&rows).Error
})
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
err := query.Find(&rows).Error
if err != nil {
return cfg, err
}
@@ -255,11 +299,12 @@ func (j *Job) handlePendingPaymentTimeout(ctx context.Context, now time.Time, cf
return 0, nil
}
var rows []model.RentalOrder
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where("status = ? AND created_at <= ?", "pending_payment", now.Add(-time.Duration(cfg.PendingPaymentTimeoutMinutes)*time.Minute)).
Order("id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
query = applyOrderTenantScope(ctx, query, "buyer_tenant_id")
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
@@ -372,11 +417,12 @@ func (j *Job) handleOwnerSubmitTimeout(ctx context.Context, now time.Time, cfg t
return 0, nil
}
var rows []model.RentalOrder
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status = ? AND COALESCE(handoff_started_at, created_at) <= ?", "pending_handoff", "pending_owner", now.Add(-time.Duration(cfg.OwnerSubmitTimeoutMinutes)*time.Minute)).
Order("id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
query = applyOrderTenantScope(ctx, query, "source_tenant_id")
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
@@ -441,11 +487,12 @@ func (j *Job) handleRenterConfirmTimeout(ctx context.Context, now time.Time, cfg
deadline := now.Add(-time.Duration(cfg.RenterConfirmTimeoutMinutes) * time.Minute)
var rows []model.RentalOrder
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status = ?", "pending_handoff", "pending_renter_confirm").
Order("id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
query = applyOrderTenantScope(ctx, query, "buyer_tenant_id")
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
@@ -527,11 +574,12 @@ func (j *Job) handleRenterConfirmTimeout(ctx context.Context, now time.Time, cfg
func (j *Job) handleReturnOverdue(ctx context.Context, now time.Time, cfg thresholds) (int, error) {
var rows []model.RentalOrder
overdueBefore := now.Add(-time.Duration(cfg.ReturnOverdueGraceMinutes) * time.Minute)
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where(`status = ? AND rented_at IS NOT NULL AND TIMESTAMPADD(HOUR, COALESCE(NULLIF(estimated_duration_hours, 0), 24), rented_at) <= ?`, "renting", overdueBefore).
Order("id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
query = applyOrderTenantScope(ctx, query, "buyer_tenant_id")
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
@@ -579,11 +627,12 @@ func (j *Job) handleOwnerReturnConfirmTimeout(ctx context.Context, now time.Time
return 0, nil
}
var rows []model.RentalOrder
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Where("status = ? AND handoff_status = ? AND COALESCE(handoff_started_at, updated_at) <= ?", "pending_checkout_confirm", "pending_owner_checkout", now.Add(-time.Duration(cfg.OwnerReturnConfirmTimeoutMinutes)*time.Minute)).
Order("id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
query = applyOrderTenantScope(ctx, query, "source_tenant_id")
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
@@ -646,7 +695,7 @@ func (j *Job) handleEndedOrderRenterRetention(ctx context.Context, now time.Time
retentionDays := clampRenterRetentionDays(cfg.RenterRetentionDaysAfterOrderEnd)
deadline := now.AddDate(0, 0, -retentionDays)
var rows []model.RentalOrder
err := j.db.WithContext(ctx).
query := j.db.WithContext(ctx).
Table("rental_orders AS o").
Select("o.*").
Joins("JOIN chat_conversations AS c ON c.listing_id = o.listing_id AND c.type = ?", chat.ConversationTypeListingGroup).
@@ -654,8 +703,11 @@ func (j *Job) handleEndedOrderRenterRetention(ctx context.Context, now time.Time
Where("o.status IN ?", []string{"completed", "cancelled", "closed"}).
Where("o.settled_at IS NOT NULL AND o.settled_at <= ?", deadline).
Order("o.id ASC").
Limit(100).
Find(&rows).Error
Limit(100)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("c.tenant_id = ?", tenantID)
}
err := query.Find(&rows).Error
if err != nil {
return 0, err
}
+8 -3
View File
@@ -9,6 +9,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/payment"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -145,8 +146,12 @@ func (j *Job) syncRefundPayments(ctx context.Context, now time.Time) (int, error
}
processed := 0
for _, row := range rows {
if _, err := j.payments.SyncRefundStatusByPaymentID(ctx, row.ID); err != nil {
if markErr := j.markRetryFailed(ctx, row, now); markErr != nil {
rowCtx := ctx
if row.TenantID > 0 {
rowCtx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: row.TenantID})
}
if _, err := j.payments.SyncRefundStatusByPaymentID(rowCtx, row.ID); err != nil {
if markErr := j.markRetryFailed(rowCtx, row, now); markErr != nil {
j.logger.Warn("退款重试失败状态保存失败",
zap.Uint64("payment_id", row.ID),
zap.Uint64("order_id", row.OrderID),
@@ -163,7 +168,7 @@ func (j *Job) syncRefundPayments(ctx context.Context, now time.Time) (int, error
)
continue
}
if err := j.resetRetry(ctx, row.ID); err != nil {
if err := j.resetRetry(rowCtx, row.ID); err != nil {
j.logger.Warn("退款重试计数重置失败",
zap.Uint64("payment_id", row.ID),
zap.Uint64("order_id", row.OrderID),
+15 -6
View File
@@ -17,6 +17,7 @@ import (
smsprovider "hfb_sys/backend/internal/integrations/sms"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/sms"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -112,11 +113,6 @@ func (j *Job) run(ctx context.Context) {
}
func (j *Job) dispatch(ctx context.Context) (int, error) {
cfg, err := sms.LoadConfig(ctx, j.configs)
if err != nil {
return 0, err
}
rows, err := j.repo.ListPending(ctx, j.batchSize, time.Now().Add(-j.retryDelay))
if err != nil {
return 0, err
@@ -127,7 +123,20 @@ func (j *Job) dispatch(ctx context.Context) (int, error) {
if err := ctx.Err(); err != nil {
return handled, err
}
if err := j.sendOne(ctx, cfg, row); err != nil {
rowCtx := ctx
if row.TenantID > 0 {
rowCtx = tenancy.WithScope(ctx, tenancy.Scope{TenantID: row.TenantID})
}
cfg, err := sms.LoadConfig(rowCtx, j.configs)
if err != nil {
j.logger.Warn("节点短信读取租户配置失败",
zap.Uint64("sms_message_id", row.ID),
zap.Uint64("tenant_id", row.TenantID),
zap.Error(err),
)
continue
}
if err := j.sendOne(rowCtx, cfg, row); err != nil {
j.logger.Warn("节点短信处理失败",
zap.Uint64("sms_message_id", row.ID),
zap.String("node", row.Node),
+2
View File
@@ -12,6 +12,8 @@ const (
type Announcement struct {
ID uint64 `gorm:"primaryKey" json:"id"`
// TenantID 经营租户归属;旧分销站点公告仍保存在同一记录中。
TenantID uint64 `gorm:"not null;default:0;index:idx_announcements_tenant_site" json:"tenant_id"`
// DistributionSiteID 公告归属站点:0=主站,>0=对应分站(分站公告中心按站点隔离)。
DistributionSiteID uint64 `gorm:"not null;default:0;index" json:"distribution_site_id"`
Title string `gorm:"size:255;not null" json:"title"`
+5 -1
View File
@@ -9,6 +9,7 @@ import (
type ChatConversation struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_chat_conversations_tenant_created" json:"tenant_id"`
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
ListingID *uint64 `gorm:"index" json:"listing_id"`
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id,omitempty"`
@@ -108,6 +109,7 @@ func (m *ChatMessage) AfterCreate(tx *gorm.DB) error {
type ChatQrCode struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_chat_qrcode_pool_tenant_site_status" json:"tenant_id"`
ImageURL string `gorm:"size:512;not null" json:"image_url"`
GroupName string `gorm:"size:128;not null;default:''" json:"group_name"`
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id,omitempty"`
@@ -128,6 +130,7 @@ func (ChatQrCode) TableName() string {
type ChatQrCodeDeliveryTask struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_chat_qrcode_delivery_tenant_status" json:"tenant_id"`
ConversationID uint64 `gorm:"column:conversation_id;not null;uniqueIndex" json:"conversation_id"`
Status string `gorm:"size:16;not null;default:'pending';index" json:"status"`
QrCodeID *uint64 `gorm:"column:qrcode_id;index" json:"qrcode_id"`
@@ -143,7 +146,8 @@ func (ChatQrCodeDeliveryTask) TableName() string {
type ChatSupportGroup struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Code string `gorm:"size:64;not null;uniqueIndex" json:"code"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_chat_support_groups_tenant_code;index:idx_chat_support_groups_tenant_status" json:"tenant_id"`
Code string `gorm:"size:64;not null;uniqueIndex:uk_chat_support_groups_tenant_code" json:"code"`
Name string `gorm:"size:64;not null" json:"name"`
Description string `gorm:"size:255;not null;default:''" json:"description"`
Status string `gorm:"size:16;not null;default:'active';index" json:"status"`
@@ -4,6 +4,7 @@ import "time"
type ChatQuickReply struct {
ID uint64 `gorm:"primaryKey;autoIncrement" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_chat_quick_replies_tenant_admin_sort" json:"tenant_id"`
AdminUserID uint64 `gorm:"not null;default:0;index" json:"admin_user_id"` // 0=全局, >0=个人
Title string `gorm:"size:64;not null" json:"title"`
Content string `gorm:"type:text;not null" json:"content"`
+1
View File
@@ -5,6 +5,7 @@ import "time"
// FileUploadOwner 记录用户上传的私有文件归属,用于业务关联创建前的临时访问授权。
type FileUploadOwner struct {
ID uint64 `gorm:"primaryKey"`
TenantID uint64 `gorm:"not null;default:0;index:idx_file_upload_owners_tenant_user"`
UserID uint64 `gorm:"not null;index"`
ObjectKey string `gorm:"size:512;not null;uniqueIndex"`
CreatedAt time.Time `json:"created_at"`
+2
View File
@@ -4,6 +4,7 @@ import "time"
type Notification struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_notifications_tenant_user_read" json:"tenant_id"`
UserID uint64 `gorm:"not null;index" json:"user_id"`
Type string `gorm:"size:32;not null" json:"type"`
Title string `gorm:"size:128;not null" json:"title"`
@@ -21,6 +22,7 @@ func (Notification) TableName() string {
type AdminNotification struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_admin_notifications_tenant_user_read" json:"tenant_id"`
AdminUserID uint64 `gorm:"not null;index" json:"admin_user_id"`
Type string `gorm:"size:32;not null" json:"type"`
Title string `gorm:"size:128;not null" json:"title"`
+1
View File
@@ -11,6 +11,7 @@ import (
// 因此短信通道异常不会影响业务提交。
type SmsMessage struct {
ID uint64 `gorm:"primaryKey" json:"id"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_sms_messages_tenant_node_biz_user;index:idx_sms_messages_tenant_status_id" json:"tenant_id"`
UserID uint64 `gorm:"not null;default:0" json:"user_id"`
Phone string `gorm:"size:32;not null;default:''" json:"phone"`
Node string `gorm:"size:64;not null" json:"node"`
+2 -1
View File
@@ -4,7 +4,8 @@ import "time"
type SystemConfig struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Key string `gorm:"column:key;size:128;not null;uniqueIndex" json:"key"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_system_configs_tenant_key" json:"tenant_id"`
Key string `gorm:"column:key;size:128;not null;uniqueIndex:uk_system_configs_tenant_key" json:"key"`
Value string `gorm:"column:value;type:text;not null" json:"value"`
Description string `gorm:"size:255;not null;default:''" json:"description"`
UpdatedBy *uint64 `json:"updated_by"`
@@ -18,6 +18,7 @@ type PaginatedResult struct {
type NotificationDTO struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
AdminUserID uint64 `json:"admin_user_id"`
Type string `json:"type"`
Title string `json:"title"`
@@ -4,6 +4,7 @@ import (
"context"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -21,6 +22,8 @@ func (r *Repository) List(ctx context.Context, query Query) (*PaginatedResult, e
Where("admin_user_id = ?", query.AdminUserID)
countDB := r.db.WithContext(ctx).Model(&model.AdminNotification{}).
Where("admin_user_id = ?", query.AdminUserID)
db = tenantFilter(ctx, db)
countDB = tenantFilter(ctx, countDB)
if query.OnlyUnread {
db = db.Where("is_read = ?", false)
countDB = countDB.Where("is_read = ?", false)
@@ -47,6 +50,7 @@ func (r *Repository) UnreadCount(ctx context.Context, adminUserID uint64) (int64
var total int64
err := r.db.WithContext(ctx).Model(&model.AdminNotification{}).
Where("admin_user_id = ? AND is_read = ?", adminUserID, false).
Scopes(func(db *gorm.DB) *gorm.DB { return tenantFilter(ctx, db) }).
Count(&total).Error
return total, err
}
@@ -54,6 +58,7 @@ func (r *Repository) UnreadCount(ctx context.Context, adminUserID uint64) (int64
func (r *Repository) MarkRead(ctx context.Context, adminUserID uint64, id uint64) error {
result := r.db.WithContext(ctx).Model(&model.AdminNotification{}).
Where("id = ? AND admin_user_id = ?", id, adminUserID).
Scopes(func(db *gorm.DB) *gorm.DB { return tenantFilter(ctx, db) }).
Update("is_read", true)
if result.Error != nil {
return result.Error
@@ -62,6 +67,7 @@ func (r *Repository) MarkRead(ctx context.Context, adminUserID uint64, id uint64
var total int64
if err := r.db.WithContext(ctx).Model(&model.AdminNotification{}).
Where("id = ? AND admin_user_id = ?", id, adminUserID).
Scopes(func(db *gorm.DB) *gorm.DB { return tenantFilter(ctx, db) }).
Count(&total).Error; err != nil {
return err
}
@@ -75,12 +81,14 @@ func (r *Repository) MarkRead(ctx context.Context, adminUserID uint64, id uint64
func (r *Repository) MarkAllRead(ctx context.Context, adminUserID uint64) (int64, error) {
result := r.db.WithContext(ctx).Model(&model.AdminNotification{}).
Where("admin_user_id = ? AND is_read = ?", adminUserID, false).
Scopes(func(db *gorm.DB) *gorm.DB { return tenantFilter(ctx, db) }).
Update("is_read", true)
return result.RowsAffected, result.Error
}
// Entry 描述一条待写入的管理员通知。
type Entry struct {
TenantID uint64
AdminUserID uint64
Type string
Title string
@@ -95,7 +103,21 @@ func Append(tx *gorm.DB, entries ...Entry) error {
if entry.AdminUserID == 0 || entry.Title == "" {
continue
}
tenantID := entry.TenantID
if tenantID == 0 {
var row struct {
TenantID uint64
}
if err := tx.Table("admin_user_roles").
Select("tenant_id").
Where("admin_user_id = ? AND tenant_id > 0", entry.AdminUserID).
Order("tenant_id ASC").
Take(&row).Error; err == nil {
tenantID = row.TenantID
}
}
row := model.AdminNotification{
TenantID: tenantID,
AdminUserID: entry.AdminUserID,
Type: entry.Type,
Title: entry.Title,
@@ -114,6 +136,7 @@ func Append(tx *gorm.DB, entries ...Entry) error {
func toDTO(row model.AdminNotification) NotificationDTO {
return NotificationDTO{
ID: row.ID,
TenantID: row.TenantID,
AdminUserID: row.AdminUserID,
Type: row.Type,
Title: row.Title,
@@ -123,3 +146,10 @@ func toDTO(row model.AdminNotification) NotificationDTO {
UpdatedAt: row.UpdatedAt,
}
}
func tenantFilter(ctx context.Context, db *gorm.DB) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where("tenant_id = ?", tenantID)
}
return db
}
@@ -4,6 +4,7 @@ import "time"
type AnnouncementDTO struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
DistributionSiteID uint64 `json:"distribution_site_id"`
DistributionSiteName string `json:"distribution_site_name,omitempty"`
Title string `json:"title"`
@@ -7,6 +7,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -49,6 +50,7 @@ func (r *Repository) ResolvePublicSiteScope(ctx context.Context, siteCode string
func (r *Repository) List(ctx context.Context, query AnnouncementListQuery) (*PaginatedResult, error) {
var total int64
tx := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("status = ?", "published")
tx = tenantScope(ctx, tx)
if len(query.AllowedSiteIDs) > 0 {
tx = tx.Where("distribution_site_id IN ?", query.AllowedSiteIDs)
@@ -91,6 +93,7 @@ func (r *Repository) List(ctx context.Context, query AnnouncementListQuery) (*Pa
func (r *Repository) PublicPopup(ctx context.Context, allowedSiteIDs []uint64) (*AnnouncementDTO, error) {
query := r.db.WithContext(ctx).
Where("status = ? AND is_popup = ?", "published", true)
query = tenantScope(ctx, query)
if len(allowedSiteIDs) > 0 {
query = query.Where("distribution_site_id IN ?", allowedSiteIDs)
}
@@ -114,6 +117,7 @@ func (r *Repository) GetByID(ctx context.Context, id uint64, allowedSiteIDs []ui
var announcement model.Announcement
db := r.db.WithContext(ctx)
query := db.Where("id = ? AND status = ?", id, "published")
query = tenantScope(ctx, query)
if len(allowedSiteIDs) > 0 {
query = query.Where("distribution_site_id IN ?", allowedSiteIDs)
}
@@ -163,6 +167,9 @@ func (r *Repository) adminListBase(ctx context.Context, query AnnouncementListQu
base := r.db.WithContext(ctx).Table("announcements AS a").
Select("a.id, a.distribution_site_id, COALESCE(s.site_name, '') AS distribution_site_name, a.title, a.content, a.category, a.priority, a.is_pinned, a.is_important, a.is_popup, a.view_count, a.status, a.published_at, a.created_at, a.updated_at").
Joins("LEFT JOIN distribution_sites AS s ON s.id = a.distribution_site_id")
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
base = base.Where("a.tenant_id = ?", tenantID)
}
if query.Status != "" {
base = base.Where("a.status = ?", query.Status)
@@ -193,6 +200,7 @@ func (r *Repository) AdminGetByID(ctx context.Context, id uint64) (*Announcement
// Create 创建公告
func (r *Repository) Create(ctx context.Context, req CreateAnnouncementRequest, createdBy uint64) (*AnnouncementDTO, error) {
announcement := model.Announcement{
TenantID: tenancy.IDFromContext(ctx),
DistributionSiteID: req.DistributionSiteID,
Title: req.Title,
Content: req.Content,
@@ -231,7 +239,11 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAnnounceme
updates["is_important"] = req.IsImportant
updates["is_popup"] = req.IsPopup
if err := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id).Updates(updates).Error; err != nil {
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Updates(updates).Error; err != nil {
return nil, err
}
@@ -241,8 +253,11 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAnnounceme
// Publish 发布公告
func (r *Repository) Publish(ctx context.Context, id uint64) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Announcement{}).
Where("id = ?", id).
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.
Updates(map[string]interface{}{
"status": "published",
"published_at": now,
@@ -251,16 +266,22 @@ func (r *Repository) Publish(ctx context.Context, id uint64) error {
// Archive 归档公告
func (r *Repository) Archive(ctx context.Context, id uint64) error {
return r.db.WithContext(ctx).Model(&model.Announcement{}).
Where("id = ?", id).
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.
Update("status", "archived").Error
}
// Unarchive 取消归档公告,恢复为已发布状态
func (r *Repository) Unarchive(ctx context.Context, id uint64) error {
now := time.Now()
return r.db.WithContext(ctx).Model(&model.Announcement{}).
Where("id = ?", id).
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.
Updates(map[string]interface{}{
"status": "published",
"published_at": gorm.Expr("COALESCE(published_at, ?)", now),
@@ -269,12 +290,17 @@ func (r *Repository) Unarchive(ctx context.Context, id uint64) error {
// Delete 删除公告
func (r *Repository) Delete(ctx context.Context, id uint64) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&model.Announcement{}).Error
query := r.db.WithContext(ctx).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.Delete(&model.Announcement{}).Error
}
func toAnnouncementDTO(a model.Announcement) AnnouncementDTO {
return AnnouncementDTO{
ID: a.ID,
TenantID: a.TenantID,
DistributionSiteID: a.DistributionSiteID,
Title: a.Title,
Content: a.Content,
@@ -290,3 +316,10 @@ func toAnnouncementDTO(a model.Announcement) AnnouncementDTO {
UpdatedAt: a.UpdatedAt,
}
}
func tenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where("tenant_id = ?", tenantID)
}
return db
}
@@ -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()
}
+26 -3
View File
@@ -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 -1
View File
@@ -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 在事务内发送系统文本消息。
+37 -19
View File
@@ -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": "二维码库存预警",
+54 -6
View File
@@ -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
})
}
+27 -14
View File
@@ -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
+96 -27
View File
@@ -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{
+40 -9
View File
@@ -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
}
+12 -2
View File
@@ -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)
+23 -6
View File
@@ -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
}
+11 -4
View File
@@ -6,6 +6,7 @@ import (
"time"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
@@ -38,7 +39,7 @@ func (h *Handler) UserEvents(c *gin.Context) {
response.Unauthorized(c, "用户上下文无效")
return
}
h.serveSSE(c, "user", userID)
h.serveSSE(c, "user", userID, tenancy.IDFromContext(c.Request.Context()), false)
}
// AdminEvents 处理管理端 SSE 连接: GET /api/admin/chats/events
@@ -53,14 +54,20 @@ func (h *Handler) AdminEvents(c *gin.Context) {
response.Unauthorized(c, "管理员上下文无效")
return
}
h.serveSSE(c, "admin", adminID)
platform := h.hub.IsPlatformAdmin(adminID)
h.serveSSE(c, "admin", adminID, tenancy.IDFromContext(c.Request.Context()), platform)
}
func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
func (h *Handler) serveSSE(c *gin.Context, pType string, pID, tenantID uint64, platform bool) {
startedAt := time.Now()
disconnectReason := "handler_completed"
var disconnectErr error
ch := h.hub.Subscribe(pType, pID)
var ch <-chan *ChatEvent
if pType == "admin" {
ch = h.hub.SubscribeAdmin(pID, tenantID, platform)
} else {
ch = h.hub.SubscribeForTenant(pType, pID, tenantID)
}
h.logger.Info("SSE 连接建立", h.connectionLogFields(c, pType, pID)...)
defer func() {
h.hub.Unsubscribe(pType, pID, ch)
+86 -29
View File
@@ -12,6 +12,8 @@ type ChatEvent struct {
Type string `json:"type"` // "new_message" | "conversation_updated" | "conversation_read"
ConversationID uint64 `json:"conversation_id"`
Message *MessageData `json:"message,omitempty"`
// TenantIDs 仅用于进程内推送路由,不返回给前端。
TenantIDs []uint64 `json:"-"`
// 以下字段仅在 conversation_read 事件中使用,标识谁在何时读取了会话。
ReaderType string `json:"reader_type,omitempty"`
ReaderID uint64 `json:"reader_id,omitempty"`
@@ -35,8 +37,10 @@ type MessageData struct {
// principal 标识一个连接方。
type principal struct {
Type string // "user" or "admin"
ID uint64
Type string // "user" or "admin"
ID uint64
TenantID uint64
PlatformAdmin bool
}
// Hub 管理所有 SSE 连接。
@@ -56,8 +60,21 @@ func NewHub(db *gorm.DB) *Hub {
// Subscribe 注册一个 SSE 连接,返回事件 channel。
func (h *Hub) Subscribe(pType string, pID uint64) <-chan *ChatEvent {
return h.SubscribeForTenant(pType, pID, 0)
}
// SubscribeForTenant 注册租户范围内的 SSE 连接。
func (h *Hub) SubscribeForTenant(pType string, pID, tenantID uint64) <-chan *ChatEvent {
return h.subscribe(principal{Type: pType, ID: pID, TenantID: tenantID})
}
// SubscribeAdmin 注册后台连接;平台超管可以接收全部租户会话事件。
func (h *Hub) SubscribeAdmin(adminID, tenantID uint64, platform bool) <-chan *ChatEvent {
return h.subscribe(principal{Type: "admin", ID: adminID, TenantID: tenantID, PlatformAdmin: platform})
}
func (h *Hub) subscribe(key principal) <-chan *ChatEvent {
ch := make(chan *ChatEvent, 16)
key := principal{Type: pType, ID: pID}
h.mu.Lock()
if h.clients[key] == nil {
h.clients[key] = make(map[chan *ChatEvent]struct{})
@@ -69,10 +86,11 @@ func (h *Hub) Subscribe(pType string, pID uint64) <-chan *ChatEvent {
// Unsubscribe 注销 SSE 连接。
func (h *Hub) Unsubscribe(pType string, pID uint64, ch <-chan *ChatEvent) {
key := principal{Type: pType, ID: pID}
h.mu.Lock()
if clients, ok := h.clients[key]; ok {
// 找到对应的发送 channel 并删除
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
for sendCh := range clients {
if sendCh == ch {
delete(clients, sendCh)
@@ -93,12 +111,15 @@ func (h *Hub) DisconnectUser(userID uint64) {
}
func (h *Hub) disconnect(pType string, pID uint64) {
key := principal{Type: pType, ID: pID}
h.mu.Lock()
clients := h.clients[key]
delete(h.clients, key)
for ch := range clients {
close(ch)
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
delete(h.clients, key)
for ch := range clients {
close(ch)
}
}
h.mu.Unlock()
}
@@ -143,27 +164,10 @@ func (h *Hub) NotifyConversation(conversationID uint64, event *ChatEvent) {
// NotifyUser 直接向指定用户/Admin 推送事件。
func (h *Hub) NotifyUser(pType string, pID uint64, event *ChatEvent) {
key := principal{Type: pType, ID: pID}
h.mu.RLock()
defer h.mu.RUnlock()
if clients, ok := h.clients[key]; ok {
for ch := range clients {
select {
case ch <- event:
default:
}
}
}
}
// NotifyAllAdmins 向所有在线管理员(客服)推送事件。
// 客服工作台的「未分配 / 全部」视图会展示当前客服并非参与者的会话,
// 仅靠 NotifyConversation(只推参与者)无法实时刷新,故对所有在线客服广播。
func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
h.mu.RLock()
defer h.mu.RUnlock()
for key, clients := range h.clients {
if key.Type != "admin" {
if key.Type != pType || key.ID != pID {
continue
}
for ch := range clients {
@@ -175,6 +179,59 @@ func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
}
}
// NotifyAllAdmins 向事件所属租户的在线管理员推送事件。
// 客服工作台的「未分配 / 全部」视图会展示当前客服并非参与者的会话,
// 仅靠 NotifyConversation(只推参与者)无法实时刷新,故对所有在线客服广播。
func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
h.mu.RLock()
defer h.mu.RUnlock()
for key, clients := range h.clients {
if key.Type != "admin" {
continue
}
if !key.PlatformAdmin && !adminClientMatchesEventTenant(key.TenantID, event) {
continue
}
for ch := range clients {
select {
case ch <- event:
default:
}
}
}
}
func adminClientMatchesEventTenant(tenantID uint64, event *ChatEvent) bool {
if event == nil {
return false
}
if len(event.TenantIDs) == 0 {
return tenantID == 0
}
if tenantID == 0 {
return false
}
for _, id := range event.TenantIDs {
if id == tenantID {
return true
}
}
return false
}
// IsPlatformAdmin 判断管理员是否拥有平台超管角色。
func (h *Hub) IsPlatformAdmin(adminID uint64) bool {
if h == nil || h.db == nil || adminID == 0 {
return false
}
var count int64
err := h.db.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 err == nil && count > 0
}
// MarshalEvent 将事件序列化为 SSE data 行。
func MarshalEvent(event *ChatEvent) string {
raw, _ := json.Marshal(event)
@@ -30,3 +30,28 @@ func TestDisconnectUserClosesAllConnections(t *testing.T) {
t.Fatalf("online admin connection count = %d, want 1", got)
}
}
func TestNotifyAllAdminsRespectsTenantAndPlatformScope(t *testing.T) {
hub := NewHub(nil)
tenantA := hub.SubscribeAdmin(1, 101, false)
tenantB := hub.SubscribeAdmin(2, 202, false)
platform := hub.SubscribeAdmin(3, 101, true)
hub.NotifyAllAdmins(&ChatEvent{
Type: "conversation_updated",
ConversationID: 9,
TenantIDs: []uint64{101},
})
if got := <-tenantA; got.ConversationID != 9 {
t.Fatalf("tenant A conversation = %d", got.ConversationID)
}
if got := <-platform; got.ConversationID != 9 {
t.Fatalf("platform conversation = %d", got.ConversationID)
}
select {
case event := <-tenantB:
t.Fatalf("tenant B received cross-tenant event: %+v", event)
default:
}
}
@@ -7,6 +7,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -48,6 +49,9 @@ func (r *Repository) ListSiteAnnouncements(ctx context.Context, adminID, siteID
}
base := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("distribution_site_id = ?", siteID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
base = base.Where("tenant_id = ?", tenantID)
}
if s := strings.TrimSpace(status); s != "" {
base = base.Where("status = ?", s)
}
@@ -83,6 +87,7 @@ func (r *Repository) CreateSiteAnnouncement(ctx context.Context, adminID, siteID
}
createdBy := adminID
row := model.Announcement{
TenantID: tenancy.IDFromContext(ctx),
DistributionSiteID: siteID,
Title: strings.TrimSpace(req.Title),
Content: req.Content,
@@ -199,7 +204,11 @@ func (r *Repository) DeleteSiteAnnouncement(ctx context.Context, adminID, siteID
// findSiteAnnouncement 按站点归属读取公告,跨站 ID 一律视为不存在。
func (r *Repository) findSiteAnnouncement(ctx context.Context, siteID, id uint64) (*model.Announcement, error) {
var row model.Announcement
err := r.db.WithContext(ctx).Where("id = ? AND distribution_site_id = ?", id, siteID).First(&row).Error
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)
}
err := query.First(&row).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAnnouncementNotFound
@@ -17,6 +17,7 @@ import (
listingpkg "hfb_sys/backend/internal/modules/listing"
"hfb_sys/backend/internal/modules/systemconfig"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/crypto"
"github.com/redis/go-redis/v9"
@@ -422,7 +423,11 @@ func (r *Repository) resolveDefaultSettlementHoldDays(ctx context.Context) int {
return systemconfig.DefaultDistributionSettlementHoldDays
}
var row model.SystemConfig
if err := r.db.WithContext(ctx).Where("`key` = ?", systemconfig.DistributionSettlementHoldDaysKey).First(&row).Error; err != nil {
query := r.db.WithContext(ctx).Where("`key` = ?", systemconfig.DistributionSettlementHoldDaysKey)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&row).Error; err != nil {
return systemconfig.DefaultDistributionSettlementHoldDays
}
return systemconfig.ParseDistributionSettlementHoldDays(row.Value)
+26 -4
View File
@@ -5,6 +5,7 @@ import (
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -23,7 +24,11 @@ func (r *Repository) GetConfig(ctx context.Context) (*ConfigDTO, error) {
}
keys := []string{configKeyDefaultQrcodeURL, configKeyOrderCopyTemplate}
var rows []model.SystemConfig
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
}
values := map[string]string{}
@@ -60,13 +65,18 @@ func (r *Repository) UpdateConfig(ctx context.Context, req UpdateConfigRequest)
}
func upsertConfig(tx *gorm.DB, key, value, description string) error {
tenantID := uint64(0)
if tx.Statement != nil && tx.Statement.Context != nil {
tenantID = tenancy.IDFromContext(tx.Statement.Context)
}
row := model.SystemConfig{
TenantID: tenantID,
Key: key,
Value: value,
Description: description,
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "key"}},
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "key"}},
DoUpdates: clause.AssignmentColumns([]string{"value", "description"}),
}).Create(&row).Error
}
@@ -86,7 +96,13 @@ func (r *Repository) resolveQrcodeURL(tx *gorm.DB, productQrcode string) string
return productQrcode
}
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", configKeyDefaultQrcodeURL).First(&cfg).Error; err == nil {
query := tx.Where("`key` = ?", configKeyDefaultQrcodeURL)
if tx.Statement != nil && tx.Statement.Context != nil {
if tenantID := tenancy.IDFromContext(tx.Statement.Context); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
}
if err := query.First(&cfg).Error; err == nil {
return strings.TrimSpace(cfg.Value)
}
return ""
@@ -94,7 +110,13 @@ func (r *Repository) resolveQrcodeURL(tx *gorm.DB, productQrcode string) string
func (r *Repository) loadCopyTemplate(tx *gorm.DB) string {
var cfg model.SystemConfig
if err := tx.Where("`key` = ?", configKeyOrderCopyTemplate).First(&cfg).Error; err == nil && strings.TrimSpace(cfg.Value) != "" {
query := tx.Where("`key` = ?", configKeyOrderCopyTemplate)
if tx.Statement != nil && tx.Statement.Context != nil {
if tenantID := tenancy.IDFromContext(tx.Statement.Context); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
}
if err := query.First(&cfg).Error; err == nil && strings.TrimSpace(cfg.Value) != "" {
return strings.TrimSpace(cfg.Value)
}
return defaultOrderCopyTemplate
@@ -4,6 +4,7 @@ import "time"
type NotificationDTO struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
UserID uint64 `json:"user_id"`
Type string `json:"type"`
Title string `json:"title"`
@@ -7,6 +7,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -16,6 +17,7 @@ type Repository struct {
}
type Entry struct {
TenantID uint64
UserID uint64
Type string
Title string
@@ -62,6 +64,7 @@ func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int
}
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ?", userID)
query = tenantFilter(ctx, query)
query = r.applySiteFilter(query, siteID, isSite)
var total int64
@@ -71,6 +74,7 @@ func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int
offset := (page - 1) * pageSize
var rows []model.Notification
dataQuery := r.db.WithContext(ctx).Where("user_id = ?", userID)
dataQuery = tenantFilter(ctx, dataQuery)
dataQuery = r.applySiteFilter(dataQuery, siteID, isSite)
if err := dataQuery.Order("id DESC").Offset(offset).Limit(pageSize).Find(&rows).Error; err != nil {
return nil, err
@@ -94,6 +98,7 @@ func (r *Repository) MarkRead(ctx context.Context, userID uint64, id uint64, sit
now := time.Now()
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("id = ? AND user_id = ?", id, userID)
query = tenantFilter(ctx, query)
query = r.applySiteFilter(query, siteID, isSite)
result := query.Update("read_at", now)
@@ -102,6 +107,7 @@ func (r *Repository) MarkRead(ctx context.Context, userID uint64, id uint64, sit
}
if result.RowsAffected == 0 {
checkQuery := r.db.WithContext(ctx).Model(&model.Notification{}).Where("id = ? AND user_id = ?", id, userID)
checkQuery = tenantFilter(ctx, checkQuery)
checkQuery = r.applySiteFilter(checkQuery, siteID, isSite)
var total int64
if err := checkQuery.Count(&total).Error; err != nil {
@@ -125,6 +131,7 @@ func (r *Repository) UnreadCount(ctx context.Context, userID uint64, siteCode ..
}
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", userID)
query = tenantFilter(ctx, query)
query = r.applySiteFilter(query, siteID, isSite)
var total int64
@@ -144,6 +151,7 @@ func (r *Repository) MarkAllRead(ctx context.Context, userID uint64, siteCode ..
now := time.Now()
query := r.db.WithContext(ctx).Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", userID)
query = tenantFilter(ctx, query)
query = r.applySiteFilter(query, siteID, isSite)
result := query.Update("read_at", now)
@@ -155,6 +163,13 @@ func Append(tx *gorm.DB, entries ...Entry) error {
if entry.UserID == 0 || entry.Title == "" {
continue
}
tenantID := entry.TenantID
if tenantID == 0 {
var user model.User
if err := tx.Select("tenant_id").First(&user, entry.UserID).Error; err == nil {
tenantID = user.TenantID
}
}
siteID := entry.DistributionSiteID
if siteID == nil {
if (entry.BizType == "order" || entry.BizType == "order_handoff") && entry.BizID != nil && *entry.BizID > 0 {
@@ -174,6 +189,7 @@ func Append(tx *gorm.DB, entries ...Entry) error {
}
}
row := model.Notification{
TenantID: tenantID,
UserID: entry.UserID,
Type: entry.Type,
Title: entry.Title,
@@ -195,6 +211,7 @@ func Append(tx *gorm.DB, entries ...Entry) error {
func toDTO(row model.Notification) NotificationDTO {
return NotificationDTO{
ID: row.ID,
TenantID: row.TenantID,
UserID: row.UserID,
Type: row.Type,
Title: row.Title,
@@ -206,3 +223,10 @@ func toDTO(row model.Notification) NotificationDTO {
CreatedAt: row.CreatedAt,
}
}
func tenantFilter(ctx context.Context, db *gorm.DB) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where("tenant_id = ?", tenantID)
}
return db
}
@@ -7,6 +7,7 @@ import (
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
@@ -191,3 +192,53 @@ func TestNotificationTenantIsolation(t *testing.T) {
t.Fatalf("autoNotif.DistributionSiteID = %v, want %d", autoNotif.DistributionSiteID, siteID)
}
}
func TestNotificationTenantScopeAndAppendDerivation(t *testing.T) {
db := database.NewTestDB()
if err := database.AutoMigrateIfMissing(db, &model.Tenant{}, &model.User{}, &model.Notification{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
tenantA := model.Tenant{Code: "notify-a", Name: "通知 A", Status: "active"}
tenantB := model.Tenant{Code: "notify-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)
}
userA := model.User{TenantID: tenantA.ID, Phone: "13700000001"}
userB := model.User{TenantID: tenantB.ID, Phone: "13700000002"}
if err := db.Create(&userA).Error; err != nil {
t.Fatalf("创建用户 A: %v", err)
}
if err := db.Create(&userB).Error; err != nil {
t.Fatalf("创建用户 B: %v", err)
}
if err := Append(db,
Entry{UserID: userA.ID, Title: "A 通知"},
Entry{UserID: userB.ID, Title: "B 通知"},
); err != nil {
t.Fatalf("Append(): %v", err)
}
var rows []model.Notification
if err := db.Order("id ASC").Find(&rows).Error; err != nil {
t.Fatalf("查询通知: %v", err)
}
if len(rows) != 2 || rows[0].TenantID != tenantA.ID || rows[1].TenantID != tenantB.ID {
t.Fatalf("通知租户回填异常: %+v", rows)
}
repo := NewRepository(db)
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantA.ID})
listA, err := repo.List(ctxA, userA.ID, 1, 20)
if err != nil {
t.Fatalf("查询租户 A 通知: %v", err)
}
if listA.Total != 1 {
t.Fatalf("租户 A 通知数 = %d, want 1", listA.Total)
}
ctxWrong := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantB.ID})
if err := repo.MarkRead(ctxWrong, userA.ID, rows[0].ID); !errors.Is(err, ErrNotificationNotFound) {
t.Fatalf("跨租户标记已读 error = %v, want not found", err)
}
}
+7 -1
View File
@@ -440,7 +440,13 @@ func (r *Repository) FindForUser(ctx context.Context, userID uint64, orderID uin
func pendingPaymentTimeoutMinutes(tx *gorm.DB) int {
var row model.SystemConfig
err := tx.Where("`key` = ?", "order.pending_payment_timeout_minutes").First(&row).Error
query := tx.Where("`key` = ?", "order.pending_payment_timeout_minutes")
if tx.Statement != nil && tx.Statement.Context != nil {
if tenantID := tenancy.IDFromContext(tx.Statement.Context); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
}
err := query.First(&row).Error
if err != nil {
return defaultPendingPaymentTimeoutMinutes
}
@@ -10,6 +10,7 @@ import (
"hfb_sys/backend/internal/auditlog"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -53,7 +54,11 @@ func (r *Repository) Rules(ctx context.Context) (Rules, error) {
return Rules{}, ErrDependencyUnavailable
}
var row model.SystemConfig
err := r.db.WithContext(ctx).Where("`key` = ?", ConfigKey).First(&row).Error
query := r.db.WithContext(ctx).Where("`key` = ?", ConfigKey)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
err := query.First(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return DefaultRules(), nil
}
@@ -9,6 +9,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -186,7 +187,13 @@ func ConfigForTx(tx *gorm.DB) (Config, error) {
return cfg, nil
}
var row model.SystemConfig
if err := tx.Where("`key` = ?", ConfigKey).First(&row).Error; err != nil {
query := tx.Where("`key` = ?", ConfigKey)
if tx.Statement != nil && tx.Statement.Context != nil {
if tenantID := tenancy.IDFromContext(tx.Statement.Context); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
}
if err := query.First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) || isMissingConfigTableError(err) {
return cfg, nil
}
@@ -637,16 +644,32 @@ func EffectiveDepositFreeQuotaCent(levelQuotaCent int64, manualQuotaCent int64)
// SyncAllUserLevels 在等级门槛调整后同步用户表中的展示缓存,订单仍以积分实时计算为准。
func SyncAllUserLevels(tx *gorm.DB, cfg Config) error {
return syncAllUserLevels(tx, cfg, 0)
}
// SyncAllUserLevelsForTenant 只重算指定经营租户的用户等级。
func SyncAllUserLevelsForTenant(tx *gorm.DB, cfg Config, tenantID uint64) error {
return syncAllUserLevels(tx, cfg, tenantID)
}
func syncAllUserLevels(tx *gorm.DB, cfg Config, tenantID uint64) error {
if tx == nil {
return nil
}
userQuery := func() *gorm.DB {
query := tx.Model(&model.User{})
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query
}
if !cfg.Enabled {
if err := tx.Model(&model.User{}).
if err := userQuery().
Where("renter_growth_level_override = ? AND renter_growth_level <> ?", "", DefaultLevelCode).
Update("renter_growth_level", DefaultLevelCode).Error; err != nil {
return err
}
return tx.Model(&model.User{}).
return userQuery().
Where("renter_growth_level_override <> ?", "").
UpdateColumn("renter_growth_level", gorm.Expr("renter_growth_level_override")).Error
}
@@ -659,12 +682,12 @@ func SyncAllUserLevels(tx *gorm.DB, cfg Config) error {
}
caseSQL += " ELSE ? END"
args = append(args, DefaultLevelCode)
if err := tx.Model(&model.User{}).
if err := userQuery().
Where("renter_growth_level_override = ?", "").
Update("renter_growth_level", gorm.Expr(caseSQL, args...)).Error; err != nil {
return err
}
return tx.Model(&model.User{}).
return userQuery().
Where("renter_growth_level_override <> ?", "").
UpdateColumn("renter_growth_level", gorm.Expr("renter_growth_level_override")).Error
}
+11 -3
View File
@@ -27,6 +27,7 @@ func NewRepository(db *gorm.DB) *Repository {
// - 被租用需辅助:每个订单发一次,同一账号被反复租用会分别提醒;
// - 上架未成交:同一账号只发一次。
type Entry struct {
TenantID uint64
UserID uint64
Phone string
Node string
@@ -48,11 +49,17 @@ func Enqueue(tx *gorm.DB, entry Entry) (bool, error) {
return false, nil
}
tenantID := entry.TenantID
phone := strings.TrimSpace(entry.Phone)
if phone == "" {
if phone == "" || tenantID == 0 {
var user model.User
if err := tx.Select("id", "phone").First(&user, entry.UserID).Error; err == nil {
phone = strings.TrimSpace(user.Phone)
if err := tx.Select("id", "phone", "tenant_id").First(&user, entry.UserID).Error; err == nil {
if phone == "" {
phone = strings.TrimSpace(user.Phone)
}
if tenantID == 0 {
tenantID = user.TenantID
}
}
}
@@ -66,6 +73,7 @@ func Enqueue(tx *gorm.DB, entry Entry) (bool, error) {
}
row := model.SmsMessage{
TenantID: tenantID,
UserID: entry.UserID,
Phone: phone,
Node: node,
@@ -82,6 +82,44 @@ func TestEnqueueIgnoresUnknownNodeAndMissingUser(t *testing.T) {
}
}
func TestEnqueueDerivesAndDeduplicatesByTenant(t *testing.T) {
db := newSmsTestDB(t)
tenantA := model.Tenant{Code: "sms-a", Name: "短信 A", Status: "active"}
tenantB := model.Tenant{Code: "sms-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)
}
userA := model.User{TenantID: tenantA.ID, Phone: "13600000001"}
userB := model.User{TenantID: tenantB.ID, Phone: "13600000002"}
if err := db.Create(&userA).Error; err != nil {
t.Fatalf("创建用户 A: %v", err)
}
if err := db.Create(&userB).Error; err != nil {
t.Fatalf("创建用户 B: %v", err)
}
for _, userID := range []uint64{userA.ID, userB.ID} {
inserted, err := Enqueue(db, Entry{
UserID: userID,
Node: NodeListingReviewRejected,
BizType: "listing",
BizID: 7001,
})
if err != nil || !inserted {
t.Fatalf("Enqueue(%d) inserted=%v err=%v", userID, inserted, err)
}
}
var rows []model.SmsMessage
if err := db.Where("node = ? AND biz_id = ?", NodeListingReviewRejected, 7001).Order("id ASC").Find(&rows).Error; err != nil {
t.Fatalf("查询短信: %v", err)
}
if len(rows) != 2 || rows[0].TenantID != tenantA.ID || rows[1].TenantID != tenantB.ID {
t.Fatalf("短信租户隔离异常: %+v", rows)
}
}
func TestRepositoryStatusTransitions(t *testing.T) {
db := newSmsTestDB(t)
ctx := context.Background()
@@ -6,6 +6,7 @@ import (
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -21,7 +22,8 @@ func NewRepository(db *gorm.DB) *Repository {
func (r *Repository) List(ctx context.Context) ([]GroupDTO, error) {
var groups []model.ChatSupportGroup
if err := r.db.WithContext(ctx).Order("sort_order ASC, id ASC").Find(&groups).Error; err != nil {
query := tenantScope(ctx, r.db.WithContext(ctx))
if err := query.Order("sort_order ASC, id ASC").Find(&groups).Error; err != nil {
return nil, err
}
items := make([]GroupDTO, 0, len(groups))
@@ -37,7 +39,7 @@ func (r *Repository) List(ctx context.Context) ([]GroupDTO, error) {
func (r *Repository) FindByID(ctx context.Context, id uint64) (*GroupDTO, error) {
var group model.ChatSupportGroup
if err := r.db.WithContext(ctx).First(&group, id).Error; err != nil {
if err := tenantScope(ctx, r.db.WithContext(ctx)).First(&group, id).Error; err != nil {
return nil, err
}
dto, err := r.toDTO(ctx, group)
@@ -54,6 +56,7 @@ func (r *Repository) Create(ctx context.Context, req CreateGroupRequest) (*Group
}
status := normalizeStatus(req.Status)
group := model.ChatSupportGroup{
TenantID: tenancy.IDFromContext(ctx),
Code: code,
Name: strings.TrimSpace(req.Name),
Description: strings.TrimSpace(req.Description),
@@ -75,7 +78,7 @@ func (r *Repository) Create(ctx context.Context, req CreateGroupRequest) (*Group
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateGroupRequest) (*GroupDTO, error) {
var group model.ChatSupportGroup
db := r.db.WithContext(ctx)
if err := db.First(&group, id).Error; err != nil {
if err := tenantScope(ctx, db).First(&group, id).Error; err != nil {
return nil, err
}
group.Name = strings.TrimSpace(req.Name)
@@ -97,7 +100,7 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateGroupReque
func (r *Repository) Delete(ctx context.Context, id uint64) error {
var group model.ChatSupportGroup
db := r.db.WithContext(ctx)
if err := db.First(&group, id).Error; err != nil {
if err := tenantScope(ctx, db).First(&group, id).Error; err != nil {
return err
}
if isProtectedCode(group.Code) {
@@ -113,7 +116,7 @@ func (r *Repository) Delete(ctx context.Context, id uint64) error {
func (r *Repository) AssignMembers(ctx context.Context, id uint64, memberIDs []uint64) error {
var count int64
if err := r.db.WithContext(ctx).Model(&model.ChatSupportGroup{}).Where("id = ?", id).Count(&count).Error; err != nil {
if err := tenantScope(ctx, r.db.WithContext(ctx)).Model(&model.ChatSupportGroup{}).Where("id = ?", id).Count(&count).Error; err != nil {
return err
}
if count == 0 {
@@ -131,11 +134,16 @@ func (r *Repository) ListSupportAdmins(ctx context.Context) ([]MemberDTO, error)
Nickname string
SupportStatus string
}
err := r.db.WithContext(ctx).Table("admin_users AS au").
tenantID := tenancy.IDFromContext(ctx)
query := r.db.WithContext(ctx).Table("admin_users AS au").
Select("DISTINCT au.id, au.username, au.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", "cs").
Where("au.status = ? AND r.code = ?", "active", "cs")
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(&rows).Error
if err != nil {
@@ -200,6 +208,10 @@ func (r *Repository) members(ctx context.Context, groupID uint64) ([]MemberDTO,
}
func replaceMembers(tx *gorm.DB, groupID uint64, memberIDs []uint64) error {
var group model.ChatSupportGroup
if err := tx.Select("tenant_id").First(&group, groupID).Error; err != nil {
return err
}
if err := tx.Where("group_id = ?", groupID).Delete(&model.ChatSupportGroupMember{}).Error; err != nil {
return err
}
@@ -207,6 +219,17 @@ func replaceMembers(tx *gorm.DB, groupID uint64, memberIDs []uint64) error {
if adminID == 0 {
continue
}
if group.TenantID > 0 {
var count int64
if err := tx.Table("admin_user_roles").
Where("admin_user_id = ? AND tenant_id = ?", adminID, group.TenantID).
Count(&count).Error; err != nil {
return err
}
if count == 0 {
continue
}
}
member := model.ChatSupportGroupMember{GroupID: groupID, AdminID: adminID}
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&member).Error; err != nil {
return err
@@ -251,6 +274,13 @@ func uniqueIDs(ids []uint64) []uint64 {
return result
}
func tenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where("tenant_id = ?", tenantID)
}
return db
}
func IsNotFound(err error) bool {
return errors.Is(err, gorm.ErrRecordNotFound)
}
@@ -9,14 +9,29 @@ import (
)
func PickSupportAdmin(tx *gorm.DB, groupCode string) (uint64, error) {
return pickSupportAdmin(tx, groupCode, 0)
}
// PickSupportAdminForTenant 仅在指定经营租户的客服分组和角色绑定中选人。
func PickSupportAdminForTenant(tx *gorm.DB, groupCode string, tenantID uint64) (uint64, error) {
return pickSupportAdmin(tx, groupCode, tenantID)
}
func pickSupportAdmin(tx *gorm.DB, groupCode string, tenantID uint64) (uint64, error) {
var row struct {
ID uint64
}
err := tx.Table("chat_support_groups AS g").
query := tx.Table("chat_support_groups AS g").
Select("au.id").
Joins("JOIN chat_support_group_members AS gm ON gm.group_id = g.id").
Joins("JOIN admin_users AS au ON au.id = gm.admin_user_id").
Where("g.code = ? AND g.status = ? AND au.status = ?", groupCode, "active", "active").
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("g.code = ? AND g.status = ? AND au.status = ? AND r.code = ?", groupCode, "active", "active", "cs")
if tenantID > 0 {
query = query.Where("g.tenant_id = ? AND aur.tenant_id = ?", tenantID, tenantID)
}
err := query.
Order(`CASE au.support_status WHEN 'online' THEN 0 WHEN 'busy' THEN 1 ELSE 2 END,
(
SELECT COUNT(1)
@@ -34,16 +49,20 @@ func PickSupportAdmin(tx *gorm.DB, groupCode string) (uint64, error) {
if row.ID > 0 {
return row.ID, nil
}
return fallbackSupportAdmin(tx)
return fallbackSupportAdmin(tx, tenantID)
}
func fallbackSupportAdmin(tx *gorm.DB) (uint64, error) {
func fallbackSupportAdmin(tx *gorm.DB, tenantID uint64) (uint64, error) {
var admin model.AdminUser
err := tx.Table("admin_users AS au").
query := tx.Table("admin_users AS au").
Select("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", "cs").
Where("au.status = ? AND r.code = ?", "active", "cs")
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").
Limit(1).
First(&admin).Error
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/modules/qualityowner"
"hfb_sys/backend/internal/modules/rentergrowth"
smsnode "hfb_sys/backend/internal/modules/sms"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -21,7 +22,7 @@ import (
type Repository struct {
db *gorm.DB
initMu sync.RWMutex
initialized bool
initialized map[uint64]bool
}
type AuditMeta = auditlog.Meta
@@ -99,14 +100,15 @@ var adminVisibleConfigKeys = []string{
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
return &Repository{db: db, initialized: make(map[uint64]bool)}
}
// EnsureDefaults 仅在服务启动或首次访问时初始化默认系统配置。
// 使用读写锁保证进程生命周期内只真正落库初始化一次,避免每个读请求重复开事务写锁争抢。
func (r *Repository) EnsureDefaults(ctx context.Context) error {
tenantID := tenancy.IDFromContext(ctx)
r.initMu.RLock()
if r.initialized {
if r.initialized[tenantID] {
r.initMu.RUnlock()
return nil
}
@@ -114,13 +116,13 @@ func (r *Repository) EnsureDefaults(ctx context.Context) error {
r.initMu.Lock()
defer r.initMu.Unlock()
if r.initialized {
if r.initialized[tenantID] {
return nil
}
if err := r.ensureDefaults(ctx); err != nil {
if err := r.ensureDefaults(ctx, tenantID); err != nil {
return err
}
r.initialized = true
r.initialized[tenantID] = true
return nil
}
@@ -129,7 +131,8 @@ func (r *Repository) List(ctx context.Context) ([]ConfigDTO, error) {
return nil, err
}
var rows []model.SystemConfig
if err := r.db.WithContext(ctx).Where("`key` IN ?", adminVisibleConfigKeys).Order("`key` ASC").Find(&rows).Error; err != nil {
query := applyTenantScope(ctx, r.db.WithContext(ctx))
if err := query.Where("`key` IN ?", adminVisibleConfigKeys).Order("`key` ASC").Find(&rows).Error; err != nil {
return nil, err
}
items := make([]ConfigDTO, 0, len(rows))
@@ -150,7 +153,7 @@ func (r *Repository) FindValue(ctx context.Context, key string) (string, error)
return "", err
}
var row model.SystemConfig
if err := r.db.WithContext(ctx).Where("`key` = ?", key).First(&row).Error; err != nil {
if err := applyTenantScope(ctx, r.db.WithContext(ctx)).Where("`key` = ?", key).First(&row).Error; err != nil {
return "", err
}
return row.Value, nil
@@ -161,10 +164,16 @@ func (r *Repository) Update(ctx context.Context, actorID uint64, key string, req
return nil, err
}
var row model.SystemConfig
tenantID := tenancy.IDFromContext(ctx)
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("`key` = ?", key).First(&row).Error; err != nil {
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("`key` = ?", key)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&row).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
row = model.SystemConfig{
TenantID: tenantID,
Key: key,
Value: req.Value,
Description: req.Description,
@@ -186,7 +195,7 @@ func (r *Repository) Update(ctx context.Context, actorID uint64, key string, req
if err := tx.Save(&row).Error; err != nil {
return err
}
if err := syncRenterGrowthLevels(tx, key, req.Value); err != nil {
if err := syncRenterGrowthLevels(tx, key, req.Value, tenantID); err != nil {
return err
}
if err := appendAuditLog(tx, actorID, "system_config.update", row.ID, meta, map[string]any{
@@ -198,7 +207,7 @@ func (r *Repository) Update(ctx context.Context, actorID uint64, key string, req
}
return nil
}
if err := syncRenterGrowthLevels(tx, key, req.Value); err != nil {
if err := syncRenterGrowthLevels(tx, key, req.Value, tenantID); err != nil {
return err
}
return appendAuditLog(tx, actorID, "system_config.create", row.ID, meta, map[string]any{
@@ -213,7 +222,7 @@ func (r *Repository) Update(ctx context.Context, actorID uint64, key string, req
return &dto, nil
}
func syncRenterGrowthLevels(tx *gorm.DB, key string, value string) error {
func syncRenterGrowthLevels(tx *gorm.DB, key string, value string, tenantID uint64) error {
if key != rentergrowth.ConfigKey {
return nil
}
@@ -221,13 +230,14 @@ func syncRenterGrowthLevels(tx *gorm.DB, key string, value string) error {
if err != nil {
return err
}
return rentergrowth.SyncAllUserLevels(tx, cfg)
return rentergrowth.SyncAllUserLevelsForTenant(tx, cfg, tenantID)
}
func (r *Repository) ensureDefaults(ctx context.Context) error {
func (r *Repository) ensureDefaults(ctx context.Context, tenantID uint64) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, item := range defaultConfigs {
row := model.SystemConfig{
TenantID: tenantID,
Key: item.Key,
Value: item.Value,
Description: item.Description,
@@ -236,17 +246,17 @@ func (r *Repository) ensureDefaults(ctx context.Context) error {
return err
}
if item.Key == "chat.default_support_admin_id" {
if err := updateDefaultSupportConfig(tx, item); err != nil {
if err := updateDefaultSupportConfig(tx, item, tenantID); err != nil {
return err
}
}
if item.Key == "chat.listing_group_welcome" {
if err := updateLegacyListingGroupWelcome(tx, item); err != nil {
if err := updateLegacyListingGroupWelcome(tx, item, tenantID); err != nil {
return err
}
}
if item.Key == publishOptionsConfigKey {
if err := updateLegacyPublishOptions(tx, item); err != nil {
if err := updateLegacyPublishOptions(tx, item, tenantID); err != nil {
return err
}
}
@@ -255,9 +265,13 @@ func (r *Repository) ensureDefaults(ctx context.Context) error {
})
}
func updateLegacyListingGroupWelcome(tx *gorm.DB, item defaultConfig) error {
func updateLegacyListingGroupWelcome(tx *gorm.DB, item defaultConfig, tenantID uint64) error {
var row model.SystemConfig
if err := tx.Where("`key` = ?", item.Key).First(&row).Error; err != nil {
query := tx.Where("`key` = ?", item.Key)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&row).Error; err != nil {
return err
}
changed := false
@@ -275,9 +289,13 @@ func updateLegacyListingGroupWelcome(tx *gorm.DB, item defaultConfig) error {
return tx.Save(&row).Error
}
func updateDefaultSupportConfig(tx *gorm.DB, item defaultConfig) error {
func updateDefaultSupportConfig(tx *gorm.DB, item defaultConfig, tenantID uint64) error {
var row model.SystemConfig
if err := tx.Where("`key` = ?", item.Key).First(&row).Error; err != nil {
query := tx.Where("`key` = ?", item.Key)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&row).Error; err != nil {
return err
}
changed := false
@@ -295,9 +313,13 @@ func updateDefaultSupportConfig(tx *gorm.DB, item defaultConfig) error {
return tx.Save(&row).Error
}
func updateLegacyPublishOptions(tx *gorm.DB, item defaultConfig) error {
func updateLegacyPublishOptions(tx *gorm.DB, item defaultConfig, tenantID uint64) error {
var row model.SystemConfig
if err := tx.Where("`key` = ?", item.Key).First(&row).Error; err != nil {
query := tx.Where("`key` = ?", item.Key)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&row).Error; err != nil {
return err
}
normalized, err := normalizePublishOptionsValue(row.Value)
@@ -538,3 +560,10 @@ func toDTO(row model.SystemConfig) ConfigDTO {
UpdatedAt: row.UpdatedAt,
}
}
func applyTenantScope(ctx context.Context, db *gorm.DB) *gorm.DB {
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
return db.Where("tenant_id = ?", tenantID)
}
return db
}
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -63,3 +64,40 @@ func TestRepositoryEnsureDefaultsConcurrency(t *testing.T) {
}
wg.Wait()
}
func TestRepositoryDefaultsAreTenantScoped(t *testing.T) {
repo, db := newTestSystemConfigRepo(t)
tenantA := model.Tenant{Code: "config-a", Name: "配置 A", Status: "active"}
tenantB := model.Tenant{Code: "config-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)
}
ctxA := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantA.ID})
ctxB := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: tenantB.ID})
if err := repo.EnsureDefaults(ctxA); err != nil {
t.Fatalf("初始化租户 A 配置: %v", err)
}
if err := repo.EnsureDefaults(ctxB); err != nil {
t.Fatalf("初始化租户 B 配置: %v", err)
}
var count int64
if err := db.Model(&model.SystemConfig{}).
Where("`key` = ? AND tenant_id IN ?", "order.pending_payment_timeout_minutes", []uint64{tenantA.ID, tenantB.ID}).
Count(&count).Error; err != nil {
t.Fatalf("统计租户配置: %v", err)
}
if count != 2 {
t.Fatalf("租户配置数 = %d, want 2", count)
}
valueA, err := repo.FindValue(ctxA, "order.pending_payment_timeout_minutes")
if err != nil || valueA != "15" {
t.Fatalf("租户 A 配置 = %q err=%v", valueA, err)
}
valueB, err := repo.FindValue(ctxB, "order.pending_payment_timeout_minutes")
if err != nil || valueB != "15" {
t.Fatalf("租户 B 配置 = %q err=%v", valueB, err)
}
}
+25 -11
View File
@@ -6,6 +6,7 @@ import (
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
@@ -35,6 +36,7 @@ func privateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (b
}
}
encodedBasePrefix := url.QueryEscape(basePrefix)
tenantID := tenancy.IDFromContext(ctx)
var count int64
queries := []struct {
@@ -42,56 +44,67 @@ func privateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (b
args []any
}{
{
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE user_id = ? AND object_key = ?",
args: []any{userID, key},
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE user_id = ? AND object_key = ? AND (? = 0 OR tenant_id = ?)",
args: []any{userID, key, tenantID, tenantID},
},
{
sql: `SELECT COUNT(1) FROM game_accounts a
JOIN rental_listings l ON l.account_id = a.id
WHERE l.status = 'published' AND l.review_status = 'approved'
AND (? = 0 OR l.source_tenant_id = ?)
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
args: []any{key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM game_accounts a
WHERE a.owner_id = ?
WHERE a.owner_id = ? AND (? = 0 OR a.source_tenant_id = ?)
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
args: []any{userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM game_accounts a
JOIN rental_orders o ON o.account_id = a.id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (? = 0 OR o.buyer_tenant_id = ? OR o.source_tenant_id = ?)
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, userID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM order_checkouts c
JOIN rental_orders o ON o.id = c.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (? = 0 OR o.buyer_tenant_id = ? OR o.source_tenant_id = ?)
AND (INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, userID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM disputes d
JOIN rental_orders o ON o.id = d.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (? = 0 OR o.buyer_tenant_id = ? OR o.source_tenant_id = ?)
AND (INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, userID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM handoff_records h
JOIN rental_orders o ON o.id = h.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (? = 0 OR o.buyer_tenant_id = ? OR o.source_tenant_id = ?)
AND (INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, userID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM chat_messages m
JOIN chat_participants p ON p.conversation_id = m.conversation_id
LEFT JOIN chat_conversations c ON c.id = m.conversation_id
WHERE p.participant_type = 'user' AND p.participant_id = ?
AND (? = 0 OR c.tenant_id = ? OR EXISTS (
SELECT 1 FROM rental_orders ro WHERE ro.id = c.order_id AND (ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)
) OR EXISTS (
SELECT 1 FROM rental_listings rl WHERE rl.id = c.listing_id AND rl.source_tenant_id = ?
))
AND (INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0)`,
args: []any{userID, key, encodedKey, basePrefix, encodedBasePrefix},
args: []any{userID, tenantID, tenantID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
},
{
sql: `SELECT COUNT(1) FROM user_payment_accounts p
@@ -129,11 +142,12 @@ func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string
return nil
}
records := make([]model.FileUploadOwner, 0, len(objectKeys))
tenantID := tenancy.IDFromContext(ctx)
for _, key := range objectKeys {
if key == "" {
continue
}
records = append(records, model.FileUploadOwner{UserID: userID, ObjectKey: key})
records = append(records, model.FileUploadOwner{TenantID: tenantID, UserID: userID, ObjectKey: key})
}
if len(records) == 0 {
return nil
@@ -6,6 +6,7 @@ import (
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -105,6 +106,30 @@ func TestRecordPrivateFileUpload(t *testing.T) {
}
}
func TestPrivateFileAuthorizerRejectsCrossTenantOwner(t *testing.T) {
db := openAuthorizerTestDB(t)
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
if err := db.Create(&model.FileUploadOwner{TenantID: 101, UserID: 11, ObjectKey: "listing/tenant-a.jpg"}).Error; err != nil {
t.Fatalf("create upload owner: %v", err)
}
authorize := privateFileAuthorizer(db)
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 202})
allowed, err := authorize(ctxA, 11, "listing/tenant-a.jpg")
if err != nil || !allowed {
t.Fatalf("same tenant allowed=%v err=%v", allowed, err)
}
allowed, err = authorize(ctxB, 11, "listing/tenant-a.jpg")
if err != nil {
t.Fatalf("cross tenant authorize error: %v", err)
}
if allowed {
t.Fatal("cross tenant upload owner must not be readable")
}
}
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
t.Helper()
db := database.NewTestDB()
+7 -1
View File
@@ -319,7 +319,13 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
var systemConfigRepo *systemconfig.Repository
if deps.DB != nil {
systemConfigRepo = systemconfig.NewRepository(deps.DB)
if err := systemConfigRepo.EnsureDefaults(context.Background()); err != nil && logger != nil {
configCtx := context.Background()
if tenantRepo != nil {
if scope, err := tenantRepo.ResolveCode(configCtx, "dachui"); err == nil && scope != nil {
configCtx = tenancy.WithScope(configCtx, *scope)
}
}
if err := systemConfigRepo.EnsureDefaults(configCtx); err != nil && logger != nil {
logger.Warn("系统配置默认值初始化失败,将在请求时按需重试", zap.Error(err))
}
}
@@ -0,0 +1,199 @@
-- +goose Up
-- 客服、通知、短信、文件和站点配置按经营租户隔离。
-- 历史数据优先按业务关系回填,无法推导的旧数据归大锤。
ALTER TABLE chat_conversations
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_chat_conversations_tenant_created (tenant_id, created_at);
UPDATE chat_conversations c
JOIN rental_orders o ON o.id = c.order_id
SET c.tenant_id = o.buyer_tenant_id
WHERE c.tenant_id = 0 AND o.buyer_tenant_id > 0;
UPDATE chat_conversations c
JOIN rental_listings l ON l.id = c.listing_id
SET c.tenant_id = l.source_tenant_id
WHERE c.tenant_id = 0 AND l.source_tenant_id > 0;
UPDATE chat_conversations
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE chat_qrcode_pool
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_chat_qrcode_pool_tenant_site_status (tenant_id, distribution_site_id, status);
UPDATE chat_qrcode_pool
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE chat_qrcode_delivery_tasks
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_chat_qrcode_delivery_tenant_status (tenant_id, status, created_at);
UPDATE chat_qrcode_delivery_tasks t
JOIN chat_conversations c ON c.id = t.conversation_id
SET t.tenant_id = c.tenant_id
WHERE t.tenant_id = 0;
UPDATE chat_qrcode_delivery_tasks
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE chat_support_groups
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
DROP KEY uk_chat_support_groups_code,
ADD UNIQUE KEY uk_chat_support_groups_tenant_code (tenant_id, code),
ADD KEY idx_chat_support_groups_tenant_status (tenant_id, status, sort_order);
UPDATE chat_support_groups
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
INSERT INTO chat_support_groups (tenant_id, code, name, description, status, sort_order)
SELECT t.id, src.code, src.name, src.description, src.status, src.sort_order
FROM tenants t
JOIN chat_support_groups src
ON src.tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE t.status = 'active'
AND t.id <> src.tenant_id
ON DUPLICATE KEY UPDATE
name = VALUES(name),
description = VALUES(description);
ALTER TABLE chat_quick_replies
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_chat_quick_replies_tenant_admin_sort (tenant_id, admin_user_id, sort_order);
UPDATE chat_quick_replies
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE notifications
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_notifications_tenant_user_read (tenant_id, user_id, read_at, id);
UPDATE notifications n
JOIN users u ON u.id = n.user_id
SET n.tenant_id = u.tenant_id
WHERE n.tenant_id = 0;
UPDATE notifications
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE admin_notifications
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_admin_notifications_tenant_user_read (tenant_id, admin_user_id, is_read, id);
UPDATE admin_notifications n
JOIN admin_user_roles aur ON aur.admin_user_id = n.admin_user_id AND aur.tenant_id > 0
SET n.tenant_id = aur.tenant_id
WHERE n.tenant_id = 0;
UPDATE admin_notifications
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE sms_messages
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
DROP KEY uk_sms_messages_node_biz_user,
ADD UNIQUE KEY uk_sms_messages_tenant_node_biz_user (tenant_id, node, biz_type, biz_id, user_id),
ADD KEY idx_sms_messages_tenant_status_id (tenant_id, status, id);
UPDATE sms_messages s
JOIN users u ON u.id = s.user_id
SET s.tenant_id = u.tenant_id
WHERE s.tenant_id = 0;
UPDATE sms_messages
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE file_upload_owners
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_file_upload_owners_tenant_user (tenant_id, user_id, object_key);
UPDATE file_upload_owners f
JOIN users u ON u.id = f.user_id
SET f.tenant_id = u.tenant_id
WHERE f.tenant_id = 0;
UPDATE file_upload_owners
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE announcements
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
ADD KEY idx_announcements_tenant_site (tenant_id, distribution_site_id, status, is_pinned, priority, published_at);
UPDATE announcements
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
ALTER TABLE system_configs
ADD COLUMN tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER id,
DROP KEY uk_system_configs_key,
ADD UNIQUE KEY uk_system_configs_tenant_key (tenant_id, `key`);
UPDATE system_configs
SET tenant_id = (SELECT id FROM tenants WHERE code = 'dachui' LIMIT 1)
WHERE tenant_id = 0;
-- +goose Down
ALTER TABLE system_configs
DROP KEY uk_system_configs_tenant_key,
ADD UNIQUE KEY uk_system_configs_key (`key`),
DROP COLUMN tenant_id;
ALTER TABLE announcements
DROP KEY idx_announcements_tenant_site,
DROP COLUMN tenant_id;
ALTER TABLE file_upload_owners
DROP KEY idx_file_upload_owners_tenant_user,
DROP COLUMN tenant_id;
ALTER TABLE sms_messages
DROP KEY idx_sms_messages_tenant_status_id,
DROP KEY uk_sms_messages_tenant_node_biz_user,
ADD UNIQUE KEY uk_sms_messages_node_biz_user (node, biz_type, biz_id, user_id),
DROP COLUMN tenant_id;
ALTER TABLE admin_notifications
DROP KEY idx_admin_notifications_tenant_user_read,
DROP COLUMN tenant_id;
ALTER TABLE notifications
DROP KEY idx_notifications_tenant_user_read,
DROP COLUMN tenant_id;
ALTER TABLE chat_quick_replies
DROP KEY idx_chat_quick_replies_tenant_admin_sort,
DROP COLUMN tenant_id;
DELETE dst
FROM chat_support_groups dst
JOIN tenants t ON t.id = dst.tenant_id
WHERE t.code <> 'dachui';
ALTER TABLE chat_support_groups
DROP KEY idx_chat_support_groups_tenant_status,
DROP KEY uk_chat_support_groups_tenant_code,
ADD UNIQUE KEY uk_chat_support_groups_code (code),
DROP COLUMN tenant_id;
ALTER TABLE chat_qrcode_delivery_tasks
DROP KEY idx_chat_qrcode_delivery_tenant_status,
DROP COLUMN tenant_id;
ALTER TABLE chat_qrcode_pool
DROP KEY idx_chat_qrcode_pool_tenant_site_status,
DROP COLUMN tenant_id;
ALTER TABLE chat_conversations
DROP KEY idx_chat_conversations_tenant_created,
DROP COLUMN tenant_id;
@@ -1,6 +1,6 @@
# 解忧商行双站点改造方案
> 状态:MVP 基调稿 v2.0
> 状态:阶段 1~6 已完成,准备进入迁移与灰度验证
> 更新时间:2026-11-15
> 目标:用一套后端、一套数据库和一套前端,上线大锤商行、解忧商行两个经营站点