wip: 新版优化,开发中。

main
NorthLan 3 years ago
parent f32e82fe1c
commit 7c8343bc17

@ -171,8 +171,8 @@ type MqGift struct {
GiftId int64 `protobuf:"varint,5,opt,name=giftId,proto3" json:"giftId,omitempty"`
Num int64 `protobuf:"varint,6,opt,name=num,proto3" json:"num,omitempty"`
GiftName string `protobuf:"bytes,7,opt,name=giftName,proto3" json:"giftName,omitempty"`
TotalCoin int64 `protobuf:"varint,8,opt,name=totalCoin,proto3" json:"totalCoin,omitempty"`
SendTime int64 `protobuf:"varint,9,opt,name=sendTime,proto3" json:"sendTime,omitempty"`
Price int64 `protobuf:"varint,8,opt,name=price,proto3" json:"price,omitempty"`
IsPaid bool `protobuf:"varint,9,opt,name=isPaid,proto3" json:"isPaid,omitempty"`
}
func (x *MqGift) Reset() {
@ -256,16 +256,111 @@ func (x *MqGift) GetGiftName() string {
return ""
}
func (x *MqGift) GetTotalCoin() int64 {
func (x *MqGift) GetPrice() int64 {
if x != nil {
return x.TotalCoin
return x.Price
}
return 0
}
func (x *MqGift) GetSendTime() int64 {
func (x *MqGift) GetIsPaid() bool {
if x != nil {
return x.SendTime
return x.IsPaid
}
return false
}
type MqRewardPool struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
WelfarePool int64 `protobuf:"varint,1,opt,name=welfarePool,proto3" json:"welfarePool,omitempty"` // 福利池,与战局无关
BattleId int64 `protobuf:"varint,2,opt,name=battleId,proto3" json:"battleId,omitempty"` // 战局ID
InitReward int64 `protobuf:"varint,3,opt,name=initReward,proto3" json:"initReward,omitempty"` // 初始奖池
GiftReward int64 `protobuf:"varint,4,opt,name=giftReward,proto3" json:"giftReward,omitempty"` // 礼物奖池
BattleReward int64 `protobuf:"varint,5,opt,name=battleReward,proto3" json:"battleReward,omitempty"` // 战斗奖池
OtherReward int64 `protobuf:"varint,6,opt,name=otherReward,proto3" json:"otherReward,omitempty"` // 其它奖池
AllRewards int64 `protobuf:"varint,10,opt,name=allRewards,proto3" json:"allRewards,omitempty"` // 所有奖池
}
func (x *MqRewardPool) Reset() {
*x = MqRewardPool{}
if protoimpl.UnsafeEnabled {
mi := &file_mq_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *MqRewardPool) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*MqRewardPool) ProtoMessage() {}
func (x *MqRewardPool) ProtoReflect() protoreflect.Message {
mi := &file_mq_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use MqRewardPool.ProtoReflect.Descriptor instead.
func (*MqRewardPool) Descriptor() ([]byte, []int) {
return file_mq_proto_rawDescGZIP(), []int{2}
}
func (x *MqRewardPool) GetWelfarePool() int64 {
if x != nil {
return x.WelfarePool
}
return 0
}
func (x *MqRewardPool) GetBattleId() int64 {
if x != nil {
return x.BattleId
}
return 0
}
func (x *MqRewardPool) GetInitReward() int64 {
if x != nil {
return x.InitReward
}
return 0
}
func (x *MqRewardPool) GetGiftReward() int64 {
if x != nil {
return x.GiftReward
}
return 0
}
func (x *MqRewardPool) GetBattleReward() int64 {
if x != nil {
return x.BattleReward
}
return 0
}
func (x *MqRewardPool) GetOtherReward() int64 {
if x != nil {
return x.OtherReward
}
return 0
}
func (x *MqRewardPool) GetAllRewards() int64 {
if x != nil {
return x.AllRewards
}
return 0
}
@ -284,7 +379,7 @@ var file_mq_proto_rawDesc = []byte{
0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28,
0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65,
0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x73, 0x65,
0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xec, 0x01, 0x0a, 0x06, 0x4d, 0x71, 0x47, 0x69, 0x66,
0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xe0, 0x01, 0x0a, 0x06, 0x4d, 0x71, 0x47, 0x69, 0x66,
0x74, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x12, 0x1e, 0x0a,
0x0a, 0x6c, 0x69, 0x76, 0x65, 0x52, 0x6f, 0x6f, 0x6d, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28,
@ -295,16 +390,30 @@ var file_mq_proto_rawDesc = []byte{
0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x67, 0x69, 0x66, 0x74, 0x49, 0x64, 0x12, 0x10, 0x0a,
0x03, 0x6e, 0x75, 0x6d, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x6e, 0x75, 0x6d, 0x12,
0x1a, 0x0a, 0x08, 0x67, 0x69, 0x66, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28,
0x09, 0x52, 0x08, 0x67, 0x69, 0x66, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x74,
0x6f, 0x74, 0x61, 0x6c, 0x43, 0x6f, 0x69, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09,
0x74, 0x6f, 0x74, 0x61, 0x6c, 0x43, 0x6f, 0x69, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x6e,
0x64, 0x54, 0x69, 0x6d, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x73, 0x65, 0x6e,
0x64, 0x54, 0x69, 0x6d, 0x65, 0x2a, 0x39, 0x0a, 0x08, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72,
0x6d, 0x12, 0x0c, 0x0a, 0x08, 0x62, 0x69, 0x6c, 0x69, 0x62, 0x69, 0x6c, 0x69, 0x10, 0x00, 0x12,
0x08, 0x0a, 0x04, 0x68, 0x75, 0x79, 0x61, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x64, 0x6f, 0x75,
0x79, 0x75, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x10, 0x03,
0x42, 0x07, 0x5a, 0x05, 0x2f, 0x70, 0x62, 0x4d, 0x71, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
0x09, 0x52, 0x08, 0x67, 0x69, 0x66, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x70,
0x72, 0x69, 0x63, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x70, 0x72, 0x69, 0x63,
0x65, 0x12, 0x16, 0x0a, 0x06, 0x69, 0x73, 0x50, 0x61, 0x69, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28,
0x08, 0x52, 0x06, 0x69, 0x73, 0x50, 0x61, 0x69, 0x64, 0x22, 0xf2, 0x01, 0x0a, 0x0c, 0x4d, 0x71,
0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x50, 0x6f, 0x6f, 0x6c, 0x12, 0x20, 0x0a, 0x0b, 0x77, 0x65,
0x6c, 0x66, 0x61, 0x72, 0x65, 0x50, 0x6f, 0x6f, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52,
0x0b, 0x77, 0x65, 0x6c, 0x66, 0x61, 0x72, 0x65, 0x50, 0x6f, 0x6f, 0x6c, 0x12, 0x1a, 0x0a, 0x08,
0x62, 0x61, 0x74, 0x74, 0x6c, 0x65, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08,
0x62, 0x61, 0x74, 0x74, 0x6c, 0x65, 0x49, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x69, 0x6e, 0x69, 0x74,
0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x69, 0x6e,
0x69, 0x74, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x67, 0x69, 0x66, 0x74,
0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x67, 0x69,
0x66, 0x74, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x12, 0x22, 0x0a, 0x0c, 0x62, 0x61, 0x74, 0x74,
0x6c, 0x65, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0c,
0x62, 0x61, 0x74, 0x74, 0x6c, 0x65, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x12, 0x20, 0x0a, 0x0b,
0x6f, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28,
0x03, 0x52, 0x0b, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x12, 0x1e,
0x0a, 0x0a, 0x61, 0x6c, 0x6c, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x73, 0x18, 0x0a, 0x20, 0x01,
0x28, 0x03, 0x52, 0x0a, 0x61, 0x6c, 0x6c, 0x52, 0x65, 0x77, 0x61, 0x72, 0x64, 0x73, 0x2a, 0x39,
0x0a, 0x08, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x12, 0x0c, 0x0a, 0x08, 0x62, 0x69,
0x6c, 0x69, 0x62, 0x69, 0x6c, 0x69, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x68, 0x75, 0x79, 0x61,
0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x64, 0x6f, 0x75, 0x79, 0x75, 0x10, 0x02, 0x12, 0x0a, 0x0a,
0x06, 0x64, 0x6f, 0x75, 0x79, 0x69, 0x6e, 0x10, 0x03, 0x42, 0x07, 0x5a, 0x05, 0x2f, 0x70, 0x62,
0x4d, 0x71, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
@ -320,11 +429,12 @@ func file_mq_proto_rawDescGZIP() []byte {
}
var file_mq_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_mq_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_mq_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_mq_proto_goTypes = []interface{}{
(Platform)(0), // 0: pb.Platform
(*MqDanmaku)(nil), // 1: pb.MqDanmaku
(*MqGift)(nil), // 2: pb.MqGift
(Platform)(0), // 0: pb.Platform
(*MqDanmaku)(nil), // 1: pb.MqDanmaku
(*MqGift)(nil), // 2: pb.MqGift
(*MqRewardPool)(nil), // 3: pb.MqRewardPool
}
var file_mq_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
@ -364,6 +474,18 @@ func file_mq_proto_init() {
return nil
}
}
file_mq_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*MqRewardPool); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
@ -371,7 +493,7 @@ func file_mq_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_mq_proto_rawDesc,
NumEnums: 1,
NumMessages: 2,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},

@ -9,7 +9,6 @@ enum Platform {
huya = 1; //
douyu = 2; //
douyin = 3; //
//
}
message MqDanmaku {
@ -29,15 +28,16 @@ message MqGift {
int64 giftId = 5;
int64 num = 6;
string giftName = 7;
int64 totalCoin = 8;
int64 sendTime = 9;
int64 price = 8;
bool isPaid = 9;
}
// MqUserInfoUpdate
message MqUserInfoUpdate {
int64 userId = 1; // ID
}
// MqRankUpdate
message MqRankUpdate {
message MqRewardPool {
int64 welfarePool = 1; //
int64 battleId = 2; // ID
int64 initReward = 3; //
int64 giftReward = 4; //
int64 battleReward = 5; //
int64 otherReward = 6; //
int64 allRewards = 10; //
}

@ -2,7 +2,7 @@
chcp 65001
@echo 开始代码生成
set tables=user_integral
set tables=user_coin
set targetDir=.\model
set templateDir=..\..\doc\template

@ -34,12 +34,9 @@ func (m *customGiftModel) FindByPlatformGift(ctx context.Context, platform strin
err := db.Model(&Gift{}).
Where("platform = ? AND gift_id = ?", platform, giftId).
Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*Gift), nil
}

@ -64,32 +64,28 @@ func (m *defaultGiftModel) Insert(ctx context.Context, tx *gorm.DB, data *Gift)
func (m *defaultGiftModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*Gift, error) {
var resp Gift
err := gormx.WithTx(ctx, m.DB, tx).Model(&Gift{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*Gift), nil
}
func (m *defaultGiftModel) FindOneByGiftIdPlatform(ctx context.Context, tx *gorm.DB, giftId string, platform string) (*Gift, error) {
var resp Gift
err := gormx.WithTx(ctx, m.DB, tx).Model(&Gift{}).Where("`gift_id` = ? and `platform` = ?", giftId, platform).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*Gift), nil
}
func (m *defaultGiftModel) Update(ctx context.Context, tx *gorm.DB, data *Gift) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultGiftModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -3,19 +3,49 @@ package model
import "live-service/app/user_center/rpc/pb"
var rankAndScoreMap map[pb.RankType]ScoreType
var scoreAndRankMap map[ScoreType]pb.RankType
func init() {
rankAndScoreMap = map[pb.RankType]ScoreType{
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_DeDamage: ScoreTypeDeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
pb.RankType_Damage: ScoreTypeDamage,
func ScoreTypeByRankType(rankType pb.RankType) ScoreType {
if scoreType, ok := rankAndScoreMap[rankType]; ok {
return scoreType
}
return ScoreTypeDamage
}
func RankTypeByScoreType(scoreType ScoreType) pb.RankType {
if rankType, ok := scoreAndRankMap[scoreType]; ok {
return rankType
}
return pb.RankType_Damage
}
func AllScoreType() []ScoreType {
result := make([]ScoreType, 0, len(rankAndScoreMap))
for _, scoreType := range rankAndScoreMap {
result = append(result, scoreType)
}
return result
}
func addRankScore(rankType pb.RankType, scoreType ScoreType) {
rankAndScoreMap[rankType] = scoreType
scoreAndRankMap[scoreType] = rankType
}
func init() {
rankAndScoreMap = make(map[pb.RankType]ScoreType)
scoreAndRankMap = make(map[ScoreType]pb.RankType)
addRankScore(pb.RankType_Damage, ScoreTypeDamage)
addRankScore(pb.RankType_DeDamage, ScoreTypeDeDamage)
addRankScore(pb.RankType_General, ScoreTypeGeneral)
addRankScore(pb.RankType_DeGeneral, ScoreTypeDeGeneral)
addRankScore(pb.RankType_KillUnit, ScoreTypeKillUnit)
addRankScore(pb.RankType_DeKillUnit, ScoreTypeDeKillUnit)
addRankScore(pb.RankType_KillPlayer, ScoreTypeKillPlayer)
addRankScore(pb.RankType_DeKillPlayer, ScoreTypeDeKillPlayer)
addRankScore(pb.RankType_Win, ScoreTypeWin)
addRankScore(pb.RankType_Lost, ScoreTypeLost)
addRankScore(pb.RankType_FirstBlood, ScoreTypeFirstBlood)
addRankScore(pb.RankType_DeFirstBlood, ScoreTypeDeFirstBlood)
}

@ -31,8 +31,8 @@ type (
// and implement the added methods in customRankPvpModel.
RankPvpModel interface {
rankPvpModel
RankListByType(ctx context.Context, rankType, topN int32) ([]RankPvpWithPlatformUser, error)
UpdateRank(ctx context.Context, rankType int32, data []RankPvp) error
RankListByType(ctx context.Context, rankType, topN int64) ([]RankPvpWithPlatformUser, error)
UpdateRank(ctx context.Context, rankType int64, data []RankPvp) error
}
customRankPvpModel struct {
@ -54,7 +54,7 @@ func NewRankPvpModel(conn *gorm.DB) RankPvpModel {
}
}
func (m *customRankPvpModel) RankListByType(ctx context.Context, rankType, topN int32) ([]RankPvpWithPlatformUser, error) {
func (m *customRankPvpModel) RankListByType(ctx context.Context, rankType, topN int64) ([]RankPvpWithPlatformUser, error) {
db := m.DB.WithContext(ctx)
limit := topN
if limit > MaxRankN {
@ -67,17 +67,14 @@ func (m *customRankPvpModel) RankListByType(ctx context.Context, rankType, topN
Where(fmt.Sprintf("%s.user_id > 0 AND rank_type = ?", m.table), rankType).
Limit(int(limit)).
Find(&result).Error
switch err {
case nil:
return result, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
selectResult, err := gormx.WrapSelectResult(err, result)
if err != nil {
return nil, err
}
return selectResult.([]RankPvpWithPlatformUser), nil
}
func (m *customRankPvpModel) UpdateRank(ctx context.Context, rankType int32, data []RankPvp) error {
func (m *customRankPvpModel) UpdateRank(ctx context.Context, rankType int64, data []RankPvp) error {
db := m.DB.WithContext(ctx)
return db.Transaction(func(tx *gorm.DB) error {
var err error

@ -62,32 +62,28 @@ func (m *defaultRankPvpModel) Insert(ctx context.Context, tx *gorm.DB, data *Ran
func (m *defaultRankPvpModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*RankPvp, error) {
var resp RankPvp
err := gormx.WithTx(ctx, m.DB, tx).Model(&RankPvp{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*RankPvp), nil
}
func (m *defaultRankPvpModel) FindOneByUserIdRankType(ctx context.Context, tx *gorm.DB, userId int64, rankType int64) (*RankPvp, error) {
var resp RankPvp
err := gormx.WithTx(ctx, m.DB, tx).Model(&RankPvp{}).Where("`user_id` = ? and `rank_type` = ?", userId, rankType).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*RankPvp), nil
}
func (m *defaultRankPvpModel) Update(ctx context.Context, tx *gorm.DB, data *RankPvp) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultRankPvpModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -35,8 +35,8 @@ type (
UpdateRecord(ctx context.Context, tx *gorm.DB, userId int64, props *UpdateRecordProps) error
// FindGreaterByScore 找到比给定分数大的用户id以及具体分数
FindGreaterByScore(ctx context.Context, score int64, scoreType ScoreType, limit int) ([]UserAndScore, error)
// FindScoreByType 根据类型获取分数
FindScoreByType()
// FindScoreByType 根据类型获取用户分数
FindScoreByType(ctx context.Context, tx *gorm.DB, userId int64, scoreType []ScoreType) (map[string]int64, error)
}
UserAndScore struct {
@ -114,13 +114,7 @@ func (m *customStatisticsPvpModel) UpdateRecord(ctx context.Context, tx *gorm.DB
data["de_first_blood_count"] = gorm.Expr("de_first_blood_count + 1")
}
result := db.Updates(data)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gormx.ErrRowsAffectedZero
}
return nil
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *customStatisticsPvpModel) FindGreaterByScore(ctx context.Context, score int64, scoreType ScoreType, limit int) ([]UserAndScore, error) {
@ -145,12 +139,33 @@ func (m *customStatisticsPvpModel) FindGreaterByScore(ctx context.Context, score
Where(whereSql, score).
Order(fmt.Sprintf("%s.%s desc", m.table, scoreType)).
Limit(limit).Find(&result).Error
switch err {
case nil:
return result, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
selectResult, err := gormx.WrapSelectResult(err, result)
if err != nil {
return nil, err
}
return selectResult.([]UserAndScore), nil
}
func (m *customStatisticsPvpModel) FindScoreByType(ctx context.Context, tx *gorm.DB, userId int64, scoreType []ScoreType) (map[string]int64, error) {
selectFields := make([]string, 0, len(scoreType))
for _, tmp := range scoreType {
selectFields = append(selectFields, string(tmp))
}
db := gormx.WithTx(ctx, m.DB, tx)
resp := map[string]interface{}{}
err := db.Table(m.table).
Select(selectFields).
Where("user_id = ?", userId).Take(&resp).Error
_, err = gormx.WrapSelectResult(err, resp)
if err != nil {
return nil, err
}
result := make(map[string]int64)
for k, v := range resp {
result[k] = v.(int64)
}
return result, nil
}

@ -70,19 +70,18 @@ func (m *defaultStatisticsPvpModel) Insert(ctx context.Context, tx *gorm.DB, dat
func (m *defaultStatisticsPvpModel) FindOne(ctx context.Context, tx *gorm.DB, userId int64) (*StatisticsPvp, error) {
var resp StatisticsPvp
err := gormx.WithTx(ctx, m.DB, tx).Model(&StatisticsPvp{}).Where("`user_id` = ?", userId).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*StatisticsPvp), nil
}
func (m *defaultStatisticsPvpModel) Update(ctx context.Context, tx *gorm.DB, data *StatisticsPvp) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultStatisticsPvpModel) Delete(ctx context.Context, tx *gorm.DB, userId int64) error {

@ -40,14 +40,11 @@ func (m *customUserCheckInModel) FindThisWeek(ctx context.Context, tx *gorm.DB,
err := db.Model(&UserCheckIn{}).
Where("user_id = ? AND check_in_time >= ", userId, now.Monday()).
Order("check_in_time ASC").Find(resp).Error
switch err {
case nil:
return resp, nil
case gormx.ErrNotFound:
return []UserCheckIn{}, nil
default:
result, err := gormx.WrapSelectResult(err, resp)
if err != nil {
return nil, err
}
return result.([]UserCheckIn), nil
}
func (m *customUserCheckInModel) CheckInToday(ctx context.Context, tx *gorm.DB, userId int64) (bool, error) {

@ -58,19 +58,18 @@ func (m *defaultUserCheckInModel) Insert(ctx context.Context, tx *gorm.DB, data
func (m *defaultUserCheckInModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*UserCheckIn, error) {
var resp UserCheckIn
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserCheckIn{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserCheckIn), nil
}
func (m *defaultUserCheckInModel) Update(ctx context.Context, tx *gorm.DB, data *UserCheckIn) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultUserCheckInModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -65,19 +65,18 @@ func (m *defaultUserGiftModel) Insert(ctx context.Context, tx *gorm.DB, data *Us
func (m *defaultUserGiftModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*UserGift, error) {
var resp UserGift
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserGift{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserGift), nil
}
func (m *defaultUserGiftModel) Update(ctx context.Context, tx *gorm.DB, data *UserGift) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultUserGiftModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -1,51 +0,0 @@
package model
import (
"context"
"git.noahlan.cn/northlan/ntools-go/gorm-zero/gormx"
"gorm.io/gorm"
)
var _ UserGiftPackModel = (*customUserGiftPackModel)(nil)
type (
// UserGiftPackModel is an interface to be customized, add more methods here,
// and implement the added methods in customUserGiftPackModel.
UserGiftPackModel interface {
userGiftPackModel
// FindOneByUserPack 获取用户领取的礼包
FindOneByUserPack(ctx context.Context, tx *gorm.DB, userId int64, packType string) (*UserGiftPack, error)
// AddDrawCount 新增领取次数
AddDrawCount(ctx context.Context, tx *gorm.DB, userId int64, packType string) error
}
PackContent struct {
Integral int64 `json:"integral"` // 奖励积分数量
Title []string `json:"title,optional"` // 称号列表
}
customUserGiftPackModel struct {
*defaultUserGiftPackModel
}
)
// NewUserGiftPackModel returns a model for the database table.
func NewUserGiftPackModel(conn *gorm.DB) UserGiftPackModel {
return &customUserGiftPackModel{
defaultUserGiftPackModel: newUserGiftPackModel(conn),
}
}
func (m *customUserGiftPackModel) FindOneByUserPack(ctx context.Context, tx *gorm.DB, userId int64, packType string) (*UserGiftPack, error) {
var resp UserGiftPack
err := withTx(ctx, m.conn, tx).Model(&UserGiftPack{}).
Where("user_id = ? AND pack_type = ?", userId, packType).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}

@ -1,91 +0,0 @@
// Code generated by goctl. DO NOT EDIT!
package model
import (
"context"
"git.noahlan.cn/northlan/ntools-go/gorm-zero/gormc"
"gorm.io/plugin/optimisticlock"
"strings"
"time"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stringx"
"gorm.io/gorm"
)
var (
userGiftPackFieldNames = builder.RawFieldNames(&UserGiftPack{})
userGiftPackRows = strings.Join(userGiftPackFieldNames, ",")
userGiftPackRowsExpectAutoSet = strings.Join(stringx.Remove(userGiftPackFieldNames, "`create_time`", "`update_time`"), ",")
userGiftPackRowsWithPlaceHolder = strings.Join(stringx.Remove(userGiftPackFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
)
type (
userGiftPackModel interface {
Insert(ctx context.Context, data *UserGiftPack) error
FindOne(ctx context.Context, id int64) (*UserGiftPack, error)
Update(ctx context.Context, data *UserGiftPack) error
Delete(ctx context.Context, id int64) error
}
defaultUserGiftPackModel struct {
conn *gorm.DB
table string
}
UserGiftPack struct {
Id int64 `gorm:"column:id;primaryKey"` // 主键
UserId int64 `gorm:"column:user_id"` // 用户ID
PackType string `gorm:"column:pack_type"` // 礼包类型
PackContent string `gorm:"column:pack_content"` // 礼包内容(冗余)
DrawCount int64 `gorm:"column:draw_count"` // 已领取数目
DrawTime time.Time `gorm:"column:draw_time;default:null"` // 领取时间
Version optimisticlock.Version `gorm:"column:version"` // 乐观锁,版本号
}
)
func newUserGiftPackModel(conn *gorm.DB) *defaultUserGiftPackModel {
return &defaultUserGiftPackModel{
conn: conn,
table: "`user_gift_pack`",
}
}
func (m *defaultUserGiftPackModel) Insert(ctx context.Context, data *UserGiftPack) error {
err := m.conn.WithContext(ctx).Create(&data).Error
return err
}
func (m *defaultUserGiftPackModel) FindOne(ctx context.Context, id int64) (*UserGiftPack, error) {
var resp UserGiftPack
err := m.conn.WithContext(ctx).Model(&UserGiftPack{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserGiftPackModel) Update(ctx context.Context, data *UserGiftPack) error {
err := m.conn.WithContext(ctx).Save(data).Error
return err
}
func (m *defaultUserGiftPackModel) Delete(ctx context.Context, id int64) error {
err := m.conn.WithContext(ctx).Delete(&UserGiftPack{}, id).Error
return err
}
func (m *defaultUserGiftPackModel) tableName() string {
return m.table
}
func (UserGiftPack) TableName() string {
model := newUserGiftPackModel(nil)
return model.tableName()
}

@ -40,13 +40,7 @@ func (m *customUserIntegralModel) UpdateIntegral(ctx context.Context, tx *gorm.D
db := gormx.WithTx(ctx, m.DB, tx)
result := db.Model(&integral).Updates(&UserIntegral{Integral: integral.Integral, Version: optimisticlock.Version{Int64: 1}})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gormx.ErrRowsAffectedZero
}
return nil
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *customUserIntegralModel) ChangeIntegral(ctx context.Context, tx *gorm.DB, userId int64, change int64) (int64, error) {
@ -57,29 +51,29 @@ func (m *customUserIntegralModel) ChangeIntegral(ctx context.Context, tx *gorm.D
if err != nil {
if errors.Is(err, ErrNotFound) {
if change < 0 {
return nerr.NewWithCode(nerr.UserIntegralNotEnoughError)
return nerr.NewError(nerr.UserIntegralNotEnoughError, "用户积分不足")
}
// 用户积分记录不存在,进行插入
if err = m.Insert(ctx, tx, &UserIntegral{
UserId: userId,
Integral: change,
}); err != nil {
return errors.Wrap(err, "插入用户积分失败")
return nerr.NewError(nerr.NewUserIntegralError, "新建用户积分失败")
}
return nil
} else {
return errors.Wrap(err, "获取当前用户积分失败")
return nerr.NewError(nerr.GetUserIntegralError, "获取当前用户积分失败")
}
}
if data.Integral+change < 0 {
return errors.New("用户积分不足")
return nerr.NewError(nerr.UserIntegralNotEnoughError, "用户积分不足")
}
data.Integral += change
if err = m.UpdateIntegral(ctx, tx, data); err != nil {
if errors.Is(err, gormx.ErrRowsAffectedZero) {
return err
}
return errors.Wrap(err, "更新用户积分失败")
return nerr.NewError(nerr.UpdateUserIntegralError, "更新用户积分失败")
}
resp = data.Integral
return nil

@ -61,26 +61,17 @@ func (m *defaultUserIntegralModel) Insert(ctx context.Context, tx *gorm.DB, data
func (m *defaultUserIntegralModel) FindOne(ctx context.Context, tx *gorm.DB, userId int64) (*UserIntegral, error) {
var resp UserIntegral
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserIntegral{}).Where("`user_id` = ?", userId).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserIntegral), nil
}
func (m *defaultUserIntegralModel) Update(ctx context.Context, tx *gorm.DB, data *UserIntegral) error {
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gormx.ErrRowsAffectedZero
}
return nil
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}

@ -59,19 +59,18 @@ func (m *defaultUserModel) Insert(ctx context.Context, tx *gorm.DB, data *User)
func (m *defaultUserModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*User, error) {
var resp User
err := gormx.WithTx(ctx, m.DB, tx).Model(&User{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*User), nil
}
func (m *defaultUserModel) Update(ctx context.Context, tx *gorm.DB, data *User) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultUserModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -1,6 +1,8 @@
package model
import (
"context"
"github.com/pkg/errors"
"gorm.io/gorm"
)
@ -11,6 +13,8 @@ type (
// and implement the added methods in customUserNobilityModel.
UserNobilityModel interface {
userNobilityModel
// RecordNobility 记录贵族信息. 已存在更新,不存在插入
RecordNobility(ctx context.Context, data *UserNobility) error
}
customUserNobilityModel struct {
@ -24,3 +28,27 @@ func NewUserNobilityModel(conn *gorm.DB) UserNobilityModel {
defaultUserNobilityModel: newUserNobilityModel(conn),
}
}
func (m *customUserNobilityModel) RecordNobility(ctx context.Context, data *UserNobility) error {
return m.TransactCtx(ctx, nil, func(tx *gorm.DB) error {
var err error
var dbModel *UserNobility
if dbModel, err = m.FindOne(ctx, tx, data.UserId); err != nil {
if !errors.Is(err, ErrNotFound) {
return err
}
}
if dbModel == nil {
// insert
if err = m.Insert(ctx, tx, data); err != nil {
return err
}
} else {
// update
if err = m.Update(ctx, tx, data); err != nil {
return err
}
}
return nil
})
}

@ -62,19 +62,18 @@ func (m *defaultUserNobilityModel) Insert(ctx context.Context, tx *gorm.DB, data
func (m *defaultUserNobilityModel) FindOne(ctx context.Context, tx *gorm.DB, userId int64) (*UserNobility, error) {
var resp UserNobility
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserNobility{}).Where("`user_id` = ?", userId).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserNobility), nil
}
func (m *defaultUserNobilityModel) Update(ctx context.Context, tx *gorm.DB, data *UserNobility) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultUserNobilityModel) Delete(ctx context.Context, tx *gorm.DB, userId int64) error {

@ -22,15 +22,15 @@ type (
FindEmptyList(ctx context.Context, num int64) ([]UserPlatform, error)
// FindUpdatableList 查询过期需要更新信息的用户
FindUpdatableList(ctx context.Context, duration int64, num int64) ([]UserPlatform, error)
// FindOneForRankByUserId 查找用户信息 用于排行榜展示
FindOneForRankByUserId(ctx context.Context, uid int64) (*UserPlatformForRank, error)
// FindDisplayOneByUserId 查找用户信息,用户展示
FindDisplayOneByUserId(ctx context.Context, uid int64) (*UserPlatformForDisplay, error)
// UpdateNobilityByPUid 更新贵族数据
UpdateNobilityByPUid(ctx context.Context, pUid int64, nobility int64) error
// FindUserIdByPlatform 根据平台与平台用户ID获取系统用户ID
FindUserIdByPlatform(ctx context.Context, platform, pUid string) (int64, error)
}
UserPlatformForRank struct {
UserPlatformForDisplay struct {
UserId int64 // 用户ID
PUname string // 平台用户名
PAvatar string // 平台用户头像地址
@ -59,14 +59,11 @@ func (m *customUserPlatformModel) FindOneByPlatformAndPUid(ctx context.Context,
var resp UserPlatform
err := db.Model(&UserPlatform{}).Where("`platform` = ? AND `p_uid` = ?", platform, pUid).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserPlatform), nil
}
func (m *customUserPlatformModel) FindFullByPlatform(ctx context.Context, tx *gorm.DB, platform, pUid string) (*FullUser, error) {
@ -77,14 +74,11 @@ func (m *customUserPlatformModel) FindFullByPlatform(ctx context.Context, tx *go
Joins("UserIntegral").
Where("platform = ? AND p_uid = ?", platform, pUid).
Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*FullUser), nil
}
func (m *customUserPlatformModel) FindEmptyList(ctx context.Context, num int64) ([]UserPlatform, error) {
@ -93,14 +87,11 @@ func (m *customUserPlatformModel) FindEmptyList(ctx context.Context, num int64)
Table(m.tableName()).
Where("JSON_LENGTH(`p_info`) = 0 LIMIT ?", num).
Find(&resp).Error
switch err {
case nil:
return resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, resp)
if err != nil {
return nil, err
}
return result.([]UserPlatform), nil
}
func (m *customUserPlatformModel) FindUpdatableList(ctx context.Context, duration int64, num int64) ([]UserPlatform, error) {
@ -109,31 +100,25 @@ func (m *customUserPlatformModel) FindUpdatableList(ctx context.Context, duratio
Table(m.tableName()).
Where("`update_time` < (NOW() - INTERVAL ? HOUR) LIMIT ?", duration, num).
Find(&resp).Error
switch err {
case nil:
return resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, resp)
if err != nil {
return nil, err
}
return result.([]UserPlatform), nil
}
func (m *customUserPlatformModel) FindOneForRankByUserId(ctx context.Context, uid int64) (*UserPlatformForRank, error) {
var resp UserPlatformForRank
func (m *customUserPlatformModel) FindDisplayOneByUserId(ctx context.Context, uid int64) (*UserPlatformForDisplay, error) {
var resp UserPlatformForDisplay
err := gormx.WithTx(ctx, m.DB, nil).
Table(m.table).
Select(fmt.Sprintf("%s.user_id, %s.p_uname, %s.p_avatar", m.table, m.table, m.table)).
Where("user_id = ?", uid).
Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserPlatformForDisplay), nil
}
func (m *customUserPlatformModel) UpdateNobilityByPUid(ctx context.Context, pUid int64, nobility int64) error {
@ -149,12 +134,9 @@ func (m *customUserPlatformModel) FindUserIdByPlatform(ctx context.Context, plat
Table(m.table).
Select(fmt.Sprintf("%s.user_id", m.table)).
Where("platform = ? AND p_uid = ?", platform, pUid).Take(&resp).Error
switch err {
case nil:
return resp, nil
case gormx.ErrNotFound:
return 0, ErrNotFound
default:
_, err = gormx.WrapSelectResult(err, resp)
if err != nil {
return 0, err
}
return resp, nil
}

@ -67,32 +67,28 @@ func (m *defaultUserPlatformModel) Insert(ctx context.Context, tx *gorm.DB, data
func (m *defaultUserPlatformModel) FindOne(ctx context.Context, tx *gorm.DB, id int64) (*UserPlatform, error) {
var resp UserPlatform
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserPlatform{}).Where("`id` = ?", id).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserPlatform), nil
}
func (m *defaultUserPlatformModel) FindOneByPlatformPUid(ctx context.Context, tx *gorm.DB, platform string, pUid string) (*UserPlatform, error) {
var resp UserPlatform
err := gormx.WithTx(ctx, m.DB, tx).Model(&UserPlatform{}).Where("`platform` = ? and `p_uid` = ?", platform, pUid).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
result, err := gormx.WrapSelectResult(err, &resp)
if err != nil {
return nil, err
}
return result.(*UserPlatform), nil
}
func (m *defaultUserPlatformModel) Update(ctx context.Context, tx *gorm.DB, data *UserPlatform) error {
err := gormx.WithTx(ctx, m.DB, tx).Save(data).Error
return err
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}
func (m *defaultUserPlatformModel) Delete(ctx context.Context, tx *gorm.DB, id int64) error {

@ -17,10 +17,13 @@ DB:
Kafka:
UserNotify:
Addr: [ "127.0.0.1:9093" ]
Topic: "notify-user"
Topic: "notify-user-dev"
RankUpdate:
Addr: [ "127.0.0.1:9093" ]
Topic: "rank-update"
Topic: "rank-update-dev"
RewardPool:
Addr: [ "127.0.0.1:9093" ]
Topic: "rewardPool-dev"
UserRetriever:
Enabled: false
UpdateDuration: 720 # 720 hours = 30 Day = 1 Month
@ -43,26 +46,34 @@ GiftCollector:
Platforms: [ "bilibili" ]
Cron:
CollectGift: "0 0 0/6 * * ?" # 每隔6小时执行一次
Coin:
# RMB到弹币的转换
RMBToCoin: 100
# 平台礼物到RMB的转换
GiftToRMB:
bilibili: 0.001
# 平台免费礼物到弹币的转换
FreeToCoin:
bilibili: 0.00025
Integral:
# 签到积分配置
CheckIn:
# 签到积分 一周 0(周日) 1 2 3 4 5 6
Points: [ 10000,2500,2500,3500,5000,6500,8000 ]
Points: [ 15000,3000,3500,5000,6500,8000,10000 ]
Critical: 0.15 # 签到积分暴击率
CriticalRadio: [ 1.0, 1.0, 1.2, 1.5, 1.8 ] # 暴击倍率
CriticalRadio: [ 1.3, 1.5, 1.8, 2.0, 2.0, 3.0 ] # 暴击倍率
BattleReport:
GeneralIntegral: 1000 # 名将积分
WinRadio: 0.02 # 伤害量 1/50
LostRadio: 0.008 # 伤害量 1/120
# RMB到积分的转换
RMBToIntegral: 1000
# 平台礼物到RMB的转换
GiftToRMB:
bilibili: 0.001
# 平台免费礼物到积分的转换
FreeToIntegral:
bilibili: 0.00025
GiftPack:
RewardPool:
InitReward: 0
Ratio: 0.7
BattleRatio: 0.75
GiftRatio: 0.5
ReturnRatio: 0.8
WelfareRatio: 0.3
GiftPackMap:
- PackType: starter
PackName: 新手礼包
Condition:

@ -0,0 +1,132 @@
package integral_manager
import (
"context"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
"live-service/app/user_center/model"
"live-service/app/user_center/rpc/internal/common/reward_pool"
"live-service/app/user_center/rpc/pb"
"live-service/common/nerr"
)
type (
Manager struct {
cfg Config // 配置
userIntegralModel model.UserIntegralModel
rewardPoolManager *reward_pool.PoolManager
logx.Logger
}
Config struct {
GiftRatio float64
}
ChangeIntegralReq struct {
BattleId int64 // 战局ID
UserId int64 // 用户ID
Change int64 // 变化量(负数为减扣)
Type pb.IntegralType // 积分类型
}
ChangeIntegralResp struct {
BattleId int64 // 战局ID
UserId int64 // 用户ID
Change int64 // 变化量(负数为减扣)
Integral int64 // 剩余积分
}
)
func NewIntegralManager(userIntegralModel model.UserIntegralModel, rewardPoolManager *reward_pool.PoolManager) *Manager {
return &Manager{
userIntegralModel: userIntegralModel,
rewardPoolManager: rewardPoolManager,
Logger: logx.WithContext(context.Background()),
}
}
func (m *Manager) GetUserIntegral(ctx context.Context, userId int64) (int64, error) {
resp, err := m.userIntegralModel.FindOne(ctx, nil, userId)
if err != nil {
return 0, err
}
return resp.Integral, err
}
func (m *Manager) TransferIntegral(ctx context.Context, req *pb.TransferUserIntegralReq) *pb.TransferUserIntegralResp {
resp := &pb.TransferUserIntegralResp{
UserId: req.UserId,
TargetUserId: req.TargetUserId,
}
if err := m.userIntegralModel.TransactCtx(ctx, nil, func(tx *gorm.DB) error {
if req.UserId == 0 {
return nerr.NewError(nerr.RequestParamError, "源用户ID为空")
}
if req.TargetUserId == 0 {
return nerr.NewError(nerr.RequestParamError, "目标用户ID为空")
}
integral, err := m.userIntegralModel.ChangeIntegral(ctx, tx, req.UserId, -req.Transfer)
if err != nil {
return err
}
targetIntegral, err := m.userIntegralModel.ChangeIntegral(ctx, tx, req.TargetUserId, req.Transfer)
if err != nil {
return err
}
resp.Code = int32(nerr.OK)
resp.Msg = "转移成功"
resp.UserIntegral = integral
resp.TargetUserIntegral = targetIntegral
return nil
}); err != nil {
if e, ok := err.(*nerr.Error); ok {
resp.Code = int32(e.Code)
resp.Msg = e.Msg
} else {
resp.Code = int32(nerr.ServerCommonError)
resp.Msg = "转移失败,未知原因"
}
}
return resp
}
func (m *Manager) ChangeIntegral(ctx context.Context, req *ChangeIntegralReq, rewardPool bool) (*ChangeIntegralResp, error) {
integral, err := m.userIntegralModel.ChangeIntegral(ctx, nil, req.UserId, req.Change)
if err != nil {
return nil, err
}
if req.BattleId != 0 && rewardPool {
m.rewardPoolManager.Pool(req.BattleId).Add(req.UserId, req.Change, req.Type)
}
return &ChangeIntegralResp{
UserId: req.UserId,
Change: req.Change,
Integral: integral,
}, nil
}
func (m *Manager) ChangeIntegralBatch(ctx context.Context, req []ChangeIntegralReq, rewardPool bool) (map[int64]ChangeIntegralResp, error) {
resp := make(map[int64]ChangeIntegralResp)
if err := m.userIntegralModel.TransactCtx(ctx, nil, func(tx *gorm.DB) error {
for _, item := range req {
integral, err := m.userIntegralModel.ChangeIntegral(ctx, tx, item.UserId, item.Change)
if err != nil {
return err
}
resp[item.UserId] = ChangeIntegralResp{
BattleId: item.BattleId,
UserId: item.UserId,
Change: item.Change,
Integral: integral,
}
}
return nil
}); err != nil {
return resp, err
}
// 奖池
for _, item := range req {
if item.BattleId != 0 && rewardPool {
m.rewardPoolManager.Pool(item.BattleId).Add(item.UserId, item.Change, item.Type)
}
}
return resp, nil
}

@ -0,0 +1,295 @@
package reward_pool
import (
"git.noahlan.cn/northlan/ntools-go/kafka"
"github.com/shopspring/decimal"
pbMq "live-service/app/pb/mq"
"live-service/app/user_center/rpc/pb"
"sort"
"sync"
)
type (
pool struct {
id int64 // 奖池ID(对局ID)
initReward int64 // 初始奖池
battleReward int64 // 积分奖池
giftReward int64 // 礼物奖池
otherReward int64 // 其它奖池
userBattleReward map[int64]int64 // 用户战斗积分[暴兵|造墙|技能 等等],用于计算分配比例
userGiftReward map[int64]int64 // 用户送礼积分,扩充奖池
userOtherReward map[int64]int64 // 用户其它积分[抽奖|兑换 等等],扩充奖池
manager *PoolManager // 管理器
mutex sync.RWMutex // 锁
}
PoolManager struct {
welfarePool int64 // 福利池,开服重置
pools map[int64]*pool // 奖池
initReward int64 // 初始奖池
ratio Ratio // 比例
producer *kafka.Producer // kafka
mutex sync.Mutex
}
Ratio struct {
Ratio float64 // 奖池比例
BattleRatio float64 // 战斗积分投入奖池比例
GiftRatio float64 // 礼物算作奖池比例
ReturnRatio float64 // 回收比例
WelfareRatio float64 // 从奖金扣除福利比例
}
// DrawResult 结算结果
DrawResult struct {
UserReturns map[int64]int64 // 用户回收积分,投放多少回收多少,战败方不回收
DrawRewards map[int64]int64 // 用户瓜分奖池,根据回收后的剩余奖池,逐级投放
AddonWelfare int64 // 本次结算添加的福利
}
// DrawRequest 结算请求
DrawRequest struct {
UserId int64 // 用户ID
Position int32 // 排名
Ratio float64 // 其它因素计算的比例
}
)
// NewRewardPoolManager 构建奖池
func NewRewardPoolManager(initReward int64, ratio Ratio, producer *kafka.Producer) *PoolManager {
return &PoolManager{
initReward: initReward,
pools: make(map[int64]*pool),
producer: producer,
ratio: ratio,
}
}
// Pool 创建或获取 pool
func (p *PoolManager) Pool(battleId int64) *pool {
resp, ok := p.pools[battleId]
if !ok {
resp = newRewardPool(battleId, p.initReward, p)
p.pools[battleId] = resp
}
return resp
}
// Draw 结算
func (p *PoolManager) Draw(battleId int64, req []DrawRequest) *DrawResult {
result := p.Pool(battleId).draw(req)
p.AddWelfare(result.AddonWelfare)
// 移除奖池
p.Remain(battleId)
// 变动通知
_ = p.producer.SendMessageAsync(&pbMq.MqRewardPool{
WelfarePool: p.welfarePool,
BattleId: battleId,
InitReward: 0,
GiftReward: 0,
BattleReward: 0,
OtherReward: 0,
AllRewards: 0,
})
return result
}
// Remain 移除 pool
func (p *PoolManager) Remain(battleId int64) {
p.mutex.Lock()
defer p.mutex.Unlock()
if _, ok := p.pools[battleId]; ok {
delete(p.pools, battleId)
}
}
func (p *PoolManager) AddWelfare(welfare int64) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.welfarePool += welfare
}
func newRewardPool(battleId int64, initReward int64, manager *PoolManager) *pool {
return &pool{
id: battleId,
initReward: initReward,
userBattleReward: make(map[int64]int64),
userGiftReward: make(map[int64]int64),
userOtherReward: make(map[int64]int64),
manager: manager,
}
}
// draw 奖池结算
func (p *pool) draw(req []DrawRequest) *DrawResult {
p.mutex.Lock()
defer p.mutex.Unlock()
sort.SliceStable(req, func(i, j int) bool {
return req[i].Position < req[j].Position
})
resp := DrawResult{
UserReturns: make(map[int64]int64),
DrawRewards: make(map[int64]int64),
}
remainRewards := p.rewards()
var addonWelfare int64 // 福利池
// 获胜方战斗总投入
var winBattleRewards int64
for _, item := range req {
// 用户回收战斗积分
if reward, ok := p.userBattleReward[item.UserId]; ok {
returnsReward := decimal.NewFromInt(reward).Mul(decimal.NewFromFloat(p.manager.ratio.ReturnRatio)).Round(0).IntPart()
resp.UserReturns[item.UserId] = returnsReward // 玩家回收,比例回收
remainRewards -= reward // 奖池回收,完全回收
addonWelfare += reward - returnsReward // 玩家比例回收,奖池完全回收,多余奖金加入福利池
winBattleRewards += reward // 获胜方战斗总投入
//fmt.Printf("用户 %d 回收战斗积分 %d\n", item.UserId, reward)
}
}
//fmt.Printf("剩余奖池: %d\n", remainRewards)
//fmt.Printf("获胜方战斗总投入 %d\n", winBattleRewards)
// 福利池抽取
{
tmp := decimal.NewFromInt(remainRewards).Mul(decimal.NewFromFloat(p.manager.ratio.WelfareRatio)).Round(0).IntPart()
addonWelfare += tmp
remainRewards -= tmp
}
// TODO 奖池分的其余用途
// 用户瓜分奖池
for _, item := range req {
// 计算战斗积分分配比例
var ratio float64
if reward, ok := p.userBattleReward[item.UserId]; ok {
ratio, _ = decimal.NewFromInt(reward).Div(decimal.NewFromInt(winBattleRewards)).Round(2).Float64()
}
// 其它因素计算比例
var poolRatio float64
if item.Ratio == 0 {
poolRatio = ratio * 1.0
} else {
poolRatio = ratio * p.manager.ratio.Ratio
}
ratio, _ = decimal.NewFromFloat(poolRatio).Add(decimal.NewFromFloat(item.Ratio * (1.0 - p.manager.ratio.Ratio))).Round(2).Float64()
//fmt.Printf("用户: %d 瓜分比例 %v\n", item.UserId, ratio)
reward := decimal.NewFromInt(remainRewards).Mul(decimal.NewFromFloat(ratio)).Round(0).IntPart()
resp.DrawRewards[item.UserId] = reward
remainRewards -= reward
//fmt.Printf("用户: %d 瓜分奖金 %d\n", item.UserId, reward)
//fmt.Printf("剩余奖池: %d\n", remainRewards)
}
addonWelfare += remainRewards
//fmt.Printf("积分 %d 加入福利池\n", remainRewards)
resp.AddonWelfare = addonWelfare
return &resp
}
// Rewards 获取当前总积分
func (p *pool) Rewards() int64 {
p.mutex.RLock()
defer p.mutex.RUnlock()
return p.rewards()
}
func (p *pool) rewards() int64 {
return p.initReward + p.battleReward + p.giftReward + p.otherReward
}
// Add 积分加入奖池
func (p *pool) Add(userId, val int64, integralType pb.IntegralType) int64 {
switch integralType {
case pb.IntegralType_Battle:
p.addBattle(userId, val)
case pb.IntegralType_Gift:
p.addGift(userId, val)
case pb.IntegralType_Other:
p.addOther(userId, val)
default:
p.addOther(userId, val)
}
result := p.Rewards()
// 变动通知
_ = p.manager.producer.SendMessageAsync(&pbMq.MqRewardPool{
WelfarePool: p.manager.initReward,
BattleId: p.id,
InitReward: p.initReward,
GiftReward: p.giftReward,
BattleReward: p.battleReward,
OtherReward: p.otherReward,
AllRewards: result,
})
return result
}
func (p *pool) addBattle(userId, val int64) int64 {
p.mutex.Lock()
defer p.mutex.Unlock()
if val == 0 || val > 0 {
return p.battleReward
}
val = -val
val = decimal.NewFromInt(val).Mul(decimal.NewFromFloat(p.manager.ratio.BattleRatio)).Round(0).IntPart()
reward, ok := p.userBattleReward[userId]
if !ok {
reward = val
p.userBattleReward[userId] = reward
} else {
p.userBattleReward[userId] = reward + val
}
p.battleReward += val
//fmt.Printf("用户 %d 战斗积分 %d 加入奖池\n", userId, val)
return p.battleReward
}
func (p *pool) addGift(userId, val int64) int64 {
p.mutex.Lock()
defer p.mutex.Unlock()
if val == 0 || val < 0 {
return p.giftReward
}
val = decimal.NewFromInt(val).Mul(decimal.NewFromFloat(p.manager.ratio.GiftRatio)).Round(0).IntPart()
reward, ok := p.userGiftReward[userId]
if !ok {
reward = val
p.userGiftReward[userId] = reward
} else {
p.userGiftReward[userId] = reward + val
}
p.giftReward += val
//fmt.Printf("用户 %d 礼物积分 %d 加入奖池\n", userId, val)
return p.giftReward
}
func (p *pool) addOther(userId, val int64) int64 {
p.mutex.Lock()
defer p.mutex.Unlock()
if val == 0 || val > 0 {
return p.otherReward
}
val = -val
reward, ok := p.userOtherReward[userId]
if !ok {
reward = val
p.userOtherReward[userId] = reward
} else {
p.userOtherReward[userId] = reward + val
}
p.otherReward += val
//fmt.Printf("用户 %d 其它消耗积分 %d 加入奖池\n", userId, val)
return p.otherReward
}

@ -44,6 +44,7 @@ type (
Kafka struct {
UserNotify Kafka // 用户信息通知队列
RankUpdate Kafka // 排行榜更新通知队列
RewardPool Kafka // 奖池通知
}
UserRetriever struct {
Enabled bool // 是否开启
@ -74,6 +75,12 @@ type (
CollectGift string
}
}
// 弹币
Coin struct {
RMBToCoin float64 // RMB到弹币的转换
GiftToRMB map[string]float64 // 平台礼物到RMB的转换
FreeToIntegral map[string]float64 // 平台免费礼物到弹币的转换
}
Integral struct {
// CheckIn 签到
CheckIn struct {
@ -87,9 +94,15 @@ type (
WinRadio float64 // 获胜方积分因子 乘法
LostRadio float64 // 失败方积分因子 乘法
}
RMBToIntegral float64 // RMB到积分的转换
GiftToRMB map[string]float64 // 平台礼物到RMB的转换
FreeToIntegral map[string]float64 // 平台免费礼物到积分的转换
// 奖池
RewardPool struct {
InitReward int64 // 奖池初始积分
Ratio float64 // 奖池结算比例
GiftRatio float64 // 礼物算入奖池比例
BattleRatio float64 // 战斗消耗积分算入奖池比例
ReturnRatio float64 // 回收积分比例
WelfareRatio float64 // 福利池从奖金扣除比例
}
}
// GiftPack 礼包配置
GiftPackMap []GiftPack

@ -0,0 +1,30 @@
package draw_pool
import (
"context"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type IncreaseWelfareLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewIncreaseWelfareLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IncreaseWelfareLogic {
return &IncreaseWelfareLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *IncreaseWelfareLogic) IncreaseWelfare(in *pb.IncreaseWelfareReq) (*pb.Empty, error) {
// todo: add your logic here and delete this line
return &pb.Empty{}, nil
}

@ -2,10 +2,13 @@ package gift
import (
"context"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"live-service/app/user_center/model"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
"live-service/common/nerr"
"live-service/common/timex"
)
type UserBuyNobilityLogic struct {
@ -23,30 +26,43 @@ func NewUserBuyNobilityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *U
}
// UserBuyNobility 用户购买贵族
// 1. 记录送礼
// 2. 新增积分
// 3. 修改贵族
// 1. 记录送礼 + 新增积分
// 2. 修改贵族
func (l *UserBuyNobilityLogic) UserBuyNobility(in *pb.UserBuyNobilityReq) (*pb.UserBuyNobilityResp, error) {
// TODO 未完成
//// 记录送礼信息
//{
// dbUserGift := &model.UserGift{
// Id: uuid.NextId(),
// UserId: in.UserId,
// Platform: in.Platform,
// RoomId: in.RoomId,
// GiftId: strconv.FormatInt(in.GiftId, 10),
// GiftName: in.GiftName,
// Num: in.Num,
// }
// if in.IsPaid {
// dbUserGift.Price = in.Price
// } else {
// dbUserGift.FreePrice = in.Price
// }
// if err := l.svcCtx.UserGiftModel.Insert(l.ctx, nil, dbUserGift); err != nil {
// l.Logger.Errorf("记录用户[%d]送礼信息 [%d:%s:%d] 失败,操作继续...", in.UserId, in.GiftId, in.GiftName, in.Num)
// }
//}
return &pb.UserBuyNobilityResp{}, nil
// 记录送礼信息
sendGiftLogic := NewUserSendGiftLogic(l.ctx, l.svcCtx)
integralChanged, err := sendGiftLogic.UserSendGift(&pb.UserSendGiftReq{
Platform: in.Platform,
UserId: in.UserId,
PUid: in.PUid,
RoomId: in.RoomId,
GiftId: in.GiftId,
GiftName: in.GiftName,
Num: in.Num,
Price: in.Price,
IsPaid: true,
BattleId: in.BattleId,
})
if err != nil {
return nil, err
}
// 修改贵族
err = l.svcCtx.UserNobilityModel.RecordNobility(l.ctx, &model.UserNobility{
UserId: in.UserId,
NobilityLevel: in.Level,
Forever: false,
StartTime: timex.TimestampToTime(in.StartTime),
EndTime: timex.TimestampToTime(in.EndTime),
})
if err != nil {
return nil, errors.Wrapf(nerr.NewError(nerr.GiftNobilityUpdateErr, "更新贵族信息失败"), "更新贵族信息失败 err:%v", err)
}
return &pb.UserBuyNobilityResp{
Integral: &pb.ChangeIntegralResp{
UserId: integralChanged.Integral.UserId,
Change: integralChanged.Integral.Change,
Integral: integralChanged.Integral.Integral,
},
}, nil
}

@ -4,6 +4,7 @@ import (
"context"
"git.noahlan.cn/northlan/ntools-go/uuid"
"live-service/app/user_center/model"
"live-service/app/user_center/rpc/internal/common/integral_manager"
"live-service/app/user_center/rpc/internal/logic/gift_collect"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
@ -61,14 +62,19 @@ func (l *UserSendGiftLogic) UserSendGift(in *pb.UserSendGiftReq) (*pb.UserSendGi
addonIntegral = calcIntegral(l.svcCtx.Config, in.Platform, tmpData.IsPaid, tmpData.Price, in.Num)
}
}
newIntegral, err := l.svcCtx.UserIntegralModel.ChangeIntegral(l.ctx, nil, in.UserId, addonIntegral)
newIntegral, err := l.svcCtx.IntegralManager.ChangeIntegral(l.ctx, &integral_manager.ChangeIntegralReq{
BattleId: in.BattleId,
UserId: in.UserId,
Change: addonIntegral,
Type: pb.IntegralType_Gift,
}, true)
if err != nil {
return nil, err
}
resp.Integral = &pb.ChangeIntegralResp{
UserId: in.UserId,
Change: addonIntegral,
Integral: newIntegral,
Change: newIntegral.Change,
Integral: newIntegral.Integral,
}
}
return resp, nil

@ -3,6 +3,7 @@ package integral
import (
"context"
"github.com/pkg/errors"
"live-service/app/user_center/rpc/internal/common/integral_manager"
"live-service/common/nerr"
"live-service/app/user_center/rpc/internal/svc"
@ -25,16 +26,21 @@ func NewChangeIntegralLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Ch
}
}
// ChangeIntegral 新增用户积分
// ChangeIntegral 更改用户积分
func (l *ChangeIntegralLogic) ChangeIntegral(in *pb.ChangeIntegralReq) (*pb.ChangeIntegralResp, error) {
integral, err := l.svcCtx.UserIntegralModel.ChangeIntegral(l.ctx, nil, in.UserId, in.Change)
integral, err := l.svcCtx.IntegralManager.ChangeIntegral(l.ctx, &integral_manager.ChangeIntegralReq{
BattleId: in.BattleId,
UserId: in.UserId,
Change: in.Change,
Type: in.IntegralType,
}, true)
if err != nil {
return nil, errors.Wrapf(nerr.NewWithErr(err), "记录积分-事务执行失败, err:%+v", err)
return nil, errors.Wrapf(nerr.NewWithErr(err), "记录积分失败, err:%+v", err)
}
return &pb.ChangeIntegralResp{
UserId: in.UserId,
Change: in.Change,
Integral: integral,
Integral: integral.Integral,
}, nil
}

@ -0,0 +1,41 @@
package integral
import (
"context"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
"live-service/common/nerr"
"github.com/zeromicro/go-zero/core/logx"
)
type TransferUserIntegralLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewTransferUserIntegralLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransferUserIntegralLogic {
return &TransferUserIntegralLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// TransferUserIntegral 转移积分
func (l *TransferUserIntegralLogic) TransferUserIntegral(in *pb.TransferUserIntegralReq) (*pb.TransferUserIntegralResp, error) {
transResp := l.svcCtx.IntegralManager.TransferIntegral(l.ctx, in)
if transResp.Code == int32(nerr.OK) {
// 获取 username
if tmp, err := l.svcCtx.UserPlatformModel.FindDisplayOneByUserId(l.ctx, transResp.UserId); err == nil {
transResp.Uname = tmp.PUname
transResp.Avatar = tmp.PAvatar
}
if tmp, err := l.svcCtx.UserPlatformModel.FindDisplayOneByUserId(l.ctx, transResp.TargetUserId); err == nil {
transResp.TargetUname = tmp.PUname
transResp.TargetAvatar = tmp.PAvatar
}
}
return transResp, nil
}

@ -27,18 +27,20 @@ type (
svcCtx *svc.ServiceContext
// 实时排行榜(定期读取,半实时)
damageRank *zset.ZSetInt
deDamageRank *zset.ZSetInt
generalRank *zset.ZSetInt
deGeneralRank *zset.ZSetInt
killUnitRank *zset.ZSetInt
deKillUnitRank *zset.ZSetInt
killPlayerRank *zset.ZSetInt
deKillPlayerRank *zset.ZSetInt
winRank *zset.ZSetInt
lostRank *zset.ZSetInt
firstBloodRank *zset.ZSetInt
deFirstBloodRank *zset.ZSetInt
rankByTypeMap map[pb.RankType]*zset.ZSetInt
//damageRank *zset.ZSetInt
//deDamageRank *zset.ZSetInt
//generalRank *zset.ZSetInt
//deGeneralRank *zset.ZSetInt
//killUnitRank *zset.ZSetInt
//deKillUnitRank *zset.ZSetInt
//killPlayerRank *zset.ZSetInt
//deKillPlayerRank *zset.ZSetInt
//winRank *zset.ZSetInt
//lostRank *zset.ZSetInt
//firstBloodRank *zset.ZSetInt
//deFirstBloodRank *zset.ZSetInt
// 用户数据表内存缓存
userCache *lru.Cache
@ -51,21 +53,23 @@ func InitRankJob(svcCtx *svc.ServiceContext) {
}
uc, _ := lru.New(4*model.MaxRankN + 1000)
Service = &Job{
ctx: context.Background(),
svcCtx: svcCtx,
damageRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
deDamageRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
generalRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
deGeneralRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
killUnitRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
deKillUnitRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
killPlayerRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
deKillPlayerRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
winRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
lostRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
firstBloodRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
deFirstBloodRank: zset.NewZSetInt(lessFunc, model.MaxRankN),
userCache: uc,
ctx: context.Background(),
svcCtx: svcCtx,
rankByTypeMap: map[pb.RankType]*zset.ZSetInt{
pb.RankType_Damage: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_DeDamage: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_General: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_DeGeneral: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_KillUnit: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_DeKillUnit: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_KillPlayer: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_DeKillPlayer: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_Win: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_Lost: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_FirstBlood: zset.NewZSetInt(lessFunc, model.MaxRankN),
pb.RankType_DeFirstBlood: zset.NewZSetInt(lessFunc, model.MaxRankN),
},
userCache: uc,
}
if !svcCtx.Config.Rank.Enabled {
@ -98,40 +102,53 @@ func (j *Job) initJob() {
// job read and update
c := cron.New()
_, _ = c.AddFunc(cfg.Cron.Update, func() {
go j.readAndUpdate(model.RankTypeDamage)
go j.readAndUpdate(model.RankTypeDeDamage)
go j.readAndUpdate(model.RankTypeGeneral)
go j.readAndUpdate(model.RankTypeDeGeneral)
go j.readAndUpdate(model.RankTypeKillUnit)
go j.readAndUpdate(model.RankTypeDeKillUnit)
go j.readAndUpdate(model.RankTypeKillPlayer)
go j.readAndUpdate(model.RankTypeDeKillPlayer)
go j.readAndUpdate(model.RankTypeWin)
go j.readAndUpdate(model.RankTypeLost)
go j.readAndUpdate(model.RankTypeFirstBlood)
go j.readAndUpdate(model.RankTypeDeFirstBlood)
go j.readAndUpdate(pb.RankType_Damage)
go j.readAndUpdate(pb.RankType_DeDamage)
go j.readAndUpdate(pb.RankType_General)
go j.readAndUpdate(pb.RankType_DeGeneral)
go j.readAndUpdate(pb.RankType_KillUnit)
go j.readAndUpdate(pb.RankType_DeKillUnit)
go j.readAndUpdate(pb.RankType_KillPlayer)
go j.readAndUpdate(pb.RankType_DeKillPlayer)
go j.readAndUpdate(pb.RankType_Win)
go j.readAndUpdate(pb.RankType_Lost)
go j.readAndUpdate(pb.RankType_FirstBlood)
go j.readAndUpdate(pb.RankType_DeFirstBlood)
})
// persistence
_, _ = c.AddFunc(cfg.Cron.Persistence, func() {
go j.persistence(model.RankTypeDamage)
go j.persistence(model.RankTypeDeDamage)
go j.persistence(model.RankTypeGeneral)
go j.persistence(model.RankTypeDeGeneral)
go j.persistence(model.RankTypeKillUnit)
go j.persistence(model.RankTypeDeKillUnit)
go j.persistence(model.RankTypeKillPlayer)
go j.persistence(model.RankTypeDeKillPlayer)
go j.persistence(model.RankTypeWin)
go j.persistence(model.RankTypeLost)
go j.persistence(model.RankTypeFirstBlood)
go j.persistence(model.RankTypeDeFirstBlood)
go j.persistence(pb.RankType_Damage)
go j.persistence(pb.RankType_DeDamage)
go j.persistence(pb.RankType_General)
go j.persistence(pb.RankType_DeGeneral)
go j.persistence(pb.RankType_KillUnit)
go j.persistence(pb.RankType_DeKillUnit)
go j.persistence(pb.RankType_KillPlayer)
go j.persistence(pb.RankType_DeKillPlayer)
go j.persistence(pb.RankType_Win)
go j.persistence(pb.RankType_Lost)
go j.persistence(pb.RankType_FirstBlood)
go j.persistence(pb.RankType_DeFirstBlood)
})
c.Start()
}
func (j *Job) RangeRankByType(rankType, topN int32) *pb.RankPvpResp {
func (j *Job) RankByScore(rankType pb.RankType, score int32) int32 {
rankZSet, _, err := j.getRankInstanceAndScoreType(rankType)
if err != nil {
return 0
}
rank := rankZSet.RangeByScore(score, score)
if len(rank) > 0 {
return int32(rankZSet.Rank(rank[0]))
}
return 0
}
func (j *Job) RangeRankByType(rankType pb.RankType, topN int32) *pb.RankPvpResp {
result := &pb.RankPvpResp{
Type: rankType,
Type: int32(rankType),
}
rankZSet, _, err := j.getRankInstanceAndScoreType(rankType)
if err != nil {
@ -158,7 +175,7 @@ func (j *Job) RangeRankByType(rankType, topN int32) *pb.RankPvpResp {
Avatar: cached.Avatar,
}
} else {
dbUser, err := j.svcCtx.UserPlatformModel.FindOneForRankByUserId(j.ctx, uid)
dbUser, err := j.svcCtx.UserPlatformModel.FindDisplayOneByUserId(j.ctx, uid)
if err != nil {
item = pb.RankPvpResp_Item{
Uid: uid,
@ -178,8 +195,8 @@ func (j *Job) RangeRankByType(rankType, topN int32) *pb.RankPvpResp {
return result
}
func (j *Job) initByType(rankType int32) {
list, err := j.svcCtx.RankPvpModel.RankListByType(j.ctx, rankType, model.MaxRankN)
func (j *Job) initByType(rankType pb.RankType) {
list, err := j.svcCtx.RankPvpModel.RankListByType(j.ctx, int64(rankType), model.MaxRankN)
if err != nil {
return
}
@ -198,7 +215,7 @@ func (j *Job) initByType(rankType int32) {
}
}
func (j *Job) readAndUpdate(rankType int32) {
func (j *Job) readAndUpdate(rankType pb.RankType) {
rankZSet, scoreType, err := j.getRankInstanceAndScoreType(rankType)
if err != nil {
return
@ -225,7 +242,7 @@ func (j *Job) readAndUpdate(rankType int32) {
for _, s := range byScore {
// 缓存用户信息
if ok := j.userCache.Contains(s.UserId); !ok {
if dbUser, err := j.svcCtx.UserPlatformModel.FindOneForRankByUserId(j.ctx, s.UserId); err == nil {
if dbUser, err := j.svcCtx.UserPlatformModel.FindDisplayOneByUserId(j.ctx, s.UserId); err == nil {
j.userCache.Add(dbUser.UserId, CachedUserInfo{
UserId: dbUser.UserId,
Username: dbUser.PUname,
@ -242,7 +259,7 @@ func (j *Job) readAndUpdate(rankType int32) {
}
}
func (j *Job) persistence(rankType int32) {
func (j *Job) persistence(rankType pb.RankType) {
rankZSet, _, err := j.getRankInstanceAndScoreType(rankType)
if err != nil {
return
@ -262,54 +279,17 @@ func (j *Job) persistence(rankType int32) {
if len(dbModel) > 0 {
// 简单避免死锁
time.Sleep(1 * time.Second)
if err = j.svcCtx.RankPvpModel.UpdateRank(j.ctx, rankType, dbModel); err != nil {
if err = j.svcCtx.RankPvpModel.UpdateRank(j.ctx, int64(rankType), dbModel); err != nil {
logx.Error("更新排行榜错误", err)
return
}
}
}
func (j *Job) getRankInstanceAndScoreType(rankType int32) (*zset.ZSetInt, model.ScoreType, error) {
func (j *Job) getRankInstanceAndScoreType(rankType pb.RankType) (*zset.ZSetInt, model.ScoreType, error) {
var rankZSet *zset.ZSetInt
scoreType := model.ScoreTypeDamage
switch rankType {
case model.RankTypeDamage:
rankZSet = j.damageRank
scoreType = model.ScoreTypeDamage
case model.RankTypeDeDamage:
rankZSet = j.deDamageRank
scoreType = model.ScoreTypeDeDamage
case model.RankTypeGeneral:
rankZSet = j.generalRank
scoreType = model.ScoreTypeGeneral
case model.RankTypeDeGeneral:
rankZSet = j.deGeneralRank
scoreType = model.ScoreTypeDeGeneral
case model.RankTypeKillUnit:
rankZSet = j.killUnitRank
scoreType = model.ScoreTypeKillUnit
case model.RankTypeDeKillUnit:
rankZSet = j.deKillUnitRank
scoreType = model.ScoreTypeDeKillUnit
case model.RankTypeKillPlayer:
rankZSet = j.killPlayerRank
scoreType = model.ScoreTypeKillPlayer
case model.RankTypeDeKillPlayer:
rankZSet = j.deKillPlayerRank
scoreType = model.ScoreTypeDeKillPlayer
case model.RankTypeWin:
rankZSet = j.winRank
scoreType = model.ScoreTypeWin
case model.RankTypeLost:
rankZSet = j.lostRank
scoreType = model.ScoreTypeLost
case model.RankTypeFirstBlood:
rankZSet = j.firstBloodRank
scoreType = model.ScoreTypeFirstBlood
case model.RankTypeDeFirstBlood:
rankZSet = j.deFirstBloodRank
scoreType = model.ScoreTypeDeFirstBlood
}
scoreType := model.ScoreTypeByRankType(rankType)
rankZSet, _ = j.rankByTypeMap[rankType]
if rankZSet == nil {
return nil, scoreType, errors.Errorf("没有此类型 [%d] 的排行榜", rankType)
}

@ -24,5 +24,5 @@ func NewRankPvpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RankPvpLo
// rank
func (l *RankPvpLogic) RankPvp(in *pb.RankPvpReq) (*pb.RankPvpResp, error) {
return Service.RangeRankByType(in.Type, in.TopN), nil
return Service.RangeRankByType(pb.RankType(in.Type), in.TopN), nil
}

@ -2,6 +2,9 @@ package rank
import (
"context"
"github.com/pkg/errors"
"live-service/app/user_center/model"
"live-service/common/nerr"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
@ -27,11 +30,34 @@ func (l *UserRankPvpLogic) UserRankPvp(in *pb.UserRankReq) (*pb.UserRankResp, er
// 1. 查询用户自己当前分数
// 2. 获取排名
// 3. 所有排名信息(需要首先判断)
var dbScoreMap map[string]int64
var err error
if in.AllRankType {
//in.UserId
if dbScoreMap, err = l.svcCtx.StatisticsPvpModel.FindScoreByType(l.ctx, nil, in.UserId, model.AllScoreType()); err != nil {
return nil, errors.Wrapf(nerr.NewError(nerr.RankStatisticsSelectError, "获取用户分数失败"), "获取用户分数失败 err:%v", err)
}
} else {
// 只查询一种类型
scoreTypes := []model.ScoreType{model.ScoreTypeByRankType(pb.RankType(in.RankType))}
if dbScoreMap, err = l.svcCtx.StatisticsPvpModel.FindScoreByType(l.ctx, nil, in.UserId, scoreTypes); err != nil {
return nil, errors.Wrapf(nerr.NewError(nerr.RankStatisticsSelectError, "获取用户分数失败"), "获取用户分数失败 err:%v", err)
}
}
items := make([]*pb.UserRankResp_Item, 0, len(dbScoreMap))
for scoreType, score := range dbScoreMap {
items = append(items, l.rankItem(model.RankTypeByScoreType(model.ScoreType(scoreType)), score))
}
return &pb.UserRankResp{
Items: items,
}, nil
}
func (l *UserRankPvpLogic) rankItem(rankType pb.RankType, score int64) *pb.UserRankResp_Item {
return &pb.UserRankResp_Item{
RankType: int32(rankType),
Score: score,
Pos: Service.RankByScore(rankType, int32(score)),
}
return &pb.UserRankResp{}, nil
}

@ -7,8 +7,11 @@ import (
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
"live-service/app/user_center/model"
"live-service/app/user_center/rpc/internal/common/integral_manager"
"live-service/app/user_center/rpc/internal/common/reward_pool"
"live-service/app/user_center/rpc/internal/svc"
"live-service/app/user_center/rpc/pb"
"sort"
)
type StatPvpReportLogic struct {
@ -27,9 +30,16 @@ func NewStatPvpReportLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Sta
func (l *StatPvpReportLogic) StatPvpReport(in *pb.StatPvPReportReq) (*pb.StatPvPReportResp, error) {
resp := &pb.StatPvPReportResp{}
// 排序
sort.SliceStable(in.WinItems, func(i, j int) bool {
return in.WinItems[i].Position < in.WinItems[j].Position
})
sort.SliceStable(in.LostItems, func(i, j int) bool {
return in.LostItems[i].Position < in.LostItems[j].Position
})
// 名将记录
{
general := in.General
if len(in.WinItems) > 0 {
general := in.WinItems[0]
if general.Uid > 0 {
if err := l.svcCtx.StatisticsPvpModel.TransactCtx(l.ctx, nil, func(tx *gorm.DB) error {
if err := l.svcCtx.StatisticsPvpModel.UpdateRecord(l.ctx, tx, general.Uid,
@ -66,52 +76,81 @@ func (l *StatPvpReportLogic) StatPvpReport(in *pb.StatPvPReportReq) (*pb.StatPvP
// 积分记录
{
battleReportCfg := l.svcCtx.Config.Integral.BattleReport
// 名将积分
if in.General.Uid > 0 {
_, err := l.svcCtx.UserIntegralModel.ChangeIntegral(l.ctx, nil, in.General.Uid, battleReportCfg.GeneralIntegral)
if err != nil {
l.Logger.Errorf("名将积分更新失败, err:%v", err)
}
resp.General = &pb.StatPvPReportResp_Item{
Uid: in.General.Uid,
Uname: in.General.Uname,
AddonIntegral: battleReportCfg.GeneralIntegral,
}
drawReq := make([]reward_pool.DrawRequest, 0, len(in.WinItems))
for _, item := range in.WinItems {
drawReq = append(drawReq, reward_pool.DrawRequest{
UserId: item.Uid,
Position: item.Position,
Ratio: 0.2,
})
}
drawResult := l.svcCtx.RewardPoolManager.Draw(in.BattleId, drawReq)
winItemResp := make([]*pb.StatPvPReportResp_Item, 0, len(in.WinItems))
lostItemResp := make([]*pb.StatPvPReportResp_Item, 0, len(in.LostItems))
integralChangeReq := make([]integral_manager.ChangeIntegralReq, 0, len(in.WinItems)+len(in.LostItems))
if err := l.svcCtx.UserIntegralModel.TransactCtx(l.ctx, nil, func(tx *gorm.DB) error {
for _, item := range in.WinItems {
uid, damage := item.Uid, item.Damage
addIntegral := int64(float64(damage) * battleReportCfg.WinRadio)
_, err := l.svcCtx.UserIntegralModel.ChangeIntegral(l.ctx, tx, uid, addIntegral)
if err != nil {
return err
}
winItemResp = append(winItemResp, &pb.StatPvPReportResp_Item{
Uid: uid,
Uname: item.Uname,
AddonIntegral: addIntegral,
})
// . 战斗结算
// . 奖池结算
for _, item := range in.WinItems {
// damage (暴兵越多伤害越高)
// killUnit (暴兵越多击杀越多)
// deDamage (暴兵越多受伤越多)
// deKillUnit (暴兵越多死的约多)
uid, uname, position, damage := item.Uid, item.Uname, item.Position, item.Damage
battleIntegral := int64(float64(damage) * battleReportCfg.WinRadio)
tmp := &pb.StatPvPReportResp_Item{
Uid: uid,
Uname: uname,
Position: position,
ReturnsIntegral: drawResult.UserReturns[uid],
RewardPoolIntegral: drawResult.DrawRewards[uid],
NobilityIntegral: 0, // TODO . 贵族加成分 再议
BattleIntegral: battleIntegral,
}
for _, item := range in.LostItems {
uid, damage := item.Uid, item.Damage
addIntegral := int64(float64(damage) * battleReportCfg.LostRadio)
_, err := l.svcCtx.UserIntegralModel.ChangeIntegral(l.ctx, tx, uid, addIntegral)
if err != nil {
return err
}
lostItemResp = append(lostItemResp, &pb.StatPvPReportResp_Item{
Uid: uid,
Uname: item.Uname,
AddonIntegral: addIntegral,
})
if position == 1 {
tmp.GeneralIntegral = battleReportCfg.GeneralIntegral
}
return nil
}); err != nil {
l.Logger.Errorf("战局积分计算失败, err:%v", err)
tmp.TotalIntegral = tmp.ReturnsIntegral + tmp.RewardPoolIntegral + tmp.GeneralIntegral + tmp.NobilityIntegral + tmp.BattleIntegral
winItemResp = append(winItemResp, tmp)
integralChangeReq = append(integralChangeReq, integral_manager.ChangeIntegralReq{
BattleId: in.BattleId,
UserId: uid,
Change: tmp.TotalIntegral,
Type: pb.IntegralType_Battle,
})
}
for _, item := range in.LostItems {
uid, uname, position, damage := item.Uid, item.Uname, item.Position, item.Damage
battleIntegral := int64(float64(damage) * battleReportCfg.LostRadio)
tmp := &pb.StatPvPReportResp_Item{
Uid: uid,
Uname: uname,
Position: position,
ReturnsIntegral: 0,
RewardPoolIntegral: 0,
GeneralIntegral: 0,
NobilityIntegral: 0, // TODO . 贵族加成分 再议
BattleIntegral: battleIntegral,
TotalIntegral: 0,
}
tmp.TotalIntegral = tmp.ReturnsIntegral + tmp.RewardPoolIntegral + tmp.GeneralIntegral + tmp.NobilityIntegral + tmp.BattleIntegral
lostItemResp = append(lostItemResp, tmp)
integralChangeReq = append(integralChangeReq, integral_manager.ChangeIntegralReq{
BattleId: in.BattleId,
UserId: uid,
Change: tmp.TotalIntegral,
Type: pb.IntegralType_Battle,
})
}
// 统一结算积分
_, err := l.svcCtx.IntegralManager.ChangeIntegralBatch(l.ctx, integralChangeReq, false)
if err != nil {
l.Logger.Errorf("积分结算失败 %v", err)
}
resp.WinItems = winItemResp
resp.LostItems = lostItemResp
}

@ -39,7 +39,7 @@ var (
// UserCheckIn 用户签到|打卡
func (l *UserCheckInLogic) UserCheckIn(in *pb.UserIdReq) (*pb.UserCheckInResp, error) {
resp := &pb.UserCheckInResp{
Success: false,
Code: 0,
Msg: "",
IntegralChange: 0,
Integral: 0,
@ -71,7 +71,7 @@ func (l *UserCheckInLogic) UserCheckIn(in *pb.UserIdReq) (*pb.UserCheckInResp, e
resp.IsCritical = critical
resp.IntegralChange = change
resp.Msg = MsgCheckInSuccess
resp.Success = true
resp.Code = 200
return nil
}); err != nil {

@ -5,6 +5,7 @@ package server
import (
"context"
"live-service/app/user_center/rpc/internal/logic/draw_pool"
"live-service/app/user_center/rpc/internal/logic/gift"
"live-service/app/user_center/rpc/internal/logic/integral"
"live-service/app/user_center/rpc/internal/logic/rank"
@ -56,6 +57,12 @@ func (s *UserCenterServer) UserCheckIn(ctx context.Context, in *pb.UserIdReq) (*
return l.UserCheckIn(in)
}
// TransferUserIntegral 转移积分
func (s *UserCenterServer) TransferUserIntegral(ctx context.Context, in *pb.TransferUserIntegralReq) (*pb.TransferUserIntegralResp, error) {
l := integral.NewTransferUserIntegralLogic(ctx, s.svcCtx)
return l.TransferUserIntegral(in)
}
// UserSendGift 用户赠送礼物
func (s *UserCenterServer) UserSendGift(ctx context.Context, in *pb.UserSendGiftReq) (*pb.UserSendGiftResp, error) {
l := gift.NewUserSendGiftLogic(ctx, s.svcCtx)
@ -87,6 +94,11 @@ func (s *UserCenterServer) DrawGiftPack(ctx context.Context, in *pb.DrawGiftPack
return l.DrawGiftPack(in)
}
func (s *UserCenterServer) IncreaseWelfare(ctx context.Context, in *pb.IncreaseWelfareReq) (*pb.Empty, error) {
l := draw_pool.NewIncreaseWelfareLogic(ctx, s.svcCtx)
return l.IncreaseWelfare(in)
}
// rankPvp pvp排行
func (s *UserCenterServer) RankPvp(ctx context.Context, in *pb.RankPvpReq) (*pb.RankPvpResp, error) {
l := rank.NewRankPvpLogic(ctx, s.svcCtx)

@ -1,11 +1,15 @@
package svc
import (
"git.noahlan.cn/northlan/ntools-go/kafka"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"live-service/app/user_center/model"
"live-service/app/user_center/rpc/internal/common/integral_manager"
"live-service/app/user_center/rpc/internal/common/reward_pool"
"live-service/app/user_center/rpc/internal/config"
kfk "live-service/common/kafka"
"log"
"os"
"time"
@ -21,12 +25,14 @@ type ServiceContext struct {
UserIntegralModel model.UserIntegralModel
UserNobilityModel model.UserNobilityModel
UserCheckInModel model.UserCheckInModel
UserGiftPackModel model.UserGiftPackModel
StatisticsPvpModel model.StatisticsPvpModel
RankPvpModel model.RankPvpModel
GiftModel model.GiftModel
RewardPoolManager *reward_pool.PoolManager
IntegralManager *integral_manager.Manager
}
func NewServiceContext(c config.Config) *ServiceContext {
@ -50,18 +56,32 @@ func NewServiceContext(c config.Config) *ServiceContext {
if err != nil {
log.Fatal(err)
}
userIntegralModel := model.NewUserIntegralModel(gormDb)
rewardPoolManager := reward_pool.NewRewardPoolManager(
c.Integral.RewardPool.InitReward,
reward_pool.Ratio{
Ratio: c.Integral.RewardPool.Ratio,
BattleRatio: c.Integral.RewardPool.BattleRatio,
GiftRatio: c.Integral.RewardPool.GiftRatio,
ReturnRatio: c.Integral.RewardPool.ReturnRatio,
WelfareRatio: c.Integral.RewardPool.WelfareRatio,
},
kafka.NewKafkaProducer(kfk.DefaultProducerConfig, c.Kafka.RewardPool.Addr, c.Kafka.RewardPool.Topic))
return &ServiceContext{
Config: c,
Db: gormDb,
UserModel: model.NewUserModel(gormDb),
UserPlatformModel: model.NewUserPlatformModel(gormDb),
UserGiftModel: model.NewUserGiftModel(gormDb),
UserIntegralModel: model.NewUserIntegralModel(gormDb),
UserIntegralModel: userIntegralModel,
UserNobilityModel: model.NewUserNobilityModel(gormDb),
UserCheckInModel: model.NewUserCheckInModel(gormDb),
UserGiftPackModel: model.NewUserGiftPackModel(gormDb),
StatisticsPvpModel: model.NewStatisticsPvpModel(gormDb),
RankPvpModel: model.NewRankPvpModel(gormDb),
GiftModel: model.NewGiftModel(gormDb),
RewardPoolManager: rewardPoolManager,
IntegralManager: integral_manager.NewIntegralManager(userIntegralModel, rewardPoolManager),
}
}

File diff suppressed because it is too large Load Diff

@ -39,10 +39,18 @@ message UserIdResp {
int64 userId = 1;
}
enum IntegralType {
Battle = 0; //
Gift = 1; //
Other = 10; //
}
//
message ChangeIntegralReq {
int64 userId = 1; // ID
int64 change = 2; //
int64 battleId = 2; // ID(RPC)
int64 change = 3; //
IntegralType integralType = 4; //
}
//
@ -60,13 +68,36 @@ message UserIntegralResp {
//
message UserCheckInResp {
bool success = 1; //
int32 code = 1;
string msg = 2; //
int64 integralChange = 3; //
int64 integral = 4; //
bool isCritical = 5; //
}
//
message TransferUserIntegralReq {
int64 userId = 1; // ID
int64 targetUserId = 2; //
int64 transfer = 3; //
}
message TransferUserIntegralResp {
int32 code = 1;
string msg = 2; //
int64 userId = 3;
string uname = 4;
string avatar = 5;
int64 targetUserId = 6;
string targetUname = 7;
string targetAvatar = 8;
int64 userIntegral = 10; //
int64 targetUserIntegral = 11; //
}
//
message UserSendGiftReq {
string platform = 1; //
@ -78,6 +109,7 @@ message UserSendGiftReq {
int64 num = 7; //
int64 price = 8; // (使)
bool isPaid = 9; //
int64 battleId = 10; // ID
}
//
@ -88,20 +120,22 @@ message UserSendGiftResp {
//
message UserBuyNobilityReq {
string platform = 1; //
string pUid = 2; // ID
string roomId = 3; // ID
int64 giftId = 4; // ID
string giftName = 5; //
int64 num = 6; //
int64 price = 7; // (使)
int64 level = 8; //
int64 startTime = 9; //
int64 endTime = 10; //
int64 userId = 2; // ID
string pUid = 3; // ID
int64 battleId = 4; // ID
string roomId = 5; // ID
int64 giftId = 6; // ID
string giftName = 7; //
int64 num = 8; //
int64 price = 9; // (使)
int64 level = 10; //
int64 startTime = 11; //
int64 endTime = 12; //
}
//
message UserBuyNobilityResp {
User user = 1; //
ChangeIntegralResp integral = 10; //
}
@ -123,17 +157,14 @@ message StatPvPReportReq {
message Item {
int64 uid = 1; // ID
string uname = 2; //
int64 damage = 3; //
int64 deDamage = 4; //
int64 killUnit = 5; //
int64 deKillUnit = 6; //
}
message General {
int64 uid = 1; // UID
string uname = 2; //
int32 position = 3; //
int64 damage = 4; //
int64 deDamage = 5; //
int64 killUnit = 6; //
int64 deKillUnit = 7; //
}
int32 winCamp = 1; // 1- 2-
General general = 2;
int64 battleId = 2; // ID
repeated Item winItems = 10; //
repeated Item lostItems = 11; //
}
@ -143,11 +174,16 @@ message StatPvPReportResp {
message Item {
int64 uid = 1; // ID
string uname = 2; //
int64 addonIntegral = 3; //
int32 position = 3; //
int64 returnsIntegral = 4; // 0
int64 rewardPoolIntegral = 5; //
int64 generalIntegral = 6; //
int64 nobilityIntegral = 7; // ||
int64 battleIntegral = 8; //
int64 totalIntegral = 10; //
}
Item general = 1; //
repeated Item winItems = 10; //
repeated Item lostItems = 11; //
repeated Item winItems = 1; //
repeated Item lostItems = 2; //
}
////////////////////
@ -158,11 +194,13 @@ enum GiftType {
}
message GiftPackItem {
string giftType = 1; // starter:
int64 integral = 2; //
repeated string title = 3; //
string packType = 1; // starter:
string packName = 2; //
int64 integral = 3; //
repeated string title = 4; //
}
//
message DrawGiftPackReq {
int64 uid = 1;
string uname = 2;
@ -177,6 +215,15 @@ message DrawGiftPackResp {
GiftPackItem item = 10;
}
////////////////////// drawPool
//
message IncreaseWelfareReq {
int64 uid = 1; // ID
string uname = 2; //
int64 welfare = 3; //
}
////////////////////// rank
enum RankType {
Unknown = 0;
@ -245,6 +292,7 @@ message UserRankResp {
message Item {
int32 rankType = 1; //
int32 pos = 2; //
int64 score = 3; //
}
repeated Item items = 1;
}
@ -260,11 +308,13 @@ service userCenter {
/// @ZeroGroup: integral
//ChangeIntegral
rpc ChangeIntegral(ChangeIntegralReq) returns (ChangeIntegralResp);
rpc changeIntegral(ChangeIntegralReq) returns (ChangeIntegralResp);
//GetUserIntegral
rpc GetUserIntegral(UserIdReq) returns (UserIntegralResp);
rpc getUserIntegral(UserIdReq) returns (UserIntegralResp);
//UserCheckIn |
rpc UserCheckIn(UserIdReq) returns (UserCheckInResp);
rpc userCheckIn(UserIdReq) returns (UserCheckInResp);
//TransferUserIntegral
rpc transferUserIntegral(TransferUserIntegralReq) returns (TransferUserIntegralResp);
/// @ZeroGroup: gift
@ -282,6 +332,10 @@ service userCenter {
rpc drawGiftPack(DrawGiftPackReq) returns(DrawGiftPackResp);
/// @ZeroGroup: drawPool
rpc increaseWelfare(IncreaseWelfareReq) returns (Empty);
/// @ZeroGroup: rank
// rankPvp pvp

@ -32,6 +32,8 @@ type UserCenterClient interface {
GetUserIntegral(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserIntegralResp, error)
//UserCheckIn 用户签到|打卡
UserCheckIn(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserCheckInResp, error)
//TransferUserIntegral 转移积分
TransferUserIntegral(ctx context.Context, in *TransferUserIntegralReq, opts ...grpc.CallOption) (*TransferUserIntegralResp, error)
// UserSendGift 用户赠送礼物
UserSendGift(ctx context.Context, in *UserSendGiftReq, opts ...grpc.CallOption) (*UserSendGiftResp, error)
UserBuyNobility(ctx context.Context, in *UserBuyNobilityReq, opts ...grpc.CallOption) (*UserBuyNobilityResp, error)
@ -39,6 +41,7 @@ type UserCenterClient interface {
StatPvpFirstBlood(ctx context.Context, in *StatPvPFirstBloodReq, opts ...grpc.CallOption) (*Empty, error)
StatPvpReport(ctx context.Context, in *StatPvPReportReq, opts ...grpc.CallOption) (*StatPvPReportResp, error)
DrawGiftPack(ctx context.Context, in *DrawGiftPackReq, opts ...grpc.CallOption) (*DrawGiftPackResp, error)
IncreaseWelfare(ctx context.Context, in *IncreaseWelfareReq, opts ...grpc.CallOption) (*Empty, error)
// rankPvp pvp排行
RankPvp(ctx context.Context, in *RankPvpReq, opts ...grpc.CallOption) (*RankPvpResp, error)
RankPvpSubmit(ctx context.Context, in *RankPvpSubmitReq, opts ...grpc.CallOption) (*RankPvpSubmitResp, error)
@ -73,7 +76,7 @@ func (c *userCenterClient) GetUserIdByPUid(ctx context.Context, in *PlatformUser
func (c *userCenterClient) ChangeIntegral(ctx context.Context, in *ChangeIntegralReq, opts ...grpc.CallOption) (*ChangeIntegralResp, error) {
out := new(ChangeIntegralResp)
err := c.cc.Invoke(ctx, "/pb.userCenter/ChangeIntegral", in, out, opts...)
err := c.cc.Invoke(ctx, "/pb.userCenter/changeIntegral", in, out, opts...)
if err != nil {
return nil, err
}
@ -82,7 +85,7 @@ func (c *userCenterClient) ChangeIntegral(ctx context.Context, in *ChangeIntegra
func (c *userCenterClient) GetUserIntegral(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserIntegralResp, error) {
out := new(UserIntegralResp)
err := c.cc.Invoke(ctx, "/pb.userCenter/GetUserIntegral", in, out, opts...)
err := c.cc.Invoke(ctx, "/pb.userCenter/getUserIntegral", in, out, opts...)
if err != nil {
return nil, err
}
@ -91,7 +94,16 @@ func (c *userCenterClient) GetUserIntegral(ctx context.Context, in *UserIdReq, o
func (c *userCenterClient) UserCheckIn(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserCheckInResp, error) {
out := new(UserCheckInResp)
err := c.cc.Invoke(ctx, "/pb.userCenter/UserCheckIn", in, out, opts...)
err := c.cc.Invoke(ctx, "/pb.userCenter/userCheckIn", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userCenterClient) TransferUserIntegral(ctx context.Context, in *TransferUserIntegralReq, opts ...grpc.CallOption) (*TransferUserIntegralResp, error) {
out := new(TransferUserIntegralResp)
err := c.cc.Invoke(ctx, "/pb.userCenter/transferUserIntegral", in, out, opts...)
if err != nil {
return nil, err
}
@ -152,6 +164,15 @@ func (c *userCenterClient) DrawGiftPack(ctx context.Context, in *DrawGiftPackReq
return out, nil
}
func (c *userCenterClient) IncreaseWelfare(ctx context.Context, in *IncreaseWelfareReq, opts ...grpc.CallOption) (*Empty, error) {
out := new(Empty)
err := c.cc.Invoke(ctx, "/pb.userCenter/increaseWelfare", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userCenterClient) RankPvp(ctx context.Context, in *RankPvpReq, opts ...grpc.CallOption) (*RankPvpResp, error) {
out := new(RankPvpResp)
err := c.cc.Invoke(ctx, "/pb.userCenter/rankPvp", in, out, opts...)
@ -193,6 +214,8 @@ type UserCenterServer interface {
GetUserIntegral(context.Context, *UserIdReq) (*UserIntegralResp, error)
//UserCheckIn 用户签到|打卡
UserCheckIn(context.Context, *UserIdReq) (*UserCheckInResp, error)
//TransferUserIntegral 转移积分
TransferUserIntegral(context.Context, *TransferUserIntegralReq) (*TransferUserIntegralResp, error)
// UserSendGift 用户赠送礼物
UserSendGift(context.Context, *UserSendGiftReq) (*UserSendGiftResp, error)
UserBuyNobility(context.Context, *UserBuyNobilityReq) (*UserBuyNobilityResp, error)
@ -200,6 +223,7 @@ type UserCenterServer interface {
StatPvpFirstBlood(context.Context, *StatPvPFirstBloodReq) (*Empty, error)
StatPvpReport(context.Context, *StatPvPReportReq) (*StatPvPReportResp, error)
DrawGiftPack(context.Context, *DrawGiftPackReq) (*DrawGiftPackResp, error)
IncreaseWelfare(context.Context, *IncreaseWelfareReq) (*Empty, error)
// rankPvp pvp排行
RankPvp(context.Context, *RankPvpReq) (*RankPvpResp, error)
RankPvpSubmit(context.Context, *RankPvpSubmitReq) (*RankPvpSubmitResp, error)
@ -226,6 +250,9 @@ func (UnimplementedUserCenterServer) GetUserIntegral(context.Context, *UserIdReq
func (UnimplementedUserCenterServer) UserCheckIn(context.Context, *UserIdReq) (*UserCheckInResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method UserCheckIn not implemented")
}
func (UnimplementedUserCenterServer) TransferUserIntegral(context.Context, *TransferUserIntegralReq) (*TransferUserIntegralResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method TransferUserIntegral not implemented")
}
func (UnimplementedUserCenterServer) UserSendGift(context.Context, *UserSendGiftReq) (*UserSendGiftResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method UserSendGift not implemented")
}
@ -244,6 +271,9 @@ func (UnimplementedUserCenterServer) StatPvpReport(context.Context, *StatPvPRepo
func (UnimplementedUserCenterServer) DrawGiftPack(context.Context, *DrawGiftPackReq) (*DrawGiftPackResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method DrawGiftPack not implemented")
}
func (UnimplementedUserCenterServer) IncreaseWelfare(context.Context, *IncreaseWelfareReq) (*Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method IncreaseWelfare not implemented")
}
func (UnimplementedUserCenterServer) RankPvp(context.Context, *RankPvpReq) (*RankPvpResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method RankPvp not implemented")
}
@ -312,7 +342,7 @@ func _UserCenter_ChangeIntegral_Handler(srv interface{}, ctx context.Context, de
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.userCenter/ChangeIntegral",
FullMethod: "/pb.userCenter/changeIntegral",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserCenterServer).ChangeIntegral(ctx, req.(*ChangeIntegralReq))
@ -330,7 +360,7 @@ func _UserCenter_GetUserIntegral_Handler(srv interface{}, ctx context.Context, d
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.userCenter/GetUserIntegral",
FullMethod: "/pb.userCenter/getUserIntegral",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserCenterServer).GetUserIntegral(ctx, req.(*UserIdReq))
@ -348,7 +378,7 @@ func _UserCenter_UserCheckIn_Handler(srv interface{}, ctx context.Context, dec f
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.userCenter/UserCheckIn",
FullMethod: "/pb.userCenter/userCheckIn",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserCenterServer).UserCheckIn(ctx, req.(*UserIdReq))
@ -356,6 +386,24 @@ func _UserCenter_UserCheckIn_Handler(srv interface{}, ctx context.Context, dec f
return interceptor(ctx, in, info, handler)
}
func _UserCenter_TransferUserIntegral_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TransferUserIntegralReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserCenterServer).TransferUserIntegral(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.userCenter/transferUserIntegral",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserCenterServer).TransferUserIntegral(ctx, req.(*TransferUserIntegralReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserCenter_UserSendGift_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserSendGiftReq)
if err := dec(in); err != nil {
@ -464,6 +512,24 @@ func _UserCenter_DrawGiftPack_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
func _UserCenter_IncreaseWelfare_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(IncreaseWelfareReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserCenterServer).IncreaseWelfare(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pb.userCenter/increaseWelfare",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserCenterServer).IncreaseWelfare(ctx, req.(*IncreaseWelfareReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserCenter_RankPvp_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RankPvpReq)
if err := dec(in); err != nil {
@ -534,17 +600,21 @@ var UserCenter_ServiceDesc = grpc.ServiceDesc{
Handler: _UserCenter_GetUserIdByPUid_Handler,
},
{
MethodName: "ChangeIntegral",
MethodName: "changeIntegral",
Handler: _UserCenter_ChangeIntegral_Handler,
},
{
MethodName: "GetUserIntegral",
MethodName: "getUserIntegral",
Handler: _UserCenter_GetUserIntegral_Handler,
},
{
MethodName: "UserCheckIn",
MethodName: "userCheckIn",
Handler: _UserCenter_UserCheckIn_Handler,
},
{
MethodName: "transferUserIntegral",
Handler: _UserCenter_TransferUserIntegral_Handler,
},
{
MethodName: "userSendGift",
Handler: _UserCenter_UserSendGift_Handler,
@ -569,6 +639,10 @@ var UserCenter_ServiceDesc = grpc.ServiceDesc{
MethodName: "drawGiftPack",
Handler: _UserCenter_DrawGiftPack_Handler,
},
{
MethodName: "increaseWelfare",
Handler: _UserCenter_IncreaseWelfare_Handler,
},
{
MethodName: "rankPvp",
Handler: _UserCenter_RankPvp_Handler,

@ -19,6 +19,7 @@ type (
DrawGiftPackResp = pb.DrawGiftPackResp
Empty = pb.Empty
GiftPackItem = pb.GiftPackItem
IncreaseWelfareReq = pb.IncreaseWelfareReq
PlatformUserReq = pb.PlatformUserReq
PlatformUserResp = pb.PlatformUserResp
RankPvpReq = pb.RankPvpReq
@ -31,10 +32,11 @@ type (
StatPvPFirstBloodReq = pb.StatPvPFirstBloodReq
StatPvPKillReq = pb.StatPvPKillReq
StatPvPReportReq = pb.StatPvPReportReq
StatPvPReportReq_General = pb.StatPvPReportReq_General
StatPvPReportReq_Item = pb.StatPvPReportReq_Item
StatPvPReportResp = pb.StatPvPReportResp
StatPvPReportResp_Item = pb.StatPvPReportResp_Item
TransferUserIntegralReq = pb.TransferUserIntegralReq
TransferUserIntegralResp = pb.TransferUserIntegralResp
User = pb.User
UserBuyNobilityReq = pb.UserBuyNobilityReq
UserBuyNobilityResp = pb.UserBuyNobilityResp
@ -59,6 +61,8 @@ type (
GetUserIntegral(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserIntegralResp, error)
// UserCheckIn 用户签到|打卡
UserCheckIn(ctx context.Context, in *UserIdReq, opts ...grpc.CallOption) (*UserCheckInResp, error)
// TransferUserIntegral 转移积分
TransferUserIntegral(ctx context.Context, in *TransferUserIntegralReq, opts ...grpc.CallOption) (*TransferUserIntegralResp, error)
// UserSendGift 用户赠送礼物
UserSendGift(ctx context.Context, in *UserSendGiftReq, opts ...grpc.CallOption) (*UserSendGiftResp, error)
UserBuyNobility(ctx context.Context, in *UserBuyNobilityReq, opts ...grpc.CallOption) (*UserBuyNobilityResp, error)
@ -66,6 +70,7 @@ type (
StatPvpFirstBlood(ctx context.Context, in *StatPvPFirstBloodReq, opts ...grpc.CallOption) (*Empty, error)
StatPvpReport(ctx context.Context, in *StatPvPReportReq, opts ...grpc.CallOption) (*StatPvPReportResp, error)
DrawGiftPack(ctx context.Context, in *DrawGiftPackReq, opts ...grpc.CallOption) (*DrawGiftPackResp, error)
IncreaseWelfare(ctx context.Context, in *IncreaseWelfareReq, opts ...grpc.CallOption) (*Empty, error)
// rankPvp pvp排行
RankPvp(ctx context.Context, in *RankPvpReq, opts ...grpc.CallOption) (*RankPvpResp, error)
RankPvpSubmit(ctx context.Context, in *RankPvpSubmitReq, opts ...grpc.CallOption) (*RankPvpSubmitResp, error)
@ -113,6 +118,12 @@ func (m *defaultUserCenter) UserCheckIn(ctx context.Context, in *UserIdReq, opts
return client.UserCheckIn(ctx, in, opts...)
}
// TransferUserIntegral 转移积分
func (m *defaultUserCenter) TransferUserIntegral(ctx context.Context, in *TransferUserIntegralReq, opts ...grpc.CallOption) (*TransferUserIntegralResp, error) {
client := pb.NewUserCenterClient(m.cli.Conn())
return client.TransferUserIntegral(ctx, in, opts...)
}
// UserSendGift 用户赠送礼物
func (m *defaultUserCenter) UserSendGift(ctx context.Context, in *UserSendGiftReq, opts ...grpc.CallOption) (*UserSendGiftResp, error) {
client := pb.NewUserCenterClient(m.cli.Conn())
@ -144,6 +155,11 @@ func (m *defaultUserCenter) DrawGiftPack(ctx context.Context, in *DrawGiftPackRe
return client.DrawGiftPack(ctx, in, opts...)
}
func (m *defaultUserCenter) IncreaseWelfare(ctx context.Context, in *IncreaseWelfareReq, opts ...grpc.CallOption) (*Empty, error) {
client := pb.NewUserCenterClient(m.cli.Conn())
return client.IncreaseWelfare(ctx, in, opts...)
}
// rankPvp pvp排行
func (m *defaultUserCenter) RankPvp(ctx context.Context, in *RankPvpReq, opts ...grpc.CallOption) (*RankPvpResp, error) {
client := pb.NewUserCenterClient(m.cli.Conn())

@ -8,24 +8,49 @@ const OK uint32 = 200
// 全局错误
const (
ServerCommonError uint32 = 100001
RequestParamError uint32 = 100002
TokenExpireError uint32 = 100003
TokenGenerateError uint32 = 100004
DBError uint32 = 100005
DBUpdateAffectedZeroError uint32 = 100006
CopyError uint32 = 100007
ServerCommonError uint32 = iota + 100001
RequestParamError
TokenExpireError
TokenGenerateError
DBError
DBUpdateAffectedZeroError
CopyError
)
// 用户积分相关 UserIntegral
// 业务错误
// 用户积分相关 UserIntegral
const (
UserIntegralNotEnoughError uint32 = 200100 // 用户积分不足
UserIntegralNotEnoughError uint32 = iota + 200100 // 用户积分不足
NewUserIntegralError // 新建用户积分失败
GetUserIntegralError // 获取用户积分失败
UpdateUserIntegralError // 更新用户积分失败
)
// 礼包相关 GiftPack
const (
GiftPackHasDrawError = 201100 // 该礼包已经领取过
GiftPackDrawCountLimitedError = 201101 // 该礼包已领取完
GiftPackHasDrawError uint32 = 201100 // 该礼包已经领取过
GiftPackDrawCountLimitedError = 201101 // 该礼包已领取完
)
// 礼物相关 Gift
const (
GiftRecordErr uint32 = 202100 // 礼物记录失败
GiftNobilityUpdateErr = 202101 // 更新贵族信息失败
)
// 排行相关
const (
RankStatisticsSelectError uint32 = 203100 // 获取统计数据失败
)
// 用户金币(Coin)相关 UserCoin
const (
UserCoinNotEnoughErr uint32 = iota + 204100 // 用户金币不足
NewUserCoinErr // 新建用户金币失败
GetUserCoinErr // 获取用户金币失败
UpdateUserCoinErr // 更新用户金币失败
)

@ -0,0 +1,22 @@
package timex
import "time"
const (
seconds = 1e11
milliseconds = 1e14
microseconds = 1e17
)
func TimestampToTime(ts int64) time.Time {
if ts < seconds {
return time.Unix(ts, 0)
}
if ts < milliseconds {
return time.Unix(ts/1000, (ts%1000)*1e6)
}
if ts < microseconds {
return time.Unix(ts/1e6, (ts%1e6)*1000)
}
return time.Unix(0, ts)
}

@ -8,22 +8,14 @@ func (m *default{{.upperStartCamelObject}}Model) FindOneBy{{.upperField}}(ctx co
}
return resp.{{.upperStartCamelPrimaryKey}}, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
if err = gormx.WrapSelectErr(err); err != nil {
return nil, err
}
return &resp, nil
}{{else}}var resp {{.upperStartCamelObject}}
err := gormx.WithTx(ctx, m.DB, tx).Model(&{{.upperStartCamelObject}}{}).Where("{{.originalField}}", {{.lowerStartCamelField}}).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
if err = gormx.WrapSelectErr(err); err != nil {
return nil, err
}
return &resp, nil
}{{end}}

@ -5,21 +5,14 @@ func (m *default{{.upperStartCamelObject}}Model) FindOne(ctx context.Context, tx
err := m.QueryCtx(ctx, &resp, {{.cacheKeyVariable}}, func(conn *gorm.DB, v interface{}) error {
return gormx.WithTx(ctx, conn, tx).Model(&{{.upperStartCamelObject}}{}).Where("{{.originalPrimaryKey}} = ?", {{.lowerStartCamelPrimaryKey}}).First(&resp).Error
})
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}{{else}}var resp {{.upperStartCamelObject}}
if err = gormx.WrapSelectErr(err); err != nil {
return nil, err
}
return &resp, nil
{{else}}var resp {{.upperStartCamelObject}}
err := gormx.WithTx(ctx, m.DB, tx).Model(&{{.upperStartCamelObject}}{}).Where("{{.originalPrimaryKey}} = ?", {{.lowerStartCamelPrimaryKey}}).Take(&resp).Error
switch err {
case nil:
return &resp, nil
case gormx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}{{end}}
if err = gormx.WrapSelectErr(err); err != nil {
return nil, err
}
return &resp, nil{{end}}
}

@ -3,21 +3,9 @@ func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, tx
{{if .withCache}}{{.keys}}
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
result := gormx.WithTx(ctx, conn, tx).Save(data)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gormx.ErrRowsAffectedZero
}
return nil
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
}, {{.keyValues}}){{else}}
result:=gormx.WithTx(ctx, m.DB, tx).Save(data)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gormx.ErrRowsAffectedZero
}
return nil
result := gormx.WithTx(ctx, m.DB, tx).Save(data)
return gormx.WrapUpdateErr(result.Error, result.RowsAffected)
{{end}}
}

@ -3,7 +3,7 @@ module live-service
go 1.18
require (
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.4
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.6
git.noahlan.cn/northlan/ntools-go/kafka v1.0.1
git.noahlan.cn/northlan/ntools-go/uuid v1.0.0
github.com/Shopify/sarama v1.33.0

@ -33,6 +33,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.4 h1:r9jH+tJ1YoeX0gtt26lWeW2hxJGbKH1DksnIrjrLaMk=
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.4/go.mod h1:ExV9s96axCdMcaXqsezoUxnbTptkMqwvNWvON05uzjE=
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.6 h1:Y59SvkmIFsAAF3BifOxMjOwj/USsZDLuMuliPS2r4OA=
git.noahlan.cn/northlan/ntools-go/gorm-zero v1.0.6/go.mod h1:ExV9s96axCdMcaXqsezoUxnbTptkMqwvNWvON05uzjE=
git.noahlan.cn/northlan/ntools-go/kafka v1.0.1 h1:SDUwYRzksZ3Vcu7PTZxk+TEMF2f3gBiQEboKOhi1yfI=
git.noahlan.cn/northlan/ntools-go/kafka v1.0.1/go.mod h1:RxX9JSUIr3Gbk+cvUwE5k+i08AgIK3TA9ayDJCMn2n8=
git.noahlan.cn/northlan/ntools-go/uuid v1.0.0 h1:C0PazSzG3+e/Hfh2C6Qf8R46sNZmZKTOcWS990yUmrE=

Loading…
Cancel
Save