package bag_m import ( "git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/resource/mysql" "gorm.io/gorm/clause" "hilo-user/_const/enum/res_e" "hilo-user/domain/event/user_ev" "time" ) type UserBag struct { mysql.Entity UserId mysql.ID ResType mysql.Type // 资源类型 1:礼物 ResId mysql.ID Count mysql.Num EndTime time.Time } type UserBagDetail struct { mysql.Entity UserId mysql.ID BagId mysql.ID ResType mysql.Type // 资源类型 1:礼物 ResId mysql.ID Count mysql.Num AddReduce mysql.AddReduce BefNum mysql.Num AftNum mysql.Num Remark mysql.Str } // 获取用户有效的背包 // param userId 用户id // param resType 背包类型 1:礼物 // condition // 1.获取end_time未到期的 // 2.数量大于0的 func GetUserValidUserBag(model *domain.Model, userId mysql.ID, resType res_e.ResUserBag) ([]*UserBag, error) { var res []*UserBag if err := model.DB().Model(UserBag{}). Where("end_time > ?", time.Now()). Where("count > 0"). Where("res_type = ?", resType). Where("user_id = ?", userId). Order("id").Find(&res).Error; err != nil { return nil, err } return res, nil } // 获取指定背包 func GetUserBag(model *domain.Model, bagId mysql.ID) (*UserBag, error) { res := new(UserBag) if err := model.DB().Model(UserBag{}). Where("id = ?", bagId).First(res).Error; err != nil { return nil, err } return res, nil } // 增加用户背包 // param userId 用户id // param resType 道具类型 // param resId 道具id // param count 增加数量 // param day 增加天数 // condition: // 0.事务操作 // 1.背包表 // 2.明细表 // return bagId func AddUserBag(model *domain.Model, userId mysql.ID, resType mysql.Type, resId mysql.ID, count mysql.Num, day int, reason string) (mysql.ID, error) { var bagId mysql.ID err := model.Transaction(func(model *domain.Model) error { // 1.背包表 endTime := time.Now().AddDate(0, 0, day) userBag := &UserBag{ UserId: userId, ResType: resType, ResId: resId, Count: count, EndTime: endTime, } if err := model.DB().Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "user_id"}, {Name: "res_type"}, {Name: "res_id"}, {Name: "end_time"}}, DoUpdates: clause.AssignmentColumns([]string{"count"}), }).Create(userBag).Error; err != nil { return err } bagId = userBag.ID // 自增id // 2.明细表 userBagDetail := &UserBagDetail{ UserId: userId, BagId: userBag.ID, ResType: resType, ResId: resId, Count: count, AddReduce: mysql.ADD, BefNum: 0, // 加背包的统一为0 AftNum: count, // 加背包统一为count,因为每次加几乎不可能是一样的 Remark: reason, } if err := model.DB().Create(userBagDetail).Error; err != nil { return err } return user_ev.PublishUserBagSend(model, &user_ev.UserBagSendEvent{ UserId: userId, ResType: resType, ResId: resId, Count: count, Day: day, Reason: reason, }) }) return bagId, err }