record_user.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package sql
  2. import (
  3. "cockData/server/log"
  4. "errors"
  5. "fmt"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/clause"
  8. "strings"
  9. "time"
  10. )
  11. type RecordUser struct {
  12. gorm.Model
  13. PID string `gorm:"uniqueIndex;not null;comment:用户标识"`
  14. Name string `gorm:"not null;comment:用户昵称"`
  15. Avatar string `gorm:"not null;comment:用户头像"`
  16. Diamond int64 `gorm:"default:0;comment:钻石数量"`
  17. }
  18. func (r *RecordUser) TableName() string {
  19. return tableName("record_user")
  20. }
  21. func FindOrCreateUser(pID string, userName string, userAvatar string) (user RecordUser, err error) {
  22. user = RecordUser{
  23. PID: pID,
  24. }
  25. err = _db.Where(&user).FirstOrCreate(&user).Error
  26. if err != nil {
  27. return
  28. }
  29. user.Name = userName
  30. user.Avatar = userAvatar
  31. if user.Name == "" {
  32. user.Name = fmt.Sprintf("Player-%d", user.ID)
  33. }
  34. if user.Avatar == "" {
  35. user.Avatar = "https://cxhy-cn.oss-cn-hangzhou.aliyuncs.com/H5Games/res/manga/IMG_2153.png"
  36. }
  37. err = _db.Save(&user).Error
  38. return
  39. }
  40. func GetUserInfo(userID uint) (createAt time.Time, curDiamond int64, err error) {
  41. user := RecordUser{Model: gorm.Model{ID: userID}}
  42. err = _db.Table(user.TableName()).Where(&user).First(&user).Error
  43. if err != nil {
  44. return
  45. }
  46. createAt = user.CreatedAt
  47. curDiamond = user.Diamond
  48. return
  49. }
  50. func ChangeDiamond(userID uint, diamond int64, reason string) (curDiamond int64, err error) {
  51. if strings.TrimSpace(reason) == "" {
  52. err = errors.New("钻石修改原因不可为空")
  53. log.Warnf("钻石修改原因为空 userID %d", userID)
  54. return
  55. }
  56. err = _db.Transaction(func(tx *gorm.DB) error {
  57. user := RecordUser{Model: gorm.Model{ID: userID}}
  58. err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).Table(user.TableName()).Where(&user).First(&user).Error
  59. if err != nil {
  60. return err
  61. }
  62. record := RecordUserDiamond{UserID: userID}
  63. record.FormDiamond = user.Diamond
  64. record.Diamond = diamond
  65. user.Diamond += diamond
  66. err = tx.Save(&user).Error
  67. if err != nil {
  68. return err
  69. }
  70. record.ToDiamond = user.Diamond
  71. record.Reason = reason
  72. err = tx.Save(&record).Error
  73. if err != nil {
  74. return err
  75. }
  76. curDiamond = user.Diamond
  77. return nil
  78. })
  79. return
  80. }