Commit cf75ee7f authored by hujiebin's avatar hujiebin

feat:排行榜

parent b377da45
package cp_m
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/resource/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"time"
)
type CpDayRank struct {
Date string
CpId mysql.ID
UserId1 mysql.ID
UserId2 mysql.ID
Score mysql.Num
CreatedTime time.Time `gorm:"->"`
UpdatedTime time.Time `gorm:"->"`
}
// 增加cp排行榜-天
func AddCpDayRank(model *domain.Model, cpRelation CpRelationTmp, score mysql.Num) (err error) {
date := time.Now().Format("2006-01-02")
rank := &CpDayRank{
Date: date,
CpId: cpRelation.ID,
UserId1: cpRelation.UserId1,
UserId2: cpRelation.UserId2,
Score: score,
}
if err = model.DB().Model(CpDayRank{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "date"}, {Name: "cp_id"}},
DoUpdates: clause.Assignments(map[string]interface{}{
"score": gorm.Expr("score + ?", rank.Score)})}).Create(rank).Error; err != nil {
model.Log.Errorf("AddCpDayRank fail:%v", err)
return err
}
return nil
}
// 分页获取cp排行榜
func PageCpDayRank(model *domain.Model, beginDate, endDate string, offset, limit int) []CpDayRank {
var ranks []CpDayRank
if err := model.DB().Table("cp_day_rank r").Joins("INNER JOIN cp_relation c ON c.id = r.cp_id").
Where("r.date BETWEEN ? AND ?", beginDate, endDate).
Order("r.score DESC").Offset(offset).Limit(limit).Select("r.*").Find(&ranks).Error; err != nil {
model.Log.Errorf("PageCpDayRank fail:%v", err)
}
return ranks
}
......@@ -6,8 +6,9 @@ import (
"hilo-user/domain/model/cp_m"
)
// 送礼增加cp值
func CpLevelEvent() {
// 送礼增加cp等级
// 送礼增加cp排行榜
func CpGiftEvent() {
gift_ev.AddSendGiftEventAsync(func(model *domain.Model, event interface{}) error {
sendGiftEvent, ok := event.(*gift_ev.SendGiftEvent)
if !ok {
......@@ -18,7 +19,13 @@ func CpLevelEvent() {
diamonds := sendGiftEvent.GiftN * sendGiftEvent.ResGift.DiamondNum
// 有cp关系
if cpRelation, exits := cp_m.GetCpRelation(model, sendGiftEvent.SendUserId, receiverUid); exits {
return cp_m.AddCpLevelPoints(model, cpRelation, diamonds) // 业务场景允许提前break(cp是唯一的)
if err := cp_m.AddCpLevelPoints(model, cpRelation, diamonds); err != nil {
model.Log.Errorf("AddCpLevelPoints fail:%v", err)
}
if err := cp_m.AddCpDayRank(model, cpRelation, diamonds); err != nil {
model.Log.Errorf("AddCpDayRank fail:%v", err)
}
return nil // 业务场景允许提前break(cp是唯一的)
}
}
return nil
......
......@@ -14,7 +14,7 @@ import (
func EventInit() {
UserBagSendEvent()
CpLevelEvent()
CpGiftEvent()
}
func UserBagSendEvent() {
......
......@@ -19,31 +19,4 @@ var (
DiamondNoEnough = myerr.NewBusinessCode(4000, "Insufficient diamonds", myerr.BusinessData{})
DiamondFrequency = myerr.NewBusinessCode(4001, "Diamond operation frequency too high", myerr.BusinessData{})
DiamondAccountFrozen = myerr.NewBusinessCode(4004, "Diamond Account Frozen", myerr.BusinessData{})
// 游戏
GameInvalidParameter = myerr.NewGameError(10002, "invalid parameter")
GameTokenInvalid = myerr.NewGameError(1004, "user token invalid")
GameTokenExpire = myerr.NewGameError(1005, "user token expire")
// 群组
GroupNotFound = myerr.NewBusinessCode(14001, "Group not found", myerr.BusinessData{}) // 找不到该群
// 游戏服务的错误码,6位,50XXX
GameAddNoPermissions = myerr.NewBusinessCode(50100, "Only room administrators can create users", myerr.BusinessData{}) // 权限不足
GameAddNotOnMic = myerr.NewBusinessCode(50101, "Need on mic", myerr.BusinessData{}) // 需要在麦上才能创建、加入游戏
GameHaveNoEnd = myerr.NewBusinessCode(50102, "Group user have no end", myerr.BusinessData{}) // 房间还有未结束的游戏
GameNotFound = myerr.NewBusinessCode(50103, "Game not found", myerr.BusinessData{}) //
GameStart = myerr.NewBusinessCode(50104, "Gaming", myerr.BusinessData{}) //
GameAlreadyJoin = myerr.NewBusinessCode(50105, "Already Joined", myerr.BusinessData{}) // 已经加入了游戏
GameNotJoin = myerr.NewBusinessCode(50106, "Not Join user", myerr.BusinessData{}) // 还未加入游戏
GameCannotClose = myerr.NewBusinessCode(50107, "Have no power to close user", myerr.BusinessData{}) // 没有权限关闭游戏
GameCloseGaming = myerr.NewBusinessCode(50108, "Can't close a user in progress", myerr.BusinessData{}) // 不能关闭进行中的游戏
GamePlayerNumWrong = myerr.NewBusinessCode(50109, "Game player num wrong", myerr.BusinessData{}) // 玩家数量错误
GameHaveNoMyRoom = myerr.NewBusinessCode(50110, "Have no my room", myerr.BusinessData{}) // 自己没有房间
GameHaveNoEndGame = myerr.NewBusinessCode(50111, "The last user is not over yet, cannot create/join a user", myerr.BusinessData{}) // 已经加入了其他房间的游戏
GameExitWrong = myerr.NewBusinessCode(50112, "Can not exit user", myerr.BusinessData{}) // 离开游戏失败
GameDiamondCannotEdit = myerr.NewBusinessCode(50113, "Game diamond can not edit", myerr.BusinessData{}) //
GameSettleWrong = myerr.NewBusinessCode(50114, "Game settle wrong", myerr.BusinessData{}) // 结算修改错误
GameCloseWrong = myerr.NewBusinessCode(50115, "Game close wrong", myerr.BusinessData{}) // 关闭错误
GameJoinFailed = myerr.NewBusinessCode(50116, "Join failed", myerr.BusinessData{}) // 加入失败
)
......@@ -225,36 +225,3 @@ func WrapErr(err error) error {
return errors.Wrap(err, "")
}
}
func WrapGameErr(err error) error {
if err == nil {
return err
}
if h, ok := err.(*GameError); ok {
return h
}
return NewGameError(500, err.Error())
}
// 系统错误
type GameError struct {
code uint16
message string
err error
}
func (err *GameError) Error() string {
return err.err.Error()
}
func (err *GameError) Code() uint16 {
return err.code
}
func NewGameError(code uint16, msg string) *GameError {
return &GameError{
code: code,
message: msg,
err: errors.New("{code:" + strconv.Itoa(int(code)) + ",message:" + msg + "}"),
}
}
......@@ -10,6 +10,18 @@ import (
"hilo-user/myerr/bizerr"
)
// 分页base
type PageReqBase struct {
PageIndex int `form:"pageIndex,default=0"`
PageSize int `form:"pageSize,default=10"`
}
type PageRespBase struct {
NextPageIndex int `json:"nextPageIndex"`
HasNextPage bool `json:"hasNextPage"`
Data interface{} `json:"data"` // 需要具体自定义
}
func GetUserId(c *gin.Context) (mysql.ID, error) {
if userIdStr, ok := c.Keys[mycontext.USERID]; ok {
userId := userIdStr.(uint64)
......
......@@ -5,6 +5,7 @@ import (
"git.hilo.cn/hilo-common/mycontext"
"github.com/gin-gonic/gin"
"hilo-user/myerr"
"hilo-user/req"
"net/http"
)
......@@ -42,27 +43,23 @@ func ResponseOk(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, response)
}
func GameResponseOk(c *gin.Context, data interface{}) {
// always return http.StatusOK
response := GameResponse{
RetCode: 0,
RetMsg: myerr.GetSuccessMsg(),
SdkErrorCode: 0,
Data: data,
// 分页返回
// 客户端入参 req.PageReqBase
// 服务端返回 req.PageRespBase
func ResponsePageBaseOk(c *gin.Context, data interface{}, nextPageIndex int, hasNextPage bool) {
if data == nil {
data = make([]interface{}, 0)
}
printResponseBody(c, &response)
c.JSON(http.StatusOK, response)
}
func GameResponseFail(c *gin.Context, err *myerr.GameError) {
// always return http.StatusOK
response := GameResponse{
RetCode: err.Code(),
RetMsg: err.Error(),
SdkErrorCode: err.Code(),
Data: nil,
response := Response{
Code: myerr.GetSuccessCode(),
Message: myerr.GetSuccessMsg(),
OperationMessage: myerr.GetSuccessMsg(),
Data: req.PageRespBase{
NextPageIndex: nextPageIndex,
HasNextPage: hasNextPage,
Data: data,
},
}
printResponseBody(c, &response)
c.JSON(http.StatusOK, response)
}
......
package cp_r
import (
"git.hilo.cn/hilo-common/domain"
"git.hilo.cn/hilo-common/mycontext"
"github.com/gin-gonic/gin"
"github.com/jinzhu/now"
"hilo-user/domain/model/cp_m"
"hilo-user/myerr/bizerr"
"hilo-user/req"
"hilo-user/resp"
"time"
)
// @Tags CP v2
// @Summary 排行榜
// @Param token header string true "token"
// @Param nonce header string true "随机数字"
// @Param pageIndex query int true "偏移值 默认:1" default(1)
// @Param pageSize query int true "请求数量 默认:10" default(10)
// @Param queryType path string true "类型:day/week/month"
// @Success 200
// @Router /v2/cp/rank/{queryType} [get]
func CpRank(c *gin.Context) (*mycontext.MyContext, error) {
myCtx := mycontext.CreateMyContext(c.Keys)
pageReq := new(req.PageReqBase)
if err := c.ShouldBindQuery(pageReq); err != nil {
return myCtx, err
}
if pageReq.PageIndex == 0 {
pageReq.PageIndex = 1
}
queryType := c.Param("queryType")
if queryType != "day" && queryType != "week" && queryType != "month" {
return myCtx, bizerr.InvalidParameter
}
var beginDate, endDate string
switch queryType {
case "day":
beginDate, endDate = time.Now().Format("2006-01-02"), time.Now().Format("2006-01-02")
case "week":
beginDate = now.BeginningOfWeek().Format("2006-01-02")
endDate = now.EndOfWeek().Format("2006-01-02")
case "month":
beginDate = now.BeginningOfMonth().Format("2006-01-02")
endDate = now.EndOfMonth().Format("2006-01-02")
}
offset, limit := (pageReq.PageIndex-1)*pageReq.PageSize, pageReq.PageSize
model := domain.CreateModelContext(myCtx)
ranks := cp_m.PageCpDayRank(model, beginDate, endDate, offset, limit)
resp.ResponsePageBaseOk(c, ranks, pageReq.PageIndex+1, len(ranks) < pageReq.PageSize)
return myCtx, nil
}
......@@ -37,9 +37,6 @@ func wrapper(handler HandlerFunc) func(c *gin.Context) {
userId, _ := req.GetUserId(c)
switch h := err.(type) {
case *myerr.GameError:
myContext.Log.Warnf("request user err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.Error())
resp.GameResponseFail(c, h)
case *myerr.BusinessError:
myContext.Log.Warnf("request err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.GetErr())
resp.ResponseBusiness(c, h)
......
......@@ -33,6 +33,7 @@ func InitRouter() *gin.Engine {
{
cp.GET("/space", wrapper(cp_r.CpSpace))
cp.PUT("/privilege/openClose", wrapper(cp_r.CpPrivilegeOpenClose))
cp.GET("/rank/:queryType", wrapper(cp_r.CpRank))
}
inner := r.Group("/inner")
inner.Use(ExceptionHandle, LoggerHandle)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment