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),