user.go 8.2 KB

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