user.go 8.2 KB

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