feat(v2): LimitAware 真实用量源——DBUsageSource 快照 + 对账 job 周期聚合当日已收(替 NopUsage)
This commit is contained in:
@@ -126,3 +126,24 @@ func (s *OrderStore) ExpireStaleOrders(cutoff time.Time, limit int) (int64, erro
|
||||
}
|
||||
return res.RowsAffected, nil
|
||||
}
|
||||
|
||||
// SumPaidAttemptMinorByAccountSince 聚合各账户自 since 起的已付金额(minor),供 LimitAware
|
||||
// 判当日用量。量纲:attempt.AmountMinor 即账户所属渠道结算币种 minor(与 DailyLimit 同量纲)。
|
||||
func (s *OrderStore) SumPaidAttemptMinorByAccountSince(since time.Time) (map[string]int64, error) {
|
||||
type row struct {
|
||||
AccountID string
|
||||
Total int64
|
||||
}
|
||||
var rows []row
|
||||
if err := s.db.Model(&model.Attempt{}).
|
||||
Select("account_id, SUM(amount_minor) AS total").
|
||||
Where("status = ? AND account_id <> '' AND paid_at >= ?", model.AttemptPaid, since).
|
||||
Group("account_id").Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("store.SumPaidAttemptMinorByAccountSince: %w", err)
|
||||
}
|
||||
out := make(map[string]int64, len(rows))
|
||||
for _, r := range rows {
|
||||
out[r.AccountID] = r.Total
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -94,3 +94,32 @@ func TestExpireStaleOrders(t *testing.T) {
|
||||
t.Fatalf("重跑应 0, got %d", n2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSumPaidAttemptMinorByAccountSince(t *testing.T) {
|
||||
db := model.OpenTestDB(t)
|
||||
s := store.NewOrderStore(db)
|
||||
now := time.Date(2026, 7, 10, 12, 0, 0, 0, time.UTC)
|
||||
dayStart := time.Date(2026, 7, 10, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
mk := func(no, acct string, minor int64, st model.AttemptStatus, paidAgo time.Duration) {
|
||||
paid := now.Add(-paidAgo)
|
||||
a := &model.Attempt{OutTradeNo: no, Channel: "alipay", AccountID: acct, ProviderRef: "R-" + no,
|
||||
AmountMinor: minor, Currency: "CNY", Status: st, PaidAt: &paid}
|
||||
if err := s.CreateAttempt(a); err != nil {
|
||||
t.Fatalf("attempt %s: %v", no, err)
|
||||
}
|
||||
}
|
||||
mk("A", "acct-1", 10000, model.AttemptPaid, 1*time.Hour) // 今日,计入
|
||||
mk("B", "acct-1", 5000, model.AttemptPaid, 2*time.Hour) // 今日,计入 → acct-1=15000
|
||||
mk("C", "acct-2", 7000, model.AttemptPaid, 30*time.Minute) // 今日 acct-2=7000
|
||||
mk("D", "acct-1", 9999, model.AttemptPending, 10*time.Minute) // 未付,不计
|
||||
mk("E", "acct-1", 8888, model.AttemptPaid, 20*time.Hour) // 昨天(paid_at < dayStart),不计
|
||||
|
||||
got, err := s.SumPaidAttemptMinorByAccountSince(dayStart)
|
||||
if err != nil {
|
||||
t.Fatalf("sum: %v", err)
|
||||
}
|
||||
if got["acct-1"] != 15000 || got["acct-2"] != 7000 {
|
||||
t.Fatalf("聚合 = %+v, want acct-1=15000 acct-2=7000", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user