user.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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, errArr []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. //var errArr = make([]error, 0)
  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. errArr = append(errArr, err)
  50. global.Logger.Error("CreateUserProduct查询product表出错:", zap.Any("err:", err))
  51. return 0, haveProductId, errArr
  52. }
  53. historyUnitPrice := product.UnitPrice
  54. err = db.GetSFISDB().Where("product_id = ? and app_id = ?", productId, appId).Find(&userProductInfo).Error
  55. if err != nil {
  56. errArr = append(errArr, err)
  57. global.Logger.Error("CreateUserProduct查询user_product表出错:", zap.Any("err:", err))
  58. return 0, haveProductId, errArr
  59. }
  60. //用户第一次购买产品
  61. if userProductInfo.ID == 0 {
  62. errs = db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
  63. rechargeAmount := 0
  64. remark := ""
  65. //第一次购买产品赠送试用量
  66. testNum := product.TestNum
  67. //扣费类型为扣余额,user_buy_record中tradeMoney金额为0
  68. if costModel == 0 {
  69. rechargeAmount = tradeMoney
  70. leftNum += testNum
  71. } else if costModel == 1 {
  72. leftNum = 0
  73. //扣余额,把赠送量转化成金额
  74. freeMoney := testNum * product.UnitPrice
  75. log.Println(freeMoney, "freeMoney")
  76. remark = "充值金额为:" + strconv.Itoa(tradeMoney) + ",赠送金额为:" + strconv.Itoa(freeMoney)
  77. tradeMoney += freeMoney
  78. }
  79. userProduct.LeftNum = leftNum
  80. //生用户产品
  81. err := tx.Create(userProduct).Error
  82. if err != nil {
  83. log.Printf("appID:[%s],productId:[%d] execute insert user_product error:[%v]", appId, productId, err)
  84. tx.Rollback()
  85. return err
  86. }
  87. userProductId := userProduct.ID
  88. //生成购买产品记录
  89. 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
  90. if err != nil {
  91. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute insert into user_buy_record error:[%v]", appId, productId, tradeMoney, err)
  92. tx.Rollback()
  93. return err
  94. }
  95. //扣费类型是扣余额,充值用户余额
  96. if costModel == 1 {
  97. userAccount := model.UserAccount{}
  98. err = tx.First(&userAccount, model.UserAccount{AppID: appId}).Error
  99. if err != nil {
  100. log.Printf("appID:[%s],productId[%d],trade_money:[%d] execute find user_account error:[%v]", appId, productId, tradeMoney, err)
  101. tx.Rollback()
  102. return err
  103. }
  104. moneyBefore := userAccount.Money
  105. moneyAfter := userAccount.Money + tradeMoney
  106. //充值
  107. err := tx.Exec("update user_account set money = ? WHERE `app_id` = ?", moneyAfter, appId).Error
  108. if err != nil {
  109. log.Printf("appID:[%s],money:[%d] execute update user_account error:[%v]", appId, moneyAfter, err)
  110. tx.Rollback()
  111. return err
  112. }
  113. //生充值记录
  114. err = tx.Exec("insert into user_money_record (app_id,`before`,`after`,trade_money,remark) values (?,?,?,?,?)", appId, moneyBefore, moneyAfter, tradeMoney, remark).Error
  115. if err != nil {
  116. log.Printf("appID:[%s],trade_money:[%d] execute insert into user_money_record error:[%v]", appId, tradeMoney, err)
  117. tx.Rollback()
  118. return err
  119. }
  120. }
  121. return nil
  122. })
  123. if errs != nil {
  124. errArr = append(errArr, errs)
  125. global.Logger.Info("用户已购买产品失败:", zap.Any("appId:", appId), zap.Any("productId:", productId))
  126. continue
  127. }
  128. } else {
  129. haveProductId += "[" + strconv.Itoa(productId) + "]"
  130. global.Logger.Info("用户已购买过该产品", zap.Any("appId:", appId), zap.Any("productId:", productId))
  131. continue
  132. }
  133. }
  134. return 1, haveProductId, errArr
  135. }
  136. func UserProductList(appId string, c *gin.Context) (userProduct []model.UserProduct, err error) {
  137. //userProduct := []model.UserProduct{}
  138. err = db.GetSFISDB().Where("app_id = ? ", appId).Find(&userProduct).Error
  139. if err != nil {
  140. log.Printf("appID:[%s] find into user_product error:[%v]", appId, err)
  141. }
  142. return userProduct, err
  143. }
  144. //创建用户
  145. func CreateUser(user model.User) (model.User, error) {
  146. var tempUser []model.User
  147. // 判断用户名是否重复
  148. db.GetSFISDB().Where("name = ?", user.Name).Find(&tempUser)
  149. if len(tempUser) > 0 {
  150. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "用户名已存在"))
  151. return user, errors.New("用户名已存在")
  152. }
  153. // 判断手机号是否重复
  154. var tempUser_ []model.User
  155. db.GetSFISDB().Where("phone = ?", user.Phone).Find(&tempUser_)
  156. if len(tempUser_) > 0 {
  157. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", "手机号已存在"))
  158. return user, errors.New("手机号已存在")
  159. }
  160. errs := db.GetSFISDB().Transaction(func(tx *gorm.DB) error {
  161. // 新增用户
  162. err := tx.Create(&user).Error
  163. if err != nil {
  164. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", err))
  165. tx.Rollback()
  166. return err
  167. }
  168. // 初始化用户账户
  169. userAccount := model.UserAccount{AppID: user.AppID, Money: 0}
  170. err = tx.Create(&userAccount).Error
  171. if err != nil {
  172. global.Logger.Error("userAccountInit Error", zap.Any("user", user), zap.Any("userAccount", userAccount), zap.Any("error", err))
  173. tx.Rollback()
  174. return err
  175. }
  176. return nil
  177. })
  178. if errs != nil {
  179. global.Logger.Error("userCreate Error", zap.Any("user", user), zap.Any("error", errs))
  180. return user, errors.New("创建失败")
  181. } else {
  182. global.Logger.Info("userCreate Success", zap.Any("user", user))
  183. // 生全局内存锁
  184. lock.MainLock.Lock()
  185. lock.UserLockMap[user.AppID] = &sync.Mutex{}
  186. lock.MainLock.Unlock()
  187. return user, nil
  188. }
  189. }
  190. // 查询用户
  191. func ListUser(condMap map[string]interface{}, page int, limit int) ([]map[string]interface{}, int64, error) {
  192. // 拼查询sql
  193. var key []string
  194. var param []interface{}
  195. for k, v := range condMap {
  196. if v == "" {
  197. continue
  198. }
  199. var kStr string
  200. kStr = fmt.Sprintf("%s like ?", k)
  201. v = "%" + v.(string) + "%"
  202. key = append(key, kStr)
  203. param = append(param, v)
  204. }
  205. whereSql := strings.Join(key, " and ")
  206. var totalCount int64
  207. var userInfo []map[string]interface{}
  208. err := db.GetSFISDB().Table("user").Where(whereSql, param...).Where("delete_at is null").Count(&totalCount).Error
  209. if err != nil {
  210. return nil, 0, errors.New("查询失败")
  211. }
  212. if totalCount == 0 {
  213. return userInfo, 0, nil
  214. }
  215. if whereSql != "" {
  216. whereSql = " and " + whereSql
  217. }
  218. 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
  219. if limit != 0 && page > 0 {
  220. sql += fmt.Sprintf(" limit %d ,%d", (page-1)*limit, limit)
  221. }
  222. result := db.GetSFISDB().Raw(sql, param...).Scan(&userInfo)
  223. if result.Error != nil {
  224. return nil, 0, errors.New("查询失败")
  225. }
  226. return userInfo, totalCount, nil
  227. }