修复超额流量不记录的问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 8m18s

This commit is contained in:
Break
2026-05-28 15:19:54 +08:00
parent 58863e8ec5
commit 1550ef3cb1

View File

@@ -65,7 +65,8 @@ func (s *UsageService) SetStopResumeCallback(callback StopResumeCallback) {
// DeductDataUsage 任务 10.2-10.6: 按优先级扣减流量
// 扣减顺序:加油包(按 priority ASC → 主套餐
// 流量用完时自动标记 status=2所有套餐用完时触发停机
// 真实用量允许超过套餐阈值,超额部分记入最后一个生效套餐,用于后续虚流量阈值评估。
// 流量用完时自动标记 status=2所有套餐用完时触发停机。
func (s *UsageService) DeductDataUsage(ctx context.Context, carrierType string, carrierID uint, usageMB float64) error {
if usageMB <= 0 {
return errors.New(errors.CodeInvalidParam, "扣减流量必须大于0")
@@ -94,7 +95,7 @@ func (s *UsageService) DeductDataUsage(ctx context.Context, carrierType string,
remainingUsage := deductUsageMB
today := time.Now().Format("2006-01-02")
for _, pkg := range packages {
for index, pkg := range packages {
if remainingUsage <= 0 {
break
}
@@ -102,7 +103,8 @@ func (s *UsageService) DeductDataUsage(ctx context.Context, carrierType string,
// 计算当前套餐剩余额度
effectiveThresholdMB := pkg.EffectiveThresholdMB()
remainingQuota := pkg.RemainingQuotaMB()
if remainingQuota <= 0 {
isLastPackage := index == len(packages)-1
if remainingQuota <= 0 && !isLastPackage {
// 套餐已用完,标记为已用完
if err := tx.Model(pkg).Update("status", constants.PackageUsageStatusDepleted).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "更新套餐状态失败")
@@ -112,11 +114,19 @@ func (s *UsageService) DeductDataUsage(ctx context.Context, carrierType string,
// 本次从该套餐扣减的流量
var deductFromPkg int64
if remainingUsage <= remainingQuota {
if isLastPackage {
deductFromPkg = remainingUsage
} else if remainingUsage <= remainingQuota {
deductFromPkg = remainingUsage
} else {
deductFromPkg = remainingQuota
}
if deductFromPkg <= 0 {
if err := tx.Model(pkg).Update("status", constants.PackageUsageStatusDepleted).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "更新套餐状态失败")
}
continue
}
// 更新套餐使用量
newUsage := pkg.DataUsageMB + deductFromPkg
@@ -145,17 +155,9 @@ func (s *UsageService) DeductDataUsage(ctx context.Context, carrierType string,
zap.Int64("deduct_mb", deductFromPkg),
zap.Int64("new_usage_mb", newUsage),
zap.Int64("effective_threshold_mb", effectiveThresholdMB),
zap.Int64("data_limit_mb", pkg.DataLimitMB))
}
// 如果流量扣减未完成,说明所有套餐都不够
if remainingUsage > 0 {
s.logger.Warn("流量不足",
zap.String("carrier_type", targetCarrierType),
zap.Uint("carrier_id", targetCarrierID),
zap.Int64("requested_mb", deductUsageMB),
zap.Int64("remaining_mb", remainingUsage))
return errors.New(errors.CodeInsufficientQuota, "流量不足")
zap.Int64("data_limit_mb", pkg.DataLimitMB),
zap.Int64("remaining_quota_mb", remainingQuota),
zap.Bool("over_threshold", effectiveThresholdMB > 0 && newUsage > effectiveThresholdMB))
}
// 任务 10.5: 检查是否所有套餐都用完(触发停机)