user.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package service
  2. import (
  3. "errors"
  4. "github.com/gin-gonic/gin"
  5. "go.uber.org/zap"
  6. "gorm.io/gorm"
  7. "log"
  8. "sfbase/global"
  9. "sfis/db"
  10. "sfis/lock"
  11. "sfis/model"
  12. "sfis/model/response"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. func UserProduct(productIds, appId, startTime, endTime string, leftNum, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, tradeMoney, buyType int, c *gin.Context) {
  19. //取出用户锁
  20. lock.MainLock.Lock()
  21. userLock := lock.UserLockMap[appId]
  22. lock.MainLock.Unlock()
  23. userLock.Lock()
  24. defer userLock.Unlock()
  25. productIdsArr := strings.Split(productIds, ",")
  26. if len(productIdsArr) > 0 {
  27. var errs error
  28. for _, v := range productIdsArr {
  29. productId, _ := strconv.Atoi(v)
  30. userProduct := &model.UserProduct{}
  31. userProduct.AppID = appId
  32. userProduct.StartAt, _ = time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
  33. userProduct.EndAt, _ = time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
  34. userProduct.LeftNum = leftNum
  35. userProduct.CostModel = costModel
  36. userProduct.InterfaceStatus = interfaceStatus
  37. userProduct.CallTimesLimitDay = callTimesLimitDay
  38. userProduct.DataNumLimitOneTimes = dataNumOneTimes
  39. userProduct.ProductID = productId
  40. userProductInfo := model.UserProduct{}
  41. product := model.Product{}
  42. //查询产品信息,获取购买时候产品单价、试用次数
  43. err := db.GetSFISDB().Where("id = ?", productId).Find(&product).Error
  44. if err != nil {
  45. response.FailWithMessage("查询产品信息出错", c)
  46. return
  47. }
  48. historyUnitPrice := product.UnitPrice
  49. err = db.GetSFISDB().Where("product_id = ? and app_id = ?", productId, appId).Find(&userProductInfo).Error
  50. if err != nil {
  51. response.FailWithMessage("查询用户产品信息出错", c)
  52. return
  53. }
  54. //已选择过该产品--更新用户产品信息
  55. if userProductInfo.ID != 0 {
  56. before := userProductInfo.LeftNum
  57. after := userProductInfo.LeftNum + leftNum
  58. userProductId := userProductInfo.ID
  59. errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
  60. //更新用户产品信息
  61. userProduct.LeftNum = userProductInfo.LeftNum + leftNum
  62. userProduct.UpdateAt = time.Now()
  63. log.Println(userProduct.UpdateAt, "++++++++++++++++++++")
  64. err := tx.Exec("update user_product set left_num = ?, start_at = ?,end_at = ?,cost_model = ?,interface_status = ?,call_times_limit_day=?,data_num_limit_one_times=? where product_id = ? and app_id = ?", after, startTime, endTime, costModel, interfaceStatus, callTimesLimitDay, dataNumOneTimes, productId, appId).Error
  65. if err != nil {
  66. log.Printf("appID:[%s],productId:[%d] update user_product error:[%v]", appId, productId, err)
  67. tx.Rollback()
  68. return err
  69. }
  70. //生成购买产品记录
  71. //扣费类型为扣余额,user_buy_record中tradeMoney金额为0
  72. rechargeAmount := 0
  73. if costModel == 0 {
  74. rechargeAmount = tradeMoney
  75. }
  76. err = tx.Exec("insert into user_buy_record (`app_id`,`product_id`,`user_product_id`,`before`,`after`,`trade_money`,`buy_type`,`history_unit_price`) values (?,?,?,?,?,?,?,?)", appId, productId, userProductId, before, after, rechargeAmount, buyType, historyUnitPrice).Error
  77. if err != nil {
  78. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, productId, tradeMoney, err)
  79. tx.Rollback()
  80. return err
  81. }
  82. //扣费类型是扣余额,充值用户余额
  83. if costModel == 1 {
  84. userAccount := model.UserAccount{}
  85. err = tx.First(&userAccount, model.UserAccount{AppID: appId}).Error
  86. if err != nil {
  87. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute find user_account error:[%v]", appId, productId, tradeMoney, err)
  88. tx.Rollback()
  89. return err
  90. }
  91. moneyBefore := userAccount.Money
  92. moneyAfter := userAccount.Money + tradeMoney
  93. //充值
  94. err := tx.Exec("update user_account set money = ? WHERE `app_id` = ?", moneyAfter, appId).Error
  95. if err != nil {
  96. log.Printf("appID:[%s],money:[%d] execute cost user_account error:[%v]", appId, moneyAfter, err)
  97. tx.Rollback()
  98. return err
  99. }
  100. //生充值记录
  101. err = tx.Exec("insert into user_money_record (app_id,`before`,`after`,trade_money) values (?,?,?,?)", appId, moneyBefore, moneyAfter, tradeMoney).Error
  102. if err != nil {
  103. log.Printf("appID:[%s],trade_money:[%d] execute insert into user_money_record error:[%v]", appId, tradeMoney, err)
  104. tx.Rollback()
  105. return err
  106. }
  107. }
  108. return nil
  109. })
  110. } else { //用户没有购买过改产品
  111. errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
  112. //扣费类型为扣余额,user_buy_record中tradeMoney金额为0
  113. rechargeAmount := 0
  114. //第一次购买产品赠送试用量
  115. testNum := product.TestNum
  116. remark := ""
  117. if costModel == 0 {
  118. rechargeAmount = tradeMoney
  119. leftNum += testNum
  120. } else if costModel == 1 {
  121. //扣余额,把赠送量转化成金额
  122. freeMoney := testNum * product.UnitPrice
  123. tradeMoney += freeMoney
  124. remark = "充值金额为:" + strconv.Itoa(tradeMoney) + "赠送金额为:" + strconv.Itoa(freeMoney)
  125. }
  126. userProduct.LeftNum = leftNum
  127. //生用户产品
  128. err := tx.Create(userProduct).Error
  129. if err != nil {
  130. log.Printf("appID:[%s],productId:[%d] insert user_product error:[%v]", appId, productId, err)
  131. tx.Rollback()
  132. return tx.Error
  133. }
  134. userProductId := userProduct.ID
  135. //生成购买产品记录
  136. err = tx.Exec("insert into user_buy_record (`app_id`,`product_id`,`user_product_id`,`before`,`after`,`trade_money`,`buy_type`,`history_unit_price`) values (?,?,?,?,?,?,?,?)", appId, productId, userProductId, 0, leftNum, rechargeAmount, buyType, historyUnitPrice).Error
  137. if err != nil {
  138. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, productId, tradeMoney, err)
  139. tx.Rollback()
  140. return err
  141. }
  142. //扣费类型是扣余额,充值用户余额
  143. if costModel == 1 {
  144. //第一次购买产品赠送免费次数
  145. userAccount := model.UserAccount{}
  146. err = tx.First(&userAccount, model.UserAccount{AppID: appId}).Error
  147. if err != nil {
  148. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute find user_account error:[%v]", appId, productId, tradeMoney, err)
  149. tx.Rollback()
  150. return err
  151. }
  152. moneyBefore := userAccount.Money
  153. moneyAfter := userAccount.Money + tradeMoney
  154. //充值
  155. err := tx.Exec("update user_account set money = ? WHERE `app_id` = ?", moneyAfter, appId).Error
  156. if err != nil {
  157. log.Printf("appID:[%s],money:[%d] execute cost user_account error:[%v]", appId, moneyAfter, err)
  158. tx.Rollback()
  159. return err
  160. }
  161. //生充值记录
  162. err = tx.Exec("insert into user_money_record (app_id,`before`,`after`,trade_money,remark) values (?,?,?,?,?)", appId, moneyBefore, moneyAfter, tradeMoney, remark).Error
  163. if err != nil {
  164. log.Printf("appID:[%s],trade_money:[%d] execute insert into user_money_record error:[%v]", appId, tradeMoney, err)
  165. tx.Rollback()
  166. return err
  167. }
  168. }
  169. return nil
  170. })
  171. }
  172. }
  173. if errs == nil {
  174. response.Ok(c)
  175. return
  176. } else {
  177. response.FailWithMessage("购买产品失败", c)
  178. return
  179. }
  180. }
  181. response.FailWithMessage("缺少参数", c)
  182. }
  183. func UserProductList(appId string, c *gin.Context) {
  184. userProduct := []model.UserProduct{}
  185. err := db.GetSFISDB().Where("app_id = ? and ", appId).Find(&userProduct).Error
  186. if err != nil {
  187. log.Printf("appID:[%s] find into user_product error:[%v]", appId, err)
  188. response.FailWithMessage("查询出错", c)
  189. } else {
  190. response.OkWithData(userProduct, c)
  191. }
  192. }
  193. //创建用户
  194. func CreateUser(user model.User) (model.User, error) {
  195. var tempUser []model.User
  196. // 判断用户名是否重复
  197. db.GetSFISDB().Where("name = ?", user.Name).Find(&tempUser)
  198. if len(tempUser) > 0 {
  199. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "用户名已存在"))
  200. return user, errors.New("用户名已存在")
  201. }
  202. // 判断手机号是否重复
  203. var tempUser_ []model.User
  204. db.GetSFISDB().Where("phone = ?", user.Phone).Find(&tempUser_)
  205. if len(tempUser_) > 0 {
  206. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "手机号已存在"))
  207. return user, errors.New("手机号已存在")
  208. }
  209. errs := db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
  210. // 新增用户
  211. err := tx.Create(&user).Error
  212. if err != nil {
  213. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", err))
  214. tx.Rollback()
  215. return err
  216. }
  217. // 初始化用户账户
  218. userAccount := model.UserAccount{AppID: user.AppID, Money: 0}
  219. err = tx.Create(&userAccount).Error
  220. if err != nil {
  221. global.Logger.Error("userAccountInit Error", zap.Any("user", user), zap.Any("userAccount", userAccount), zap.Any("error", err))
  222. tx.Rollback()
  223. return err
  224. }
  225. return nil
  226. })
  227. if errs != nil {
  228. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", errs))
  229. return user, errors.New("创建失败")
  230. } else {
  231. global.Logger.Info("userCreate Success", zap.Any("user", user))
  232. // 生全局内存锁
  233. lock.MainLock.Lock()
  234. lock.UserLockMap[user.AppID] = &sync.Mutex{}
  235. lock.MainLock.Unlock()
  236. return user, nil
  237. }
  238. }