topup.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "one-api/common"
  6. "one-api/logger"
  7. "github.com/shopspring/decimal"
  8. "gorm.io/gorm"
  9. )
  10. type TopUp struct {
  11. Id int `json:"id"`
  12. UserId int `json:"user_id" gorm:"index"`
  13. Amount int64 `json:"amount"`
  14. Money float64 `json:"money"`
  15. TradeNo string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
  16. PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
  17. CreateTime int64 `json:"create_time"`
  18. CompleteTime int64 `json:"complete_time"`
  19. Status string `json:"status"`
  20. }
  21. func (topUp *TopUp) Insert() error {
  22. var err error
  23. err = DB.Create(topUp).Error
  24. return err
  25. }
  26. func (topUp *TopUp) Update() error {
  27. var err error
  28. err = DB.Save(topUp).Error
  29. return err
  30. }
  31. func GetTopUpById(id int) *TopUp {
  32. var topUp *TopUp
  33. var err error
  34. err = DB.Where("id = ?", id).First(&topUp).Error
  35. if err != nil {
  36. return nil
  37. }
  38. return topUp
  39. }
  40. func GetTopUpByTradeNo(tradeNo string) *TopUp {
  41. var topUp *TopUp
  42. var err error
  43. err = DB.Where("trade_no = ?", tradeNo).First(&topUp).Error
  44. if err != nil {
  45. return nil
  46. }
  47. return topUp
  48. }
  49. func Recharge(referenceId string, customerId string) (err error) {
  50. if referenceId == "" {
  51. return errors.New("未提供支付单号")
  52. }
  53. var quota float64
  54. topUp := &TopUp{}
  55. refCol := "`trade_no`"
  56. if common.UsingPostgreSQL {
  57. refCol = `"trade_no"`
  58. }
  59. err = DB.Transaction(func(tx *gorm.DB) error {
  60. err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", referenceId).First(topUp).Error
  61. if err != nil {
  62. return errors.New("充值订单不存在")
  63. }
  64. if topUp.Status != common.TopUpStatusPending {
  65. return errors.New("充值订单状态错误")
  66. }
  67. topUp.CompleteTime = common.GetTimestamp()
  68. topUp.Status = common.TopUpStatusSuccess
  69. err = tx.Save(topUp).Error
  70. if err != nil {
  71. return err
  72. }
  73. quota = topUp.Money * common.QuotaPerUnit
  74. err = tx.Model(&User{}).Where("id = ?", topUp.UserId).Updates(map[string]interface{}{"stripe_customer": customerId, "quota": gorm.Expr("quota + ?", quota)}).Error
  75. if err != nil {
  76. return err
  77. }
  78. return nil
  79. })
  80. if err != nil {
  81. return errors.New("充值失败," + err.Error())
  82. }
  83. RecordLog(topUp.UserId, LogTypeTopup, fmt.Sprintf("使用在线充值成功,充值金额: %v,支付金额:%d", logger.FormatQuota(int(quota)), topUp.Amount))
  84. return nil
  85. }
  86. func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error) {
  87. // Start transaction
  88. tx := DB.Begin()
  89. if tx.Error != nil {
  90. return nil, 0, tx.Error
  91. }
  92. defer func() {
  93. if r := recover(); r != nil {
  94. tx.Rollback()
  95. }
  96. }()
  97. // Get total count within transaction
  98. err = tx.Model(&TopUp{}).Where("user_id = ?", userId).Count(&total).Error
  99. if err != nil {
  100. tx.Rollback()
  101. return nil, 0, err
  102. }
  103. // Get paginated topups within same transaction
  104. err = tx.Where("user_id = ?", userId).Order("id desc").Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Find(&topups).Error
  105. if err != nil {
  106. tx.Rollback()
  107. return nil, 0, err
  108. }
  109. // Commit transaction
  110. if err = tx.Commit().Error; err != nil {
  111. return nil, 0, err
  112. }
  113. return topups, total, nil
  114. }
  115. // GetAllTopUps 获取全平台的充值记录(管理员使用)
  116. func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error) {
  117. tx := DB.Begin()
  118. if tx.Error != nil {
  119. return nil, 0, tx.Error
  120. }
  121. defer func() {
  122. if r := recover(); r != nil {
  123. tx.Rollback()
  124. }
  125. }()
  126. if err = tx.Model(&TopUp{}).Count(&total).Error; err != nil {
  127. tx.Rollback()
  128. return nil, 0, err
  129. }
  130. if err = tx.Order("id desc").Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Find(&topups).Error; err != nil {
  131. tx.Rollback()
  132. return nil, 0, err
  133. }
  134. if err = tx.Commit().Error; err != nil {
  135. return nil, 0, err
  136. }
  137. return topups, total, nil
  138. }
  139. // ManualCompleteTopUp 管理员手动完成订单并给用户充值
  140. func ManualCompleteTopUp(tradeNo string) error {
  141. if tradeNo == "" {
  142. return errors.New("未提供订单号")
  143. }
  144. refCol := "`trade_no`"
  145. if common.UsingPostgreSQL {
  146. refCol = `"trade_no"`
  147. }
  148. var userId int
  149. var quotaToAdd int
  150. var payMoney float64
  151. err := DB.Transaction(func(tx *gorm.DB) error {
  152. topUp := &TopUp{}
  153. // 行级锁,避免并发补单
  154. if err := tx.Set("gorm:query_option", "FOR UPDATE").Where(refCol+" = ?", tradeNo).First(topUp).Error; err != nil {
  155. return errors.New("充值订单不存在")
  156. }
  157. // 幂等处理:已成功直接返回
  158. if topUp.Status == common.TopUpStatusSuccess {
  159. return nil
  160. }
  161. if topUp.Status != common.TopUpStatusPending {
  162. return errors.New("订单状态不是待支付,无法补单")
  163. }
  164. // 计算应充值额度:
  165. // - Stripe 订单:Money 代表经分组倍率换算后的美元数量,直接 * QuotaPerUnit
  166. // - 其他订单(如易支付):Amount 为美元数量,* QuotaPerUnit
  167. if topUp.PaymentMethod == "stripe" {
  168. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  169. quotaToAdd = int(decimal.NewFromFloat(topUp.Money).Mul(dQuotaPerUnit).IntPart())
  170. } else {
  171. dAmount := decimal.NewFromInt(topUp.Amount)
  172. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  173. quotaToAdd = int(dAmount.Mul(dQuotaPerUnit).IntPart())
  174. }
  175. if quotaToAdd <= 0 {
  176. return errors.New("无效的充值额度")
  177. }
  178. // 标记完成
  179. topUp.CompleteTime = common.GetTimestamp()
  180. topUp.Status = common.TopUpStatusSuccess
  181. if err := tx.Save(topUp).Error; err != nil {
  182. return err
  183. }
  184. // 增加用户额度(立即写库,保持一致性)
  185. if err := tx.Model(&User{}).Where("id = ?", topUp.UserId).Update("quota", gorm.Expr("quota + ?", quotaToAdd)).Error; err != nil {
  186. return err
  187. }
  188. userId = topUp.UserId
  189. payMoney = topUp.Money
  190. return nil
  191. })
  192. if err != nil {
  193. return err
  194. }
  195. // 事务外记录日志,避免阻塞
  196. RecordLog(userId, LogTypeTopup, fmt.Sprintf("管理员补单成功,充值金额: %v,支付金额:%f", logger.FormatQuota(quotaToAdd), payMoney))
  197. return nil
  198. }