--- a/model/subscription.go +++ b/model/subscription.go @@ -10,6 +10,7 @@ "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/pkg/cachex" + "github.com/QuantumNous/new-api/setting/operation_setting" "github.com/samber/hot" "github.com/shopspring/decimal" "gorm.io/gorm" @@ -754,21 +755,30 @@ return nil, nil } -func calcSubscriptionBalanceQuota(priceAmount float64) (int, error) { +func SubscriptionBalanceQuota(priceAmount float64) (int, error) { if priceAmount <= 0 { return 0, nil } if common.QuotaPerUnit <= 0 { return 0, common.NewMessage("Quota unit is misconfigured") } - quota := decimal.NewFromFloat(priceAmount). - Mul(decimal.NewFromFloat(common.QuotaPerUnit)). - Ceil() - return common.WalletQuotaFromDecimalStrict(quota) + quota := decimal.NewFromFloat(priceAmount).Mul(decimal.NewFromFloat(common.QuotaPerUnit)) + if operation_setting.GetQuotaDisplayType() == operation_setting.QuotaDisplayTypeCNY { + // MaltAI sells these plans in CNY. Price is the CNY face value of one wallet unit. + if operation_setting.Price <= 0 { + return 0, common.NewMessage("Quota unit is misconfigured") + } + whole, remainder := quota.QuoRem(decimal.NewFromFloat(operation_setting.Price), 0) + if remainder.IsPositive() { + whole = whole.Add(decimal.NewFromInt(1)) + } + quota = whole + } + return common.WalletQuotaFromDecimalStrict(quota.Ceil()) } // PurchaseSubscriptionWithBalance creates a subscription by deducting the user's wallet quota. -func PurchaseSubscriptionWithBalance(userId int, planId int) error { +func PurchaseSubscriptionWithBalance(userId int, planId int, expectedQuota *int) error { if userId <= 0 || planId <= 0 { return errors.New("invalid userId or planId") } @@ -792,9 +802,12 @@ return common.NewMessage("This plan does not allow balance redemption") } - requiredQuota, err := calcSubscriptionBalanceQuota(plan.PriceAmount) + requiredQuota, err := SubscriptionBalanceQuota(plan.PriceAmount) if err != nil { return err + } + if expectedQuota != nil && *expectedQuota != requiredQuota { + return common.NewMessage("Subscription balance quote has changed") } var user User --- a/controller/subscription.go +++ b/controller/subscription.go @@ -15,7 +15,8 @@ // ---- Shared types ---- type SubscriptionPlanDTO struct { - Plan model.SubscriptionPlan `json:"plan"` + Plan model.SubscriptionPlan `json:"plan"` + BalanceQuota *int `json:"balance_quota,omitempty"` } type BillingPreferenceRequest struct { @@ -23,7 +24,8 @@ } type SubscriptionBalancePayRequest struct { - PlanId int `json:"plan_id"` + PlanId int `json:"plan_id"` + ExpectedBalanceQuota *int `json:"expected_balance_quota"` } // ---- User APIs ---- @@ -42,9 +44,12 @@ result := make([]SubscriptionPlanDTO, 0, len(plans)) for _, p := range plans { p.NormalizeDefaults() - result = append(result, SubscriptionPlanDTO{ - Plan: p, - }) + quota, err := model.SubscriptionBalanceQuota(p.PriceAmount) + if err != nil { + common.ApiError(c, err) + return + } + result = append(result, SubscriptionPlanDTO{Plan: p, BalanceQuota: "a}) } common.ApiSuccess(c, result) } @@ -108,7 +113,7 @@ return } - if err := model.PurchaseSubscriptionWithBalance(userId, req.PlanId); err != nil { + if err := model.PurchaseSubscriptionWithBalance(userId, req.PlanId, req.ExpectedBalanceQuota); err != nil { common.ApiError(c, err) return } --- a/service/billing_session.go +++ b/service/billing_session.go @@ -84,6 +84,44 @@ return tokenErr } +// reserveSubscriptionCharge extends the hold up to the measured text usage. +// Each reservation checks both the subscription and the personal key. When the +// final output exceeds the remaining balance, charge only units we actually hold. +func (s *BillingSession) reserveSubscriptionCharge(actual int) int { + held := s.GetPreConsumedQuota() + if actual <= held || s.ReserveBeforeSubmit(actual) == nil { + return actual + } + // The full increase did not fit. Read current headroom and still enforce it + // atomically when reserving, since other requests can settle concurrently. + subs, err := model.GetAllActiveUserSubscriptions(s.relayInfo.UserId) + if err != nil { + return held + } + for _, item := range subs { + sub := item.Subscription + if sub == nil || sub.Id != s.relayInfo.SubscriptionId { + continue + } + delta := int64(actual - held) + if sub.AmountTotal > 0 { + delta = min(delta, sub.AmountTotal-sub.AmountUsed) + } + if !s.relayInfo.IsPlayground && !s.relayInfo.TokenUnlimited { + key, err := model.GetTokenByIds(s.relayInfo.TokenId, s.relayInfo.UserId) + if err != nil { + return held + } + delta = min(delta, int64(key.RemainQuota)) + } + if delta > 0 && s.ReserveBeforeSubmit(held+int(delta)) == nil { + return held + int(delta) + } + break + } + return held +} + // Refund 退还所有预扣费,幂等安全,异步执行。 func (s *BillingSession) Refund(c *gin.Context) { s.mu.Lock() --- a/service/text_quota.go +++ b/service/text_quota.go @@ -458,13 +458,20 @@ if !summary.hasBillableUsage() { extraContent = append(extraContent, common.NewMessage("Upstream returned no usage, so nothing was charged (possibly an upstream timeout)")) logger.LogError(ctx, common.LogText("total tokens is 0, cannot consume quota, userId %d, channelId %d, tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, summary.ModelName, relayInfo.FinalPreConsumedQuota)) - } else { - model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, summary.Quota) - model.UpdateChannelUsedQuota(relayInfo.ChannelId, summary.Quota) - } - + } + meteredQuota := summary.Quota + if session, ok := relayInfo.Billing.(*BillingSession); ok && relayInfo.BillingSource == BillingSourceSubscription { + summary.Quota = session.reserveSubscriptionCharge(meteredQuota) + } if err := SettleBilling(ctx, relayInfo, summary.Quota); err != nil { logger.LogError(ctx, common.LogText("error settling billing: %s", err.Error())) + if relayInfo.BillingSource == BillingSourceSubscription { + summary.Quota = int(relayInfo.SubscriptionPreConsumed + relayInfo.SubscriptionPostDelta) + } + } + if summary.hasBillableUsage() { + model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, summary.Quota) + model.UpdateChannelUsedQuota(relayInfo.ChannelId, meteredQuota) } logModel := summary.ModelName @@ -489,6 +496,10 @@ other.SetPublic("usage_semantic", "anthropic") } else { other = GenerateTextOtherInfo(ctx, relayInfo, summary.ModelRatio, summary.GroupRatio, summary.CompletionRatio, summary.CacheTokens, summary.CacheRatio, summary.ModelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio) + } + if meteredQuota != summary.Quota { + other.SetAdmin("metered_quota", meteredQuota) + other.SetAdmin("uncollected_quota", meteredQuota-summary.Quota) } appendUsageBillingPathForLog(other, common.GetContextKeyBool(ctx, constant.ContextKeyLocalCountTokens), originUsage) if adminRejectReason != "" { --- a/model/subscription.go +++ b/model/subscription.go @@ -1434,7 +1434,7 @@ record.Status = "refunded" return tx.Save(&record).Error } - if err := PostConsumeUserSubscriptionDelta(record.UserSubscriptionId, -record.PreConsumed); err != nil { + if err := postConsumeUserSubscriptionDeltaTx(tx, record.UserSubscriptionId, -record.PreConsumed); err != nil { return err } record.Status = "refunded" @@ -1533,17 +1533,21 @@ return nil } return DB.Transaction(func(tx *gorm.DB) error { - var sub UserSubscription - if err := lockForUpdate(tx). - Where("id = ?", userSubscriptionId). - First(&sub).Error; err != nil { - return err - } - newUsed := max(sub.AmountUsed+delta, 0) - if sub.AmountTotal > 0 && newUsed > sub.AmountTotal { - return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal) - } - sub.AmountUsed = newUsed - return tx.Save(&sub).Error + return postConsumeUserSubscriptionDeltaTx(tx, userSubscriptionId, delta) }) } + +func postConsumeUserSubscriptionDeltaTx(tx *gorm.DB, userSubscriptionId int, delta int64) error { + var sub UserSubscription + if err := lockForUpdate(tx). + Where("id = ?", userSubscriptionId). + First(&sub).Error; err != nil { + return err + } + newUsed := max(sub.AmountUsed+delta, 0) + if sub.AmountTotal > 0 && newUsed > sub.AmountTotal { + return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal) + } + sub.AmountUsed = newUsed + return tx.Save(&sub).Error +} --- a/controller/usedata.go +++ b/controller/usedata.go @@ -69,6 +69,19 @@ common.ApiError(c, err) return } + if c.Query("aggregation") == "settled_day" { + if endTimestamp <= 0 || startTimestamp > endTimestamp { + common.ApiErrorMsg(c, "invalid settlement time range") + return + } + days, err := model.GetSettledQuotaDays(c.Request.Context(), userId, startTimestamp, endTimestamp) + if err != nil { + common.ApiError(c, err) + return + } + common.ApiSuccess(c, days) + return + } dates, err := model.GetQuotaDataByUserId(userId, startTimestamp, endTimestamp) if err != nil { common.ApiError(c, err) --- a/model/usedata.go +++ b/model/usedata.go @@ -1,6 +1,7 @@ package model import ( + "context" "fmt" "sync" "time" @@ -159,6 +160,23 @@ return quotaDatas, err } +type SettledQuotaDay struct { + CreatedAt int64 `json:"created_at"` + Quota int64 `json:"quota"` +} + +// Group the account's settled statement entries by UTC day, including recent +// charges that have not been flushed to the dashboard's reporting cache. +func GetSettledQuotaDays(ctx context.Context, userID int, startTime, endTime int64) ([]SettledQuotaDay, error) { + const day = "created_at - (created_at % 86400)" + rows := make([]SettledQuotaDay, 0) + err := LOG_DB.WithContext(ctx).Model(&Log{}). + Select(day + " AS created_at, SUM(quota) AS quota"). + Where("user_id = ? AND type = ? AND created_at >= ? AND created_at <= ?", userID, LogTypeConsume, startTime, endTime). + Group(day).Scan(&rows).Error + return rows, err +} + func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error) { var quotaDatas []*QuotaData // 从quota_data表中查询数据