privilege.go 1.54 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
package cp_m

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/resource/mysql"
	"gorm.io/gorm"
	"hilo-user/_const/enum/cp_e"
)

// svip特权
type CpPrivilege struct {
	mysql.Entity
	UserId    mysql.ID
	Type      cp_e.CpPrivilege
	OpenClose mysql.OpenClose
}

// 开关用于svip特权
func OpenCLoseUserSvipPrivilege(model *domain.Model, userId mysql.ID, Type cp_e.CpPrivilege, openClose mysql.OpenClose) error {
	var pri CpPrivilege
	if err := model.DB().Model(CpPrivilege{}).Where("user_id = ? AND `type` = ?", userId, Type).
		First(&pri).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			return err
		}
		// record not found
		return model.DB().Create(&CpPrivilege{
			UserId:    userId,
			Type:      Type,
			OpenClose: openClose,
		}).Error
	}
	// update
	return model.DB().Model(CpPrivilege{}).Where("user_id = ? AND `type` = ?", userId, Type).
		UpdateColumn("open_close", openClose).Error
}

// 批量获取用户svip特权开关
// map userId->type->open
func MGetUserSvipPrivilege(model *domain.Model, userIds []mysql.ID) (map[mysql.ID]map[cp_e.CpPrivilege]bool, error) {
	res := make(map[mysql.ID]map[cp_e.CpPrivilege]bool)
	var privileges []CpPrivilege
	if err := model.DB().Model(CpPrivilege{}).Where("user_id in ? AND open_close = ?", userIds, mysql.OPEN).Find(&privileges).Error; err != nil {
		return res, err
	}
	for _, v := range privileges {
		if data, ok := res[v.UserId]; ok {
			data[v.Type] = true
		} else {
			res[v.UserId] = make(map[cp_e.CpPrivilege]bool)
			res[v.UserId][v.Type] = true
		}
	}
	return res, nil
}