subscription.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/pkg/cachex"
  11. "github.com/samber/hot"
  12. "gorm.io/gorm"
  13. )
  14. // Subscription duration units
  15. const (
  16. SubscriptionDurationYear = "year"
  17. SubscriptionDurationMonth = "month"
  18. SubscriptionDurationDay = "day"
  19. SubscriptionDurationHour = "hour"
  20. SubscriptionDurationCustom = "custom"
  21. )
  22. // Subscription quota reset period
  23. const (
  24. SubscriptionResetNever = "never"
  25. SubscriptionResetDaily = "daily"
  26. SubscriptionResetWeekly = "weekly"
  27. SubscriptionResetMonthly = "monthly"
  28. SubscriptionResetCustom = "custom"
  29. )
  30. var (
  31. ErrSubscriptionOrderNotFound = errors.New("subscription order not found")
  32. ErrSubscriptionOrderStatusInvalid = errors.New("subscription order status invalid")
  33. )
  34. const (
  35. subscriptionPlanCacheNamespace = "new-api:subscription_plan:v1"
  36. subscriptionPlanInfoCacheNamespace = "new-api:subscription_plan_info:v1"
  37. )
  38. var (
  39. subscriptionPlanCacheOnce sync.Once
  40. subscriptionPlanInfoCacheOnce sync.Once
  41. subscriptionPlanCache *cachex.HybridCache[SubscriptionPlan]
  42. subscriptionPlanInfoCache *cachex.HybridCache[SubscriptionPlanInfo]
  43. )
  44. func subscriptionPlanCacheTTL() time.Duration {
  45. ttlSeconds := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_CACHE_TTL", 300)
  46. if ttlSeconds <= 0 {
  47. ttlSeconds = 300
  48. }
  49. return time.Duration(ttlSeconds) * time.Second
  50. }
  51. func subscriptionPlanInfoCacheTTL() time.Duration {
  52. ttlSeconds := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_INFO_CACHE_TTL", 120)
  53. if ttlSeconds <= 0 {
  54. ttlSeconds = 120
  55. }
  56. return time.Duration(ttlSeconds) * time.Second
  57. }
  58. func subscriptionPlanCacheCapacity() int {
  59. capacity := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_CACHE_CAP", 5000)
  60. if capacity <= 0 {
  61. capacity = 5000
  62. }
  63. return capacity
  64. }
  65. func subscriptionPlanInfoCacheCapacity() int {
  66. capacity := common.GetEnvOrDefault("SUBSCRIPTION_PLAN_INFO_CACHE_CAP", 10000)
  67. if capacity <= 0 {
  68. capacity = 10000
  69. }
  70. return capacity
  71. }
  72. func getSubscriptionPlanCache() *cachex.HybridCache[SubscriptionPlan] {
  73. subscriptionPlanCacheOnce.Do(func() {
  74. ttl := subscriptionPlanCacheTTL()
  75. subscriptionPlanCache = cachex.NewHybridCache[SubscriptionPlan](cachex.HybridCacheConfig[SubscriptionPlan]{
  76. Namespace: cachex.Namespace(subscriptionPlanCacheNamespace),
  77. Redis: common.RDB,
  78. RedisEnabled: func() bool {
  79. return common.RedisEnabled && common.RDB != nil
  80. },
  81. RedisCodec: cachex.JSONCodec[SubscriptionPlan]{},
  82. Memory: func() *hot.HotCache[string, SubscriptionPlan] {
  83. return hot.NewHotCache[string, SubscriptionPlan](hot.LRU, subscriptionPlanCacheCapacity()).
  84. WithTTL(ttl).
  85. WithJanitor().
  86. Build()
  87. },
  88. })
  89. })
  90. return subscriptionPlanCache
  91. }
  92. func getSubscriptionPlanInfoCache() *cachex.HybridCache[SubscriptionPlanInfo] {
  93. subscriptionPlanInfoCacheOnce.Do(func() {
  94. ttl := subscriptionPlanInfoCacheTTL()
  95. subscriptionPlanInfoCache = cachex.NewHybridCache[SubscriptionPlanInfo](cachex.HybridCacheConfig[SubscriptionPlanInfo]{
  96. Namespace: cachex.Namespace(subscriptionPlanInfoCacheNamespace),
  97. Redis: common.RDB,
  98. RedisEnabled: func() bool {
  99. return common.RedisEnabled && common.RDB != nil
  100. },
  101. RedisCodec: cachex.JSONCodec[SubscriptionPlanInfo]{},
  102. Memory: func() *hot.HotCache[string, SubscriptionPlanInfo] {
  103. return hot.NewHotCache[string, SubscriptionPlanInfo](hot.LRU, subscriptionPlanInfoCacheCapacity()).
  104. WithTTL(ttl).
  105. WithJanitor().
  106. Build()
  107. },
  108. })
  109. })
  110. return subscriptionPlanInfoCache
  111. }
  112. func subscriptionPlanCacheKey(id int) string {
  113. if id <= 0 {
  114. return ""
  115. }
  116. return strconv.Itoa(id)
  117. }
  118. func InvalidateSubscriptionPlanCache(planId int) {
  119. if planId <= 0 {
  120. return
  121. }
  122. cache := getSubscriptionPlanCache()
  123. _, _ = cache.DeleteMany([]string{subscriptionPlanCacheKey(planId)})
  124. infoCache := getSubscriptionPlanInfoCache()
  125. _ = infoCache.Purge()
  126. }
  127. // Subscription plan
  128. type SubscriptionPlan struct {
  129. Id int `json:"id"`
  130. Title string `json:"title" gorm:"type:varchar(128);not null"`
  131. Subtitle string `json:"subtitle" gorm:"type:varchar(255);default:''"`
  132. // Display money amount (follow existing code style: float64 for money)
  133. PriceAmount float64 `json:"price_amount" gorm:"type:decimal(10,6);not null;default:0"`
  134. Currency string `json:"currency" gorm:"type:varchar(8);not null;default:'USD'"`
  135. DurationUnit string `json:"duration_unit" gorm:"type:varchar(16);not null;default:'month'"`
  136. DurationValue int `json:"duration_value" gorm:"type:int;not null;default:1"`
  137. CustomSeconds int64 `json:"custom_seconds" gorm:"type:bigint;not null;default:0"`
  138. Enabled bool `json:"enabled" gorm:"default:true"`
  139. SortOrder int `json:"sort_order" gorm:"type:int;default:0"`
  140. StripePriceId string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"`
  141. CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"`
  142. // Max purchases per user (0 = unlimited)
  143. MaxPurchasePerUser int `json:"max_purchase_per_user" gorm:"type:int;default:0"`
  144. // Upgrade user group after purchase (empty = no change)
  145. UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
  146. // Total quota (amount in quota units, 0 = unlimited)
  147. TotalAmount int64 `json:"total_amount" gorm:"type:bigint;not null;default:0"`
  148. // Quota reset period for plan
  149. QuotaResetPeriod string `json:"quota_reset_period" gorm:"type:varchar(16);default:'never'"`
  150. QuotaResetCustomSeconds int64 `json:"quota_reset_custom_seconds" gorm:"type:bigint;default:0"`
  151. CreatedAt int64 `json:"created_at" gorm:"bigint"`
  152. UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
  153. }
  154. func (p *SubscriptionPlan) BeforeCreate(tx *gorm.DB) error {
  155. now := common.GetTimestamp()
  156. p.CreatedAt = now
  157. p.UpdatedAt = now
  158. return nil
  159. }
  160. func (p *SubscriptionPlan) BeforeUpdate(tx *gorm.DB) error {
  161. p.UpdatedAt = common.GetTimestamp()
  162. return nil
  163. }
  164. // Subscription order (payment -> webhook -> create UserSubscription)
  165. type SubscriptionOrder struct {
  166. Id int `json:"id"`
  167. UserId int `json:"user_id" gorm:"index"`
  168. PlanId int `json:"plan_id" gorm:"index"`
  169. Money float64 `json:"money"`
  170. TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
  171. PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
  172. Status string `json:"status"`
  173. CreateTime int64 `json:"create_time"`
  174. CompleteTime int64 `json:"complete_time"`
  175. ProviderPayload string `json:"provider_payload" gorm:"type:text"`
  176. }
  177. func (o *SubscriptionOrder) Insert() error {
  178. if o.CreateTime == 0 {
  179. o.CreateTime = common.GetTimestamp()
  180. }
  181. return DB.Create(o).Error
  182. }
  183. func (o *SubscriptionOrder) Update() error {
  184. return DB.Save(o).Error
  185. }
  186. func GetSubscriptionOrderByTradeNo(tradeNo string) *SubscriptionOrder {
  187. if tradeNo == "" {
  188. return nil
  189. }
  190. var order SubscriptionOrder
  191. if err := DB.Where("trade_no = ?", tradeNo).First(&order).Error; err != nil {
  192. return nil
  193. }
  194. return &order
  195. }
  196. // User subscription instance
  197. type UserSubscription struct {
  198. Id int `json:"id"`
  199. UserId int `json:"user_id" gorm:"index;index:idx_user_sub_active,priority:1"`
  200. PlanId int `json:"plan_id" gorm:"index"`
  201. AmountTotal int64 `json:"amount_total" gorm:"type:bigint;not null;default:0"`
  202. AmountUsed int64 `json:"amount_used" gorm:"type:bigint;not null;default:0"`
  203. StartTime int64 `json:"start_time" gorm:"bigint"`
  204. EndTime int64 `json:"end_time" gorm:"bigint;index;index:idx_user_sub_active,priority:3"`
  205. Status string `json:"status" gorm:"type:varchar(32);index;index:idx_user_sub_active,priority:2"` // active/expired/cancelled
  206. Source string `json:"source" gorm:"type:varchar(32);default:'order'"` // order/admin
  207. LastResetTime int64 `json:"last_reset_time" gorm:"type:bigint;default:0"`
  208. NextResetTime int64 `json:"next_reset_time" gorm:"type:bigint;default:0;index"`
  209. UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
  210. PrevUserGroup string `json:"prev_user_group" gorm:"type:varchar(64);default:''"`
  211. CreatedAt int64 `json:"created_at" gorm:"bigint"`
  212. UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
  213. }
  214. func (s *UserSubscription) BeforeCreate(tx *gorm.DB) error {
  215. now := common.GetTimestamp()
  216. s.CreatedAt = now
  217. s.UpdatedAt = now
  218. return nil
  219. }
  220. func (s *UserSubscription) BeforeUpdate(tx *gorm.DB) error {
  221. s.UpdatedAt = common.GetTimestamp()
  222. return nil
  223. }
  224. type SubscriptionSummary struct {
  225. Subscription *UserSubscription `json:"subscription"`
  226. }
  227. func calcPlanEndTime(start time.Time, plan *SubscriptionPlan) (int64, error) {
  228. if plan == nil {
  229. return 0, errors.New("plan is nil")
  230. }
  231. if plan.DurationValue <= 0 && plan.DurationUnit != SubscriptionDurationCustom {
  232. return 0, errors.New("duration_value must be > 0")
  233. }
  234. switch plan.DurationUnit {
  235. case SubscriptionDurationYear:
  236. return start.AddDate(plan.DurationValue, 0, 0).Unix(), nil
  237. case SubscriptionDurationMonth:
  238. return start.AddDate(0, plan.DurationValue, 0).Unix(), nil
  239. case SubscriptionDurationDay:
  240. return start.Add(time.Duration(plan.DurationValue) * 24 * time.Hour).Unix(), nil
  241. case SubscriptionDurationHour:
  242. return start.Add(time.Duration(plan.DurationValue) * time.Hour).Unix(), nil
  243. case SubscriptionDurationCustom:
  244. if plan.CustomSeconds <= 0 {
  245. return 0, errors.New("custom_seconds must be > 0")
  246. }
  247. return start.Add(time.Duration(plan.CustomSeconds) * time.Second).Unix(), nil
  248. default:
  249. return 0, fmt.Errorf("invalid duration_unit: %s", plan.DurationUnit)
  250. }
  251. }
  252. func NormalizeResetPeriod(period string) string {
  253. switch strings.TrimSpace(period) {
  254. case SubscriptionResetDaily, SubscriptionResetWeekly, SubscriptionResetMonthly, SubscriptionResetCustom:
  255. return strings.TrimSpace(period)
  256. default:
  257. return SubscriptionResetNever
  258. }
  259. }
  260. func calcNextResetTime(base time.Time, plan *SubscriptionPlan, endUnix int64) int64 {
  261. if plan == nil {
  262. return 0
  263. }
  264. period := NormalizeResetPeriod(plan.QuotaResetPeriod)
  265. if period == SubscriptionResetNever {
  266. return 0
  267. }
  268. var next time.Time
  269. switch period {
  270. case SubscriptionResetDaily:
  271. next = time.Date(base.Year(), base.Month(), base.Day(), 0, 0, 0, 0, base.Location()).
  272. AddDate(0, 0, 1)
  273. case SubscriptionResetWeekly:
  274. // Align to next Monday 00:00
  275. weekday := int(base.Weekday()) // Sunday=0
  276. // Convert to Monday=1..Sunday=7
  277. if weekday == 0 {
  278. weekday = 7
  279. }
  280. daysUntil := 8 - weekday
  281. next = time.Date(base.Year(), base.Month(), base.Day(), 0, 0, 0, 0, base.Location()).
  282. AddDate(0, 0, daysUntil)
  283. case SubscriptionResetMonthly:
  284. // Align to first day of next month 00:00
  285. next = time.Date(base.Year(), base.Month(), 1, 0, 0, 0, 0, base.Location()).
  286. AddDate(0, 1, 0)
  287. case SubscriptionResetCustom:
  288. if plan.QuotaResetCustomSeconds <= 0 {
  289. return 0
  290. }
  291. next = base.Add(time.Duration(plan.QuotaResetCustomSeconds) * time.Second)
  292. default:
  293. return 0
  294. }
  295. if endUnix > 0 && next.Unix() > endUnix {
  296. return 0
  297. }
  298. return next.Unix()
  299. }
  300. func GetSubscriptionPlanById(id int) (*SubscriptionPlan, error) {
  301. return getSubscriptionPlanByIdTx(nil, id)
  302. }
  303. func getSubscriptionPlanByIdTx(tx *gorm.DB, id int) (*SubscriptionPlan, error) {
  304. if id <= 0 {
  305. return nil, errors.New("invalid plan id")
  306. }
  307. key := subscriptionPlanCacheKey(id)
  308. if key != "" {
  309. if cached, found, err := getSubscriptionPlanCache().Get(key); err == nil && found {
  310. return &cached, nil
  311. }
  312. }
  313. var plan SubscriptionPlan
  314. query := DB
  315. if tx != nil {
  316. query = tx
  317. }
  318. if err := query.Where("id = ?", id).First(&plan).Error; err != nil {
  319. return nil, err
  320. }
  321. _ = getSubscriptionPlanCache().SetWithTTL(key, plan, subscriptionPlanCacheTTL())
  322. return &plan, nil
  323. }
  324. func CountUserSubscriptionsByPlan(userId int, planId int) (int64, error) {
  325. if userId <= 0 || planId <= 0 {
  326. return 0, errors.New("invalid userId or planId")
  327. }
  328. var count int64
  329. if err := DB.Model(&UserSubscription{}).
  330. Where("user_id = ? AND plan_id = ?", userId, planId).
  331. Count(&count).Error; err != nil {
  332. return 0, err
  333. }
  334. return count, nil
  335. }
  336. func getUserGroupByIdTx(tx *gorm.DB, userId int) (string, error) {
  337. if userId <= 0 {
  338. return "", errors.New("invalid userId")
  339. }
  340. if tx == nil {
  341. tx = DB
  342. }
  343. var group string
  344. if err := tx.Model(&User{}).Where("id = ?", userId).Select(commonGroupCol).Find(&group).Error; err != nil {
  345. return "", err
  346. }
  347. return group, nil
  348. }
  349. func downgradeUserGroupForSubscriptionTx(tx *gorm.DB, sub *UserSubscription, now int64) (string, error) {
  350. if tx == nil || sub == nil {
  351. return "", errors.New("invalid downgrade args")
  352. }
  353. upgradeGroup := strings.TrimSpace(sub.UpgradeGroup)
  354. if upgradeGroup == "" {
  355. return "", nil
  356. }
  357. currentGroup, err := getUserGroupByIdTx(tx, sub.UserId)
  358. if err != nil {
  359. return "", err
  360. }
  361. if currentGroup != upgradeGroup {
  362. return "", nil
  363. }
  364. var activeSub UserSubscription
  365. activeQuery := tx.Where("user_id = ? AND status = ? AND end_time > ? AND id <> ? AND upgrade_group <> ''",
  366. sub.UserId, "active", now, sub.Id).
  367. Order("end_time desc, id desc").
  368. Limit(1).
  369. Find(&activeSub)
  370. if activeQuery.Error == nil && activeQuery.RowsAffected > 0 {
  371. return "", nil
  372. }
  373. prevGroup := strings.TrimSpace(sub.PrevUserGroup)
  374. if prevGroup == "" || prevGroup == currentGroup {
  375. return "", nil
  376. }
  377. if err := tx.Model(&User{}).Where("id = ?", sub.UserId).
  378. Update("group", prevGroup).Error; err != nil {
  379. return "", err
  380. }
  381. return prevGroup, nil
  382. }
  383. func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *SubscriptionPlan, source string) (*UserSubscription, error) {
  384. if tx == nil {
  385. return nil, errors.New("tx is nil")
  386. }
  387. if plan == nil || plan.Id == 0 {
  388. return nil, errors.New("invalid plan")
  389. }
  390. if userId <= 0 {
  391. return nil, errors.New("invalid user id")
  392. }
  393. if plan.MaxPurchasePerUser > 0 {
  394. var count int64
  395. if err := tx.Model(&UserSubscription{}).
  396. Where("user_id = ? AND plan_id = ?", userId, plan.Id).
  397. Count(&count).Error; err != nil {
  398. return nil, err
  399. }
  400. if count >= int64(plan.MaxPurchasePerUser) {
  401. return nil, errors.New("已达到该套餐购买上限")
  402. }
  403. }
  404. nowUnix := GetDBTimestamp()
  405. now := time.Unix(nowUnix, 0)
  406. endUnix, err := calcPlanEndTime(now, plan)
  407. if err != nil {
  408. return nil, err
  409. }
  410. resetBase := now
  411. nextReset := calcNextResetTime(resetBase, plan, endUnix)
  412. lastReset := int64(0)
  413. if nextReset > 0 {
  414. lastReset = now.Unix()
  415. }
  416. upgradeGroup := strings.TrimSpace(plan.UpgradeGroup)
  417. prevGroup := ""
  418. if upgradeGroup != "" {
  419. currentGroup, err := getUserGroupByIdTx(tx, userId)
  420. if err != nil {
  421. return nil, err
  422. }
  423. if currentGroup != upgradeGroup {
  424. prevGroup = currentGroup
  425. if err := tx.Model(&User{}).Where("id = ?", userId).
  426. Update("group", upgradeGroup).Error; err != nil {
  427. return nil, err
  428. }
  429. }
  430. }
  431. sub := &UserSubscription{
  432. UserId: userId,
  433. PlanId: plan.Id,
  434. AmountTotal: plan.TotalAmount,
  435. AmountUsed: 0,
  436. StartTime: now.Unix(),
  437. EndTime: endUnix,
  438. Status: "active",
  439. Source: source,
  440. LastResetTime: lastReset,
  441. NextResetTime: nextReset,
  442. UpgradeGroup: upgradeGroup,
  443. PrevUserGroup: prevGroup,
  444. CreatedAt: common.GetTimestamp(),
  445. UpdatedAt: common.GetTimestamp(),
  446. }
  447. if err := tx.Create(sub).Error; err != nil {
  448. return nil, err
  449. }
  450. return sub, nil
  451. }
  452. // Complete a subscription order (idempotent). Creates a UserSubscription snapshot from the plan.
  453. func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentMethod string) error {
  454. if tradeNo == "" {
  455. return errors.New("tradeNo is empty")
  456. }
  457. refCol := "`trade_no`"
  458. if common.UsingPostgreSQL {
  459. refCol = `"trade_no"`
  460. }
  461. var logUserId int
  462. var logPlanTitle string
  463. var logMoney float64
  464. var logPaymentMethod string
  465. var upgradeGroup string
  466. err := DB.Transaction(func(tx *gorm.DB) error {
  467. var order SubscriptionOrder
  468. if err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(&order).Error; err != nil {
  469. return ErrSubscriptionOrderNotFound
  470. }
  471. if expectedPaymentMethod != "" && order.PaymentMethod != expectedPaymentMethod {
  472. return ErrPaymentMethodMismatch
  473. }
  474. if order.Status == common.TopUpStatusSuccess {
  475. return nil
  476. }
  477. if order.Status != common.TopUpStatusPending {
  478. return ErrSubscriptionOrderStatusInvalid
  479. }
  480. plan, err := GetSubscriptionPlanById(order.PlanId)
  481. if err != nil {
  482. return err
  483. }
  484. if !plan.Enabled {
  485. // still allow completion for already purchased orders
  486. }
  487. upgradeGroup = strings.TrimSpace(plan.UpgradeGroup)
  488. _, err = CreateUserSubscriptionFromPlanTx(tx, order.UserId, plan, "order")
  489. if err != nil {
  490. return err
  491. }
  492. if err := upsertSubscriptionTopUpTx(tx, &order); err != nil {
  493. return err
  494. }
  495. order.Status = common.TopUpStatusSuccess
  496. order.CompleteTime = common.GetTimestamp()
  497. if providerPayload != "" {
  498. order.ProviderPayload = providerPayload
  499. }
  500. if err := tx.Save(&order).Error; err != nil {
  501. return err
  502. }
  503. logUserId = order.UserId
  504. logPlanTitle = plan.Title
  505. logMoney = order.Money
  506. logPaymentMethod = order.PaymentMethod
  507. return nil
  508. })
  509. if err != nil {
  510. return err
  511. }
  512. if upgradeGroup != "" && logUserId > 0 {
  513. _ = UpdateUserGroupCache(logUserId, upgradeGroup)
  514. }
  515. if logUserId > 0 {
  516. msg := fmt.Sprintf("订阅购买成功,套餐: %s,支付金额: %.2f,支付方式: %s", logPlanTitle, logMoney, logPaymentMethod)
  517. RecordLog(logUserId, LogTypeTopup, msg)
  518. }
  519. return nil
  520. }
  521. func upsertSubscriptionTopUpTx(tx *gorm.DB, order *SubscriptionOrder) error {
  522. if tx == nil || order == nil {
  523. return errors.New("invalid subscription order")
  524. }
  525. now := common.GetTimestamp()
  526. var topup TopUp
  527. if err := tx.Where("trade_no = ?", order.TradeNo).First(&topup).Error; err != nil {
  528. if errors.Is(err, gorm.ErrRecordNotFound) {
  529. topup = TopUp{
  530. UserId: order.UserId,
  531. Amount: 0,
  532. Money: order.Money,
  533. TradeNo: order.TradeNo,
  534. PaymentMethod: order.PaymentMethod,
  535. CreateTime: order.CreateTime,
  536. CompleteTime: now,
  537. Status: common.TopUpStatusSuccess,
  538. }
  539. return tx.Create(&topup).Error
  540. }
  541. return err
  542. }
  543. topup.Money = order.Money
  544. if topup.PaymentMethod == "" {
  545. topup.PaymentMethod = order.PaymentMethod
  546. } else if topup.PaymentMethod != order.PaymentMethod {
  547. return ErrPaymentMethodMismatch
  548. }
  549. if topup.CreateTime == 0 {
  550. topup.CreateTime = order.CreateTime
  551. }
  552. topup.CompleteTime = now
  553. topup.Status = common.TopUpStatusSuccess
  554. return tx.Save(&topup).Error
  555. }
  556. func ExpireSubscriptionOrder(tradeNo string, expectedPaymentMethod string) error {
  557. if tradeNo == "" {
  558. return errors.New("tradeNo is empty")
  559. }
  560. refCol := "`trade_no`"
  561. if common.UsingPostgreSQL {
  562. refCol = `"trade_no"`
  563. }
  564. return DB.Transaction(func(tx *gorm.DB) error {
  565. var order SubscriptionOrder
  566. if err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(&order).Error; err != nil {
  567. return ErrSubscriptionOrderNotFound
  568. }
  569. if expectedPaymentMethod != "" && order.PaymentMethod != expectedPaymentMethod {
  570. return ErrPaymentMethodMismatch
  571. }
  572. if order.Status != common.TopUpStatusPending {
  573. return nil
  574. }
  575. order.Status = common.TopUpStatusExpired
  576. order.CompleteTime = common.GetTimestamp()
  577. return tx.Save(&order).Error
  578. })
  579. }
  580. // Admin bind (no payment). Creates a UserSubscription from a plan.
  581. func AdminBindSubscription(userId int, planId int, sourceNote string) (string, error) {
  582. if userId <= 0 || planId <= 0 {
  583. return "", errors.New("invalid userId or planId")
  584. }
  585. plan, err := GetSubscriptionPlanById(planId)
  586. if err != nil {
  587. return "", err
  588. }
  589. err = DB.Transaction(func(tx *gorm.DB) error {
  590. _, err := CreateUserSubscriptionFromPlanTx(tx, userId, plan, "admin")
  591. return err
  592. })
  593. if err != nil {
  594. return "", err
  595. }
  596. if strings.TrimSpace(plan.UpgradeGroup) != "" {
  597. _ = UpdateUserGroupCache(userId, plan.UpgradeGroup)
  598. return fmt.Sprintf("用户分组将升级到 %s", plan.UpgradeGroup), nil
  599. }
  600. return "", nil
  601. }
  602. // GetAllActiveUserSubscriptions returns all active subscriptions for a user.
  603. func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error) {
  604. if userId <= 0 {
  605. return nil, errors.New("invalid userId")
  606. }
  607. now := common.GetTimestamp()
  608. var subs []UserSubscription
  609. err := DB.Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
  610. Order("end_time desc, id desc").
  611. Find(&subs).Error
  612. if err != nil {
  613. return nil, err
  614. }
  615. return buildSubscriptionSummaries(subs), nil
  616. }
  617. // HasActiveUserSubscription returns whether the user has any active subscription.
  618. // This is a lightweight existence check to avoid heavy pre-consume transactions.
  619. func HasActiveUserSubscription(userId int) (bool, error) {
  620. if userId <= 0 {
  621. return false, errors.New("invalid userId")
  622. }
  623. now := common.GetTimestamp()
  624. var count int64
  625. if err := DB.Model(&UserSubscription{}).
  626. Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
  627. Count(&count).Error; err != nil {
  628. return false, err
  629. }
  630. return count > 0, nil
  631. }
  632. // GetAllUserSubscriptions returns all subscriptions (active and expired) for a user.
  633. func GetAllUserSubscriptions(userId int) ([]SubscriptionSummary, error) {
  634. if userId <= 0 {
  635. return nil, errors.New("invalid userId")
  636. }
  637. var subs []UserSubscription
  638. err := DB.Where("user_id = ?", userId).
  639. Order("end_time desc, id desc").
  640. Find(&subs).Error
  641. if err != nil {
  642. return nil, err
  643. }
  644. return buildSubscriptionSummaries(subs), nil
  645. }
  646. func buildSubscriptionSummaries(subs []UserSubscription) []SubscriptionSummary {
  647. if len(subs) == 0 {
  648. return []SubscriptionSummary{}
  649. }
  650. result := make([]SubscriptionSummary, 0, len(subs))
  651. for _, sub := range subs {
  652. subCopy := sub
  653. result = append(result, SubscriptionSummary{
  654. Subscription: &subCopy,
  655. })
  656. }
  657. return result
  658. }
  659. // AdminInvalidateUserSubscription marks a user subscription as cancelled and ends it immediately.
  660. func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error) {
  661. if userSubscriptionId <= 0 {
  662. return "", errors.New("invalid userSubscriptionId")
  663. }
  664. now := common.GetTimestamp()
  665. cacheGroup := ""
  666. downgradeGroup := ""
  667. var userId int
  668. err := DB.Transaction(func(tx *gorm.DB) error {
  669. var sub UserSubscription
  670. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  671. Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
  672. return err
  673. }
  674. userId = sub.UserId
  675. if err := tx.Model(&sub).Updates(map[string]interface{}{
  676. "status": "cancelled",
  677. "end_time": now,
  678. "updated_at": now,
  679. }).Error; err != nil {
  680. return err
  681. }
  682. target, err := downgradeUserGroupForSubscriptionTx(tx, &sub, now)
  683. if err != nil {
  684. return err
  685. }
  686. if target != "" {
  687. cacheGroup = target
  688. downgradeGroup = target
  689. }
  690. return nil
  691. })
  692. if err != nil {
  693. return "", err
  694. }
  695. if cacheGroup != "" && userId > 0 {
  696. _ = UpdateUserGroupCache(userId, cacheGroup)
  697. }
  698. if downgradeGroup != "" {
  699. return fmt.Sprintf("用户分组将回退到 %s", downgradeGroup), nil
  700. }
  701. return "", nil
  702. }
  703. // AdminDeleteUserSubscription hard-deletes a user subscription.
  704. func AdminDeleteUserSubscription(userSubscriptionId int) (string, error) {
  705. if userSubscriptionId <= 0 {
  706. return "", errors.New("invalid userSubscriptionId")
  707. }
  708. now := common.GetTimestamp()
  709. cacheGroup := ""
  710. downgradeGroup := ""
  711. var userId int
  712. err := DB.Transaction(func(tx *gorm.DB) error {
  713. var sub UserSubscription
  714. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  715. Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
  716. return err
  717. }
  718. userId = sub.UserId
  719. target, err := downgradeUserGroupForSubscriptionTx(tx, &sub, now)
  720. if err != nil {
  721. return err
  722. }
  723. if target != "" {
  724. cacheGroup = target
  725. downgradeGroup = target
  726. }
  727. if err := tx.Where("id = ?", userSubscriptionId).Delete(&UserSubscription{}).Error; err != nil {
  728. return err
  729. }
  730. return nil
  731. })
  732. if err != nil {
  733. return "", err
  734. }
  735. if cacheGroup != "" && userId > 0 {
  736. _ = UpdateUserGroupCache(userId, cacheGroup)
  737. }
  738. if downgradeGroup != "" {
  739. return fmt.Sprintf("用户分组将回退到 %s", downgradeGroup), nil
  740. }
  741. return "", nil
  742. }
  743. type SubscriptionPreConsumeResult struct {
  744. UserSubscriptionId int
  745. PreConsumed int64
  746. AmountTotal int64
  747. AmountUsedBefore int64
  748. AmountUsedAfter int64
  749. }
  750. // ExpireDueSubscriptions marks expired subscriptions and handles group downgrade.
  751. func ExpireDueSubscriptions(limit int) (int, error) {
  752. if limit <= 0 {
  753. limit = 200
  754. }
  755. now := GetDBTimestamp()
  756. var subs []UserSubscription
  757. if err := DB.Where("status = ? AND end_time > 0 AND end_time <= ?", "active", now).
  758. Order("end_time asc, id asc").
  759. Limit(limit).
  760. Find(&subs).Error; err != nil {
  761. return 0, err
  762. }
  763. if len(subs) == 0 {
  764. return 0, nil
  765. }
  766. expiredCount := 0
  767. userIds := make(map[int]struct{}, len(subs))
  768. for _, sub := range subs {
  769. if sub.UserId > 0 {
  770. userIds[sub.UserId] = struct{}{}
  771. }
  772. }
  773. for userId := range userIds {
  774. cacheGroup := ""
  775. err := DB.Transaction(func(tx *gorm.DB) error {
  776. res := tx.Model(&UserSubscription{}).
  777. Where("user_id = ? AND status = ? AND end_time > 0 AND end_time <= ?", userId, "active", now).
  778. Updates(map[string]interface{}{
  779. "status": "expired",
  780. "updated_at": common.GetTimestamp(),
  781. })
  782. if res.Error != nil {
  783. return res.Error
  784. }
  785. expiredCount += int(res.RowsAffected)
  786. // If there's an active upgraded subscription, keep current group.
  787. var activeSub UserSubscription
  788. activeQuery := tx.Where("user_id = ? AND status = ? AND end_time > ? AND upgrade_group <> ''",
  789. userId, "active", now).
  790. Order("end_time desc, id desc").
  791. Limit(1).
  792. Find(&activeSub)
  793. if activeQuery.Error == nil && activeQuery.RowsAffected > 0 {
  794. return nil
  795. }
  796. // No active upgraded subscription, downgrade to previous group if needed.
  797. var lastExpired UserSubscription
  798. expiredQuery := tx.Where("user_id = ? AND status = ? AND upgrade_group <> ''",
  799. userId, "expired").
  800. Order("end_time desc, id desc").
  801. Limit(1).
  802. Find(&lastExpired)
  803. if expiredQuery.Error != nil || expiredQuery.RowsAffected == 0 {
  804. return nil
  805. }
  806. upgradeGroup := strings.TrimSpace(lastExpired.UpgradeGroup)
  807. prevGroup := strings.TrimSpace(lastExpired.PrevUserGroup)
  808. if upgradeGroup == "" || prevGroup == "" {
  809. return nil
  810. }
  811. currentGroup, err := getUserGroupByIdTx(tx, userId)
  812. if err != nil {
  813. return err
  814. }
  815. if currentGroup != upgradeGroup || currentGroup == prevGroup {
  816. return nil
  817. }
  818. if err := tx.Model(&User{}).Where("id = ?", userId).
  819. Update("group", prevGroup).Error; err != nil {
  820. return err
  821. }
  822. cacheGroup = prevGroup
  823. return nil
  824. })
  825. if err != nil {
  826. return expiredCount, err
  827. }
  828. if cacheGroup != "" {
  829. _ = UpdateUserGroupCache(userId, cacheGroup)
  830. }
  831. }
  832. return expiredCount, nil
  833. }
  834. // SubscriptionPreConsumeRecord stores idempotent pre-consume operations per request.
  835. type SubscriptionPreConsumeRecord struct {
  836. Id int `json:"id"`
  837. RequestId string `json:"request_id" gorm:"type:varchar(64);uniqueIndex"`
  838. UserId int `json:"user_id" gorm:"index"`
  839. UserSubscriptionId int `json:"user_subscription_id" gorm:"index"`
  840. PreConsumed int64 `json:"pre_consumed" gorm:"type:bigint;not null;default:0"`
  841. Status string `json:"status" gorm:"type:varchar(32);index"` // consumed/refunded
  842. CreatedAt int64 `json:"created_at" gorm:"bigint"`
  843. UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
  844. }
  845. func (r *SubscriptionPreConsumeRecord) BeforeCreate(tx *gorm.DB) error {
  846. now := common.GetTimestamp()
  847. r.CreatedAt = now
  848. r.UpdatedAt = now
  849. return nil
  850. }
  851. func (r *SubscriptionPreConsumeRecord) BeforeUpdate(tx *gorm.DB) error {
  852. r.UpdatedAt = common.GetTimestamp()
  853. return nil
  854. }
  855. func maybeResetUserSubscriptionWithPlanTx(tx *gorm.DB, sub *UserSubscription, plan *SubscriptionPlan, now int64) error {
  856. if tx == nil || sub == nil || plan == nil {
  857. return errors.New("invalid reset args")
  858. }
  859. if sub.NextResetTime > 0 && sub.NextResetTime > now {
  860. return nil
  861. }
  862. if NormalizeResetPeriod(plan.QuotaResetPeriod) == SubscriptionResetNever {
  863. return nil
  864. }
  865. baseUnix := sub.LastResetTime
  866. if baseUnix <= 0 {
  867. baseUnix = sub.StartTime
  868. }
  869. base := time.Unix(baseUnix, 0)
  870. next := calcNextResetTime(base, plan, sub.EndTime)
  871. advanced := false
  872. for next > 0 && next <= now {
  873. advanced = true
  874. base = time.Unix(next, 0)
  875. next = calcNextResetTime(base, plan, sub.EndTime)
  876. }
  877. if !advanced {
  878. if sub.NextResetTime == 0 && next > 0 {
  879. sub.NextResetTime = next
  880. sub.LastResetTime = base.Unix()
  881. return tx.Save(sub).Error
  882. }
  883. return nil
  884. }
  885. sub.AmountUsed = 0
  886. sub.LastResetTime = base.Unix()
  887. sub.NextResetTime = next
  888. return tx.Save(sub).Error
  889. }
  890. // PreConsumeUserSubscription pre-consumes from any active subscription total quota.
  891. func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error) {
  892. if userId <= 0 {
  893. return nil, errors.New("invalid userId")
  894. }
  895. if strings.TrimSpace(requestId) == "" {
  896. return nil, errors.New("requestId is empty")
  897. }
  898. if amount <= 0 {
  899. return nil, errors.New("amount must be > 0")
  900. }
  901. now := GetDBTimestamp()
  902. returnValue := &SubscriptionPreConsumeResult{}
  903. err := DB.Transaction(func(tx *gorm.DB) error {
  904. var existing SubscriptionPreConsumeRecord
  905. query := tx.Where("request_id = ?", requestId).Limit(1).Find(&existing)
  906. if query.Error != nil {
  907. return query.Error
  908. }
  909. if query.RowsAffected > 0 {
  910. if existing.Status == "refunded" {
  911. return errors.New("subscription pre-consume already refunded")
  912. }
  913. var sub UserSubscription
  914. if err := tx.Where("id = ?", existing.UserSubscriptionId).First(&sub).Error; err != nil {
  915. return err
  916. }
  917. returnValue.UserSubscriptionId = sub.Id
  918. returnValue.PreConsumed = existing.PreConsumed
  919. returnValue.AmountTotal = sub.AmountTotal
  920. returnValue.AmountUsedBefore = sub.AmountUsed
  921. returnValue.AmountUsedAfter = sub.AmountUsed
  922. return nil
  923. }
  924. var subs []UserSubscription
  925. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  926. Where("user_id = ? AND status = ? AND end_time > ?", userId, "active", now).
  927. Order("end_time asc, id asc").
  928. Find(&subs).Error; err != nil {
  929. return errors.New("no active subscription")
  930. }
  931. if len(subs) == 0 {
  932. return errors.New("no active subscription")
  933. }
  934. for _, candidate := range subs {
  935. sub := candidate
  936. plan, err := getSubscriptionPlanByIdTx(tx, sub.PlanId)
  937. if err != nil {
  938. return err
  939. }
  940. if err := maybeResetUserSubscriptionWithPlanTx(tx, &sub, plan, now); err != nil {
  941. return err
  942. }
  943. usedBefore := sub.AmountUsed
  944. if sub.AmountTotal > 0 {
  945. remain := sub.AmountTotal - usedBefore
  946. if remain < amount {
  947. continue
  948. }
  949. }
  950. record := &SubscriptionPreConsumeRecord{
  951. RequestId: requestId,
  952. UserId: userId,
  953. UserSubscriptionId: sub.Id,
  954. PreConsumed: amount,
  955. Status: "consumed",
  956. }
  957. if err := tx.Create(record).Error; err != nil {
  958. var dup SubscriptionPreConsumeRecord
  959. if err2 := tx.Where("request_id = ?", requestId).First(&dup).Error; err2 == nil {
  960. if dup.Status == "refunded" {
  961. return errors.New("subscription pre-consume already refunded")
  962. }
  963. returnValue.UserSubscriptionId = sub.Id
  964. returnValue.PreConsumed = dup.PreConsumed
  965. returnValue.AmountTotal = sub.AmountTotal
  966. returnValue.AmountUsedBefore = sub.AmountUsed
  967. returnValue.AmountUsedAfter = sub.AmountUsed
  968. return nil
  969. }
  970. return err
  971. }
  972. sub.AmountUsed += amount
  973. if err := tx.Save(&sub).Error; err != nil {
  974. return err
  975. }
  976. returnValue.UserSubscriptionId = sub.Id
  977. returnValue.PreConsumed = amount
  978. returnValue.AmountTotal = sub.AmountTotal
  979. returnValue.AmountUsedBefore = usedBefore
  980. returnValue.AmountUsedAfter = sub.AmountUsed
  981. return nil
  982. }
  983. return fmt.Errorf("subscription quota insufficient, need=%d", amount)
  984. })
  985. if err != nil {
  986. return nil, err
  987. }
  988. return returnValue, nil
  989. }
  990. // RefundSubscriptionPreConsume is idempotent and refunds pre-consumed subscription quota by requestId.
  991. func RefundSubscriptionPreConsume(requestId string) error {
  992. if strings.TrimSpace(requestId) == "" {
  993. return errors.New("requestId is empty")
  994. }
  995. return DB.Transaction(func(tx *gorm.DB) error {
  996. var record SubscriptionPreConsumeRecord
  997. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  998. Where("request_id = ?", requestId).First(&record).Error; err != nil {
  999. return err
  1000. }
  1001. if record.Status == "refunded" {
  1002. return nil
  1003. }
  1004. if record.PreConsumed <= 0 {
  1005. record.Status = "refunded"
  1006. return tx.Save(&record).Error
  1007. }
  1008. if err := PostConsumeUserSubscriptionDelta(record.UserSubscriptionId, -record.PreConsumed); err != nil {
  1009. return err
  1010. }
  1011. record.Status = "refunded"
  1012. return tx.Save(&record).Error
  1013. })
  1014. }
  1015. // ResetDueSubscriptions resets subscriptions whose next_reset_time has passed.
  1016. func ResetDueSubscriptions(limit int) (int, error) {
  1017. if limit <= 0 {
  1018. limit = 200
  1019. }
  1020. now := GetDBTimestamp()
  1021. var subs []UserSubscription
  1022. if err := DB.Where("next_reset_time > 0 AND next_reset_time <= ? AND status = ?", now, "active").
  1023. Order("next_reset_time asc").
  1024. Limit(limit).
  1025. Find(&subs).Error; err != nil {
  1026. return 0, err
  1027. }
  1028. if len(subs) == 0 {
  1029. return 0, nil
  1030. }
  1031. resetCount := 0
  1032. for _, sub := range subs {
  1033. subCopy := sub
  1034. plan, err := getSubscriptionPlanByIdTx(nil, sub.PlanId)
  1035. if err != nil || plan == nil {
  1036. continue
  1037. }
  1038. err = DB.Transaction(func(tx *gorm.DB) error {
  1039. var locked UserSubscription
  1040. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  1041. Where("id = ? AND next_reset_time > 0 AND next_reset_time <= ?", subCopy.Id, now).
  1042. First(&locked).Error; err != nil {
  1043. return nil
  1044. }
  1045. if err := maybeResetUserSubscriptionWithPlanTx(tx, &locked, plan, now); err != nil {
  1046. return err
  1047. }
  1048. resetCount++
  1049. return nil
  1050. })
  1051. if err != nil {
  1052. return resetCount, err
  1053. }
  1054. }
  1055. return resetCount, nil
  1056. }
  1057. // CleanupSubscriptionPreConsumeRecords removes old idempotency records to keep table small.
  1058. func CleanupSubscriptionPreConsumeRecords(olderThanSeconds int64) (int64, error) {
  1059. if olderThanSeconds <= 0 {
  1060. olderThanSeconds = 7 * 24 * 3600
  1061. }
  1062. cutoff := GetDBTimestamp() - olderThanSeconds
  1063. res := DB.Where("updated_at < ?", cutoff).Delete(&SubscriptionPreConsumeRecord{})
  1064. return res.RowsAffected, res.Error
  1065. }
  1066. type SubscriptionPlanInfo struct {
  1067. PlanId int
  1068. PlanTitle string
  1069. }
  1070. func GetSubscriptionPlanInfoByUserSubscriptionId(userSubscriptionId int) (*SubscriptionPlanInfo, error) {
  1071. if userSubscriptionId <= 0 {
  1072. return nil, errors.New("invalid userSubscriptionId")
  1073. }
  1074. cacheKey := fmt.Sprintf("sub:%d", userSubscriptionId)
  1075. if cached, found, err := getSubscriptionPlanInfoCache().Get(cacheKey); err == nil && found {
  1076. return &cached, nil
  1077. }
  1078. var sub UserSubscription
  1079. if err := DB.Where("id = ?", userSubscriptionId).First(&sub).Error; err != nil {
  1080. return nil, err
  1081. }
  1082. plan, err := getSubscriptionPlanByIdTx(nil, sub.PlanId)
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. info := &SubscriptionPlanInfo{
  1087. PlanId: sub.PlanId,
  1088. PlanTitle: plan.Title,
  1089. }
  1090. _ = getSubscriptionPlanInfoCache().SetWithTTL(cacheKey, *info, subscriptionPlanInfoCacheTTL())
  1091. return info, nil
  1092. }
  1093. // Update subscription used amount by delta (positive consume more, negative refund).
  1094. func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error {
  1095. if userSubscriptionId <= 0 {
  1096. return errors.New("invalid userSubscriptionId")
  1097. }
  1098. if delta == 0 {
  1099. return nil
  1100. }
  1101. return DB.Transaction(func(tx *gorm.DB) error {
  1102. var sub UserSubscription
  1103. if err := tx.Set("gorm:query_option", "FOR UPDATE").
  1104. Where("id = ?", userSubscriptionId).
  1105. First(&sub).Error; err != nil {
  1106. return err
  1107. }
  1108. newUsed := sub.AmountUsed + delta
  1109. if newUsed < 0 {
  1110. newUsed = 0
  1111. }
  1112. if sub.AmountTotal > 0 && newUsed > sub.AmountTotal {
  1113. return fmt.Errorf("subscription used exceeds total, used=%d total=%d", newUsed, sub.AmountTotal)
  1114. }
  1115. sub.AmountUsed = newUsed
  1116. return tx.Save(&sub).Error
  1117. })
  1118. }