group_grade.go 10.9 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5
package groupPower_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
6 7
	"git.hilo.cn/hilo-common/utils"
	"github.com/jinzhu/now"
hujiebin's avatar
hujiebin committed
8 9 10
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"hilo-group/_const/enum/groupPower_e"
hujiebin's avatar
hujiebin committed
11
	"hilo-group/domain/event/group_power_ev"
hujiebin's avatar
hujiebin committed
12 13 14
	"time"
)

hujiebin's avatar
hujiebin committed
15
type GroupPowerDayExp struct {
hujiebin's avatar
hujiebin committed
16 17
	Date         string
	GroupPowerId mysql.ID
hujiebin's avatar
hujiebin committed
18
	Exp          mysql.Num
hujiebin's avatar
hujiebin committed
19 20 21 22 23 24
	CreatedTime  time.Time `gorm:"->"`
	UpdatedTime  time.Time `gorm:"->"`
}

type GroupPowerGrade struct {
	GroupPowerId mysql.ID
hujiebin's avatar
hujiebin committed
25
	Exp          mysql.Num
hujiebin's avatar
hujiebin committed
26
	Grade        groupPower_e.GroupPowerGrade
hujiebin's avatar
hujiebin committed
27
	ExpireAt     time.Time
hujiebin's avatar
hujiebin committed
28 29 30 31
	CreatedTime  time.Time `gorm:"->"`
	UpdatedTime  time.Time `gorm:"->"`
}

hujiebin's avatar
hujiebin committed
32 33 34 35 36 37 38 39 40 41 42
type GroupPowerExpDetail struct {
	mysql.Entity
	GroupPowerId mysql.ID
	UserId       mysql.ID
	Exp          mysql.Num
	AddReduce    mysql.AddReduce
	BefNum       mysql.Num
	AftNum       mysql.Num
	Remark       string
}

hujiebin's avatar
hujiebin committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56
type GroupPowerOnMic struct {
	Date         string
	GroupPowerId mysql.ID
	UserId       mysql.ID
	Seconds      int64
	LastCalTs    int64
	CreatedTime  time.Time `gorm:"->"`
	UpdatedTime  time.Time `gorm:"->"`
}

type GroupPowerOnMicDetail struct {
	Date         string
	GroupPowerId mysql.ID
	UserId       mysql.ID
hujiebin's avatar
hujiebin committed
57
	Minute       int
hujiebin's avatar
hujiebin committed
58 59 60 61
	CreatedTime  time.Time `gorm:"->"`
	UpdatedTime  time.Time `gorm:"->"`
}

hujiebin's avatar
hujiebin committed
62 63 64
// 增加家族经验
// 达到经验值之后升级
// 单进程同步执行,不考虑并发
hujiebin's avatar
hujiebin committed
65
func IncrGroupPowerExp(txModel *domain.Model, groupPowerId mysql.ID, exp mysql.Num, userId mysql.ID, remark string) error {
hujiebin's avatar
hujiebin committed
66 67 68 69 70 71 72 73
	var err error
	defer func() {
		if err != nil {
			txModel.Log.Errorf("IncrGroupPowerExp fail,id:%v,exp:%v,err:%v", groupPowerId, exp, err)
		}
	}()
	// 增加家族经验-天
	date := time.Now().Format("2006-01-02")
hujiebin's avatar
hujiebin committed
74
	gpe := &GroupPowerDayExp{
hujiebin's avatar
hujiebin committed
75 76 77 78
		Date:         date,
		GroupPowerId: groupPowerId,
		Exp:          exp,
	}
hujiebin's avatar
hujiebin committed
79
	if err = txModel.DB().Model(GroupPowerDayExp{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "group_power_id"}},
hujiebin's avatar
hujiebin committed
80 81 82 83 84 85 86 87 88
		DoUpdates: clause.Assignments(map[string]interface{}{
			"exp": gorm.Expr("exp + ?", gpe.Exp)})}).Create(gpe).Error; err != nil {
		return err
	}
	// 增加家族经验-总
	gpg := &GroupPowerGrade{
		GroupPowerId: groupPowerId,
		Exp:          exp,
		Grade:        0,
hujiebin's avatar
hujiebin committed
89
		ExpireAt:     time.Time{},
hujiebin's avatar
hujiebin committed
90 91 92 93 94 95
	}
	if err = txModel.DB().Model(GroupPowerGrade{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "group_power_id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{
			"exp": gorm.Expr("exp + ?", gpg.Exp)})}).Create(gpg).Error; err != nil {
		return err
	}
hujiebin's avatar
hujiebin committed
96
	// 当前写后读
hujiebin's avatar
hujiebin committed
97 98 99 100
	latestGrade := new(GroupPowerGrade)
	if err = txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", groupPowerId).First(latestGrade).Error; err != nil {
		return err
	}
hujiebin's avatar
hujiebin committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114
	// 记录明细
	detail := &GroupPowerExpDetail{
		GroupPowerId: groupPowerId,
		UserId:       userId,
		Exp:          exp,
		AddReduce:    mysql.ADD,
		BefNum:       latestGrade.Exp - exp,
		AftNum:       latestGrade.Exp,
		Remark:       remark,
	}
	if err = txModel.DB().Model(GroupPowerExpDetail{}).Create(detail).Error; err != nil {
		return err
	}
	// 达到经验值之后升级
hujiebin's avatar
hujiebin committed
115
	for grade := groupPower_e.GroupPowerGradeMax; grade >= groupPower_e.GroupPowerGrade0; grade-- {
hujiebin's avatar
hujiebin committed
116 117
		if latestGrade.Exp > groupPower_e.GroupPowerGradeExp[grade] {
			if latestGrade.Grade < grade { // 升级
118 119 120 121 122 123 124
				expireAt := now.EndOfMonth()
				expireAt = utils.AddDate(expireAt, 0, 1) // 等级有效期到下个月月底
				updateAttrs := map[string]interface{}{
					"grade":     grade,
					"expire_at": expireAt,
				}
				if err = txModel.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", latestGrade.GroupPowerId).UpdateColumns(updateAttrs).Error; err != nil {
hujiebin's avatar
hujiebin committed
125 126
					return err
				}
hujiebin's avatar
hujiebin committed
127 128 129 130
				// 升级发事件
				_ = group_power_ev.PublishGroupPowerUpgrade(txModel, &group_power_ev.GroupPowerUpgradeEvent{
					GroupPowerId: groupPowerId,
				})
hujiebin's avatar
hujiebin committed
131 132 133 134 135 136
			}
			break
		}
	}
	return nil
}
hujiebin's avatar
hujiebin committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

// 获取势力用户上麦加经验记录
func GetGroupPowerUserOnMicDetails(model *domain.Model, groupPowerId, userId mysql.ID) ([]*GroupPowerOnMicDetail, error) {
	var res []*GroupPowerOnMicDetail
	date := time.Now().Format("2006-01-02")
	if err := model.DB().Model(GroupPowerOnMicDetail{}).Where("date = ? AND group_power_id = ? AND user_id = ?", date, groupPowerId, userId).Find(&res).Error; err != nil {
		return res, err
	}
	return res, nil
}

// 获取势力用户上麦记录
func GetGroupPowerOnMic(model *domain.Model, groupPowerId, userId mysql.ID) (*GroupPowerOnMic, error) {
	gpom := new(GroupPowerOnMic)
	date := time.Now().Format("2006-01-02")
	if err := model.DB().Model(GroupPowerOnMic{}).Where("date = ? AND group_power_id = ? AND user_id = ?", date, groupPowerId, userId).First(gpom).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return &GroupPowerOnMic{Date: date, GroupPowerId: groupPowerId, UserId: userId}, nil
		}
		return nil, err
	}
	return gpom, nil
}

const MaxMinuteTimes = 18

// 增加势力上麦经验
hujiebin's avatar
hujiebin committed
164
// 事务操作
hujiebin's avatar
hujiebin committed
165
func IncrGroupPowerExpOnMic(model *domain.Model, groupPowerId, userId mysql.ID, joinMicTimestamp int64) error {
hujiebin's avatar
hujiebin committed
166 167 168 169 170
	return model.Transaction(func(model *domain.Model) error {
		// 获取用户上麦奖励历史
		onMicDetails, err := GetGroupPowerUserOnMicDetails(model, groupPowerId, userId)
		if err != nil {
			return err
hujiebin's avatar
hujiebin committed
171
		}
hujiebin's avatar
hujiebin committed
172 173 174 175 176 177 178 179 180
		numDetails := len(onMicDetails)
		if numDetails >= MaxMinuteTimes {
			// 上麦经验贡献值最多1800,1分钟100
			return nil
		}
		onMic, err := GetGroupPowerOnMic(model, groupPowerId, userId)
		if err != nil {
			return err
		}
hujiebin's avatar
hujiebin committed
181 182 183 184 185
		nowTs := time.Now().Unix()
		curTs := joinMicTimestamp
		day0Ts := utils.GetZeroTime(time.Now()).Unix()
		if joinMicTimestamp < onMic.LastCalTs {
			curTs = onMic.LastCalTs
hujiebin's avatar
hujiebin committed
186
		}
hujiebin's avatar
hujiebin committed
187 188 189 190 191
		// 跨天
		if curTs < day0Ts {
			curTs = day0Ts
		}
		onMicSeconds := nowTs - curTs
hujiebin's avatar
hujiebin committed
192
		var moreDetails []*GroupPowerOnMicDetail
hujiebin's avatar
hujiebin committed
193
		totalMinuteTimes := int((onMic.Seconds + onMicSeconds) / 600) // 今天实际能加经验次数
hujiebin's avatar
hujiebin committed
194 195 196 197
		if totalMinuteTimes >= MaxMinuteTimes {
			totalMinuteTimes = MaxMinuteTimes
		}
		if totalMinuteTimes > numDetails {
hujiebin's avatar
hujiebin committed
198 199
			// 续上上一次的时间,从numDetails开始
			for mt := numDetails + 1; mt <= totalMinuteTimes; mt++ {
hujiebin's avatar
hujiebin committed
200 201 202 203
				moreDetails = append(moreDetails, &GroupPowerOnMicDetail{
					Date:         time.Now().Format("2006-01-02"),
					GroupPowerId: groupPowerId,
					UserId:       userId,
hujiebin's avatar
hujiebin committed
204
					Minute:       mt * 10, // 转换分钟
hujiebin's avatar
hujiebin committed
205 206 207 208 209 210 211 212 213 214 215
				})
			}
		}
		// 有更多麦上10分钟,可以加经验
		if len(moreDetails) > 0 {
			for _, detail := range moreDetails {
				// 添加明细,避免重复计算
				if err := model.DB().Model(GroupPowerOnMicDetail{}).Create(detail).Error; err != nil {
					return err
				}
				// 每10分钟增加100点经验
hujiebin's avatar
hujiebin committed
216
				if err := IncrGroupPowerExp(model, groupPowerId, 100, userId, "上麦10分钟"); err != nil {
hujiebin's avatar
hujiebin committed
217 218
					return err
				}
hujiebin's avatar
hujiebin committed
219
			}
hujiebin's avatar
hujiebin committed
220 221
			// 更新micExp信息
			onMic.Seconds = onMic.Seconds + onMicSeconds
hujiebin's avatar
hujiebin committed
222
			onMic.LastCalTs = nowTs
hujiebin's avatar
hujiebin committed
223 224 225 226
			if err := model.DB().Model(GroupPowerOnMic{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "group_power_id"}},
				DoUpdates: clause.Assignments(
					map[string]interface{}{
						"seconds":     onMic.Seconds,
hujiebin's avatar
hujiebin committed
227
						"last_cal_ts": nowTs,
hujiebin's avatar
hujiebin committed
228 229 230
					},
				)}).
				Create(onMic).Error; err != nil {
hujiebin's avatar
hujiebin committed
231 232 233
				return err
			}
		}
hujiebin's avatar
hujiebin committed
234 235
		return nil
	})
hujiebin's avatar
hujiebin committed
236
}
hujiebin's avatar
hujiebin committed
237

238 239 240 241
// 增加势力上麦时长-家族之星
// 事务操作
func IncrGroupPowerStarOnMic(model *domain.Model, groupPowerId, userId mysql.ID, joinMicTimestamp int64) error {
	return model.Transaction(func(model *domain.Model) error {
hujiebin's avatar
hujiebin committed
242
		// 月统计
243 244
		star, err := GetGroupPowerMonthStar(model, groupPowerId, userId, groupPower_e.GroupPowerStarTypeActive)
		curTs := joinMicTimestamp
hujiebin's avatar
hujiebin committed
245
		nowTs := time.Now().Unix()
hujiebin's avatar
hujiebin committed
246
		month0Ts := now.BeginningOfMonth().Unix()
247 248 249
		if err != nil && err != gorm.ErrRecordNotFound {
			return err
		}
250
		if star != nil && joinMicTimestamp < star.LastCalTs { // 加入的时间比上次计算时间小
251 252
			curTs = star.LastCalTs
		}
hujiebin's avatar
hujiebin committed
253 254 255 256
		// 跨月
		if curTs < month0Ts {
			curTs = month0Ts
		}
hujiebin's avatar
hujiebin committed
257
		score := nowTs - curTs
258
		err = IncrGroupPowerMonthStarScore(model, groupPowerId, userId, groupPower_e.GroupPowerStarTypeActive, mysql.Num(score), nowTs)
hujiebin's avatar
hujiebin committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
		return err
	})
}

// 增加势力上麦时长-家族之星
// 事务操作
func IncrGroupPowerStarOnMicDay(model *domain.Model, groupPowerId, userId mysql.ID, joinMicTimestamp int64) error {
	return model.Transaction(func(model *domain.Model) error {
		// 日统计
		star, err := GetGroupPowerDayStar(model, groupPowerId, userId, groupPower_e.GroupPowerStarTypeActive)
		curTs := joinMicTimestamp
		nowTs := time.Now().Unix()
		day0Ts := now.BeginningOfDay().Unix()
		if err != nil && err != gorm.ErrRecordNotFound {
			return err
		}
		if star != nil && joinMicTimestamp < star.LastCalTs { // 加入的时间比上次计算时间小
			curTs = star.LastCalTs
		}
		// 跨天
		if curTs < day0Ts {
			curTs = day0Ts
		}
		score := nowTs - curTs
283 284
		err = IncrGroupPowerDayStarScore(model, groupPowerId, userId, groupPower_e.GroupPowerStarTypeActive, mysql.Num(score), nowTs)
		return err
285 286 287
	})
}

hujiebin's avatar
hujiebin committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
// 清理所有家族的经验
func ClearGroupPowerExp(model *domain.Model) error {
	var groupPowerGrades []*GroupPowerGrade
	if err := model.DB().Model(GroupPowerGrade{}).Where("exp > 0").Find(&groupPowerGrades).Error; err != nil {
		return err
	}
	return model.Transaction(func(model *domain.Model) error {
		for _, grade := range groupPowerGrades {
			if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", grade.GroupPowerId).UpdateColumn("exp", 0).Error; err != nil {
				return err
			}
			// 记录明细
			detail := &GroupPowerExpDetail{
				GroupPowerId: grade.GroupPowerId,
				UserId:       0,
				Exp:          0,
				AddReduce:    mysql.SET,
				BefNum:       grade.Exp,
				AftNum:       0,
				Remark:       "每月清零",
			}
			if err := model.DB().Model(GroupPowerExpDetail{}).Create(detail).Error; err != nil {
				return err
			}
		}
		return nil
	})
}

// 清理过期家族等级
func ClearGroupPowerGrade(model *domain.Model) error {
	var groupPowerGrades []*GroupPowerGrade
hujiebin's avatar
hujiebin committed
320
	if err := model.DB().Model(GroupPowerGrade{}).Where("expire_at < ?", time.Now()).Find(&groupPowerGrades).Error; err != nil {
hujiebin's avatar
hujiebin committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
		return err
	}
	return model.Transaction(func(model *domain.Model) error {
		for _, grade := range groupPowerGrades {
			updateAttrs := map[string]interface{}{
				"grade":     0,
				"expire_at": time.Time{},
			}
			if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id = ?", grade.GroupPowerId).Updates(updateAttrs).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
hujiebin's avatar
hujiebin committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349

// 批量获取家族等级
func MGetGroupPowerGrade(model *domain.Model, groupPowerIds []mysql.ID) (map[mysql.ID]GroupPowerGrade, error) {
	var rows []GroupPowerGrade
	res := make(map[mysql.ID]GroupPowerGrade)
	if err := model.DB().Model(GroupPowerGrade{}).Where("group_power_id in ?", groupPowerIds).Find(&rows).Error; err != nil {
		model.Log.Errorf("MGetGroupPowerGrade fail:%v", err)
		return res, err
	}
	for i, v := range rows {
		res[v.GroupPowerId] = rows[i]
	}
	return res, nil
}