package handler import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" "github.com/liangdas/mqant/log" "gorm.io/gorm" "server/call" "server/common" "server/config" "server/db" "server/modules/web/app" "server/modules/web/values" "server/util" "time" ) // 分享信息[done] func ShareInfo(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() if !a.CheckActivityExpire(common.ActivityIDShare) { return } resp := &values.ShareNewInfoResp{} a.Data = resp banners := call.GetConfigShareBanner(a.Channel) for _, v := range banners { resp.Banners = append(resp.Banners, v.URL) } shareInfo := call.GetShareInfo(a.UID) resp.NowLevel = shareInfo.Level resp.NowExp = shareInfo.Exp nextCon := call.GetConfigShare(shareInfo.Level+1, a.Channel) if nextCon != nil { resp.NextExp = nextCon.Exp } else { resp.NextExp = shareInfo.Exp } conShare := call.GetConfigShare(shareInfo.Level, a.Channel) if conShare == nil { a.Code = values.CodeRetry return } resp.ShareLink = call.GetShareLink(a.Channel, a.UID) user, _ := call.GetUserInfo(a.UID) resp.Avatar = user.Avatar // 新手任务弹窗 task := &common.ShareTaskNewData{UID: a.UID} db.Mysql().Get(task) if task.ID == 0 { // 初始化任务 if user.IsOldDevice != 1 { resp.PopNewTask = true } resp.NewReward = conShare.SubNewReward.Amount shareInfo.Reward += conShare.SubNewReward.Amount update := map[string]interface{}{"reward": gorm.Expr("reward + ?", conShare.SubNewReward.Amount)} if conShare.SubNewReward.CanWithdraw { shareInfo.Withdrawable += conShare.SubNewReward.Amount update["withdrawable"] = gorm.Expr("withdrawable + ?", conShare.SubNewReward.Amount) // 新建一个任务标记玩家已经领取过新手奖励 task := &common.ShareTaskNewData{UID: a.UID, TaskID: 1, Type: common.ShareTaskNewTypeFirst, Progress: 1, Target: 1, Reward: 0, Status: 1} db.Mysql().Create(task) } else { con := call.GetConfigShareTaskNew() for _, v := range con { task := &common.ShareTaskNewData{UID: a.UID, TaskID: v.TaskID, Type: v.Type, Progress: 0, Target: v.Target, Reward: v.Reward, Condition: v.Condition} if v.Type == common.ShareTaskNewTypeFirst { task.Progress = 1 } db.Mysql().Create(task) } } db.Mysql().Update(&common.ShareInfo{UID: a.UID}, update) call.WriteShareBalance(&common.ESShareBalance{ Event: common.ShareEventOther, FriendUID: a.UID, AmountType: int(common.CurrencyINR), RefererUID: a.UID, Amount: conShare.SubNewReward.Amount, Level: 1, Balance: conShare.SubNewReward.Amount, }, true) } // 可退出弹窗 //products := call.GetConfigWithdrawProduct(common.WithdrawSorceShare) //if shareInfo.PopWithdraw == 0 && len(products) > 0 && shareInfo.Withdrawable >= products[0].Amount*100 { // resp.PopWithdraw = true // resp.PopWithdrawAmount = products[0].Amount * 100 // shareInfo.PopWithdraw = 1 // db.Mysql().Update(&common.ShareInfo{ID: shareInfo.ID}, map[string]interface{}{"pop_withdraw": 1}) //} resp.Balance = shareInfo.Reward resp.TotalCommission = shareInfo.Withdrawable resp.TotalReferrals = shareInfo.Down1 + shareInfo.Down2 + shareInfo.Down3 + shareInfo.Down4 + shareInfo.Down5 resp.TotalWithdrawals = call.GetShareWithdrawInfo(a.UID).TotalWithdraw * 100 // 昨日收益弹窗 { now := time.Now() t := util.GetZeroTime(now.AddDate(0, 0, -1)).Unix() last := &common.ShareRewardData{UID: a.UID, Time: t} db.Mysql().Get(last) if last.ID > 0 && !util.IsSameDayTimeStamp(now.Unix(), last.PopTime) { db.Mysql().Update(&common.ShareRewardData{UID: a.UID, Time: t}, map[string]interface{}{"pop_time": now.Unix()}) resp.LastReward.Total = last.TotalReward resp.LastReward.Invitation = last.InviteReward resp.LastReward.Recharge = last.RechargeReward resp.LastReward.Affiliate = last.AffiliateReward resp.LastReward.Other = last.OtherReward } } // 升级弹窗 { if shareInfo.LastLevel != shareInfo.Level { db.Mysql().Update(&common.ShareInfo{UID: a.UID}, map[string]interface{}{"last_level": shareInfo.Level}) resp.LevelUpInfo = conShare.GetLevelUpInfo() } } } // 分享新手任务[done] func ShareNewTaskInfo(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() resp := &values.ShareNewTaskInfoResp{} a.Data = resp list := []common.ShareTaskNewData{} db.Mysql().QueryAll(fmt.Sprintf("uid = %d", a.UID), "", &common.ShareTaskNewData{}, &list) for _, v := range list { one := values.OneShareNewTask{ TaskID: v.TaskID, Desc: v.GetDesc(), Type: v.Type, Progess: v.Progress, Target: v.Target, Reward: v.Reward, } if one.Progess >= one.Target || v.Status == 1 { one.Progess = one.Target if v.Status == 1 { one.Status = 2 } else { one.Status = 1 } } resp.TaskList = append(resp.TaskList, one) } } // 新手任务领取[done] func ShareNewTaskDraw(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareNewTaskDrawReq) if !a.S(req) { return } resp := &values.ShareNewTaskDrawResp{} a.Data = resp task := &common.ShareTaskNewData{UID: a.UID, TaskID: req.TaskID} db.Mysql().Get(task) if task.ID == 0 || task.Progress < task.Target { a.Code = values.CodeParam a.Msg = "Task not completed." return } if task.Status == 1 { a.Code = values.CodeParam a.Msg = "Task received." return } rows, err := db.Mysql().UpdateWRes(&common.ShareTaskNewData{}, map[string]interface{}{"status": 1}, fmt.Sprintf("uid = %d and task_id = %d and status = 0", a.UID, req.TaskID)) if rows == 0 || err != nil { a.Code = values.CodeRetry return } s := call.GetShareInfo(a.UID) // 转化奖励 db.Mysql().Update(&common.ShareInfo{UID: a.UID}, map[string]interface{}{"withdrawable": gorm.Expr("withdrawable + ?", task.Reward)}) bal := &common.ESShareBalance{ Event: common.ShareEventOther, AmountType: int(common.CurrencyINR), Amount: task.Reward, RefererUID: a.UID, Level: s.Level, Balance: s.Withdrawable + task.Reward, } call.WriteShareBalance(bal, false) resp.Reward = task.Reward } func ShareNewAffiliate(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareNewAffiliateReq) if !a.S(req) { return } if req.Num > 50 { req.Num = 50 } resp := &values.ShareNewAffiliateResp{} a.Data = resp si := &common.ShareInfo{UID: a.UID} db.Mysql().Get(si) if si.ID == 0 { return } resp.Level1 = si.Down1 resp.Level2 = si.Down2 resp.Level3 = si.Down3 resp.Level4 = si.Down4 resp.Level5 = si.Down5 list := []common.ShareInfo{} sql := fmt.Sprintf("up1 = %d", a.UID) if req.Level > 0 { sql = fmt.Sprintf("up%d = %d", req.Level, a.UID) } resp.Count, _ = db.Mysql().QueryList(req.Page, req.Num, sql, "down1 desc", &common.ShareInfo{}, &list) for _, v := range list { one := values.OneShareNewAffiliate{UID: v.UID, AffiliateCount: v.Down1} p, _ := call.GetUserXInfo(v.UID, "nick", "last_login") one.Nick = p.Nick one.LastLogin = p.LastLogin resp.AffiliateList = append(resp.AffiliateList, one) } } // 收益列表 func ShareNewCommission(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareNewCommissionReq) if !a.S(req) { return } resp := &values.ShareNewCommissionResp{Count: 100, List: []values.OneShareNewCommission{}} a.Data = resp total := &common.ShareRewardData{UID: a.UID} db.Mysql().QueryBySql(fmt.Sprintf("select * from share_reward_data where uid = %d and time = 0", a.UID), total) resp.All = total.TotalReward resp.Invitation = total.InviteReward resp.Affiliate = total.AffiliateReward resp.Recharge = total.RechargeReward resp.Other = total.OtherReward if req.Num*req.Page >= 100 { return } list := []common.ShareRewardData{} db.Mysql().QueryList(0, 100, fmt.Sprintf("uid = %d", a.UID), "time desc", &common.ShareRewardData{}, &list) now := time.Now() zero := util.GetZeroTime(now) if req.Page > 0 { zero = zero.AddDate(0, 0, -req.Page*req.Num) } for i := 0; i < req.Num; i++ { one := values.OneShareNewCommission{Date: zero.Format("20060102")} for _, v := range list { if v.Date == one.Date { one.Invitation = v.InviteReward one.Recharge = v.RechargeReward one.Affiliate = v.AffiliateReward one.Other = v.OtherReward break } } resp.List = append(resp.List, one) zero = zero.AddDate(0, 0, -1) } } // 排行榜 func ShareNewRank(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareNewRankReq) if !a.S(req) { return } resp := &values.ShareNewRankResp{ List: []*common.ShareRank{}, } a.Data = resp now := time.Now() dayNow := now for i := 0; i < 7; i++ { resp.Days = append(resp.Days, dayNow.Format("01/02")) dayNow = dayNow.AddDate(0, 0, -1) } weekNow := util.GetWeekZeroTime(now) for i := 0; i < 4; i++ { resp.Weeks = append(resp.Weeks, fmt.Sprintf("%s-%s", weekNow.Format("01/02"), weekNow.AddDate(0, 0, 7).Format("01/02"))) weekNow = weekNow.AddDate(0, 0, -7) } monthNow := util.GetFirstDateOfMonth(now) for i := 0; i < 3; i++ { resp.Months = append(resp.Months, fmt.Sprintf("%s-%s", monthNow.Format("01/02"), monthNow.AddDate(0, 1, 0).Format("01/02"))) monthNow = monthNow.AddDate(0, -1, 0) } var list []*common.ShareRank resp.Self = &common.ShareRank{ UID: a.UID, Type: req.Type, Rank: -1, } if req.Time == 0 { resp.Self.Time = time.Now().Unix() switch req.Type { case common.ShareRankTypeDaily: list = values.ShareRankDaily case common.ShareRankTypeWeekly: list = values.ShareRankWeekly case common.ShareRankTypeMonthly: list = values.ShareRankMonthly } } else { var ti int64 switch req.Type { case common.ShareRankTypeDaily: ti = util.GetZeroTime(now.AddDate(0, 0, -req.Time)).Unix() case common.ShareRankTypeWeekly: ti = util.GetWeekZeroTime(now.AddDate(0, 0, -req.Time*7)).Unix() case common.ShareRankTypeMonthly: ti = util.GetFirstDateOfMonth(now.AddDate(0, -req.Time, 0)).Unix() } resp.Self.Time = ti list = call.GetShareRank(req.Type, ti) } for i, v := range list { v.Rank = i + 1 if v.UID == a.UID { resp.Self = v } } if resp.Self.Rank == -1 { resp.Self = call.GetShareRewardData(a.UID, req.Type, resp.Self.Time) resp.Self.Rank = -1 } start := req.Page * req.Num if start > common.ShareRankMaxNum { return } if start > len(list) { return } end := start + req.Num if end > common.ShareRankMaxNum { end = common.ShareRankMaxNum } if end > len(list) { end = len(list) } resp.List = list[start:end] } // 限时任务 func ShareLimitTaskInfo(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() resp := &values.ShareLimitTaskInfoResp{} a.Data = resp si := call.GetShareInfo(a.UID) tasks := []*common.ShareLimitTaskData{} db.Mysql().QueryBySql(fmt.Sprintf("select * from share_limit_task_data where uid = %d order by level asc", a.UID), &tasks) now := time.Now().Unix() var task *common.ShareLimitTaskData for i := 1; i <= si.Level; i++ { var thisTask *common.ShareLimitTaskData for _, v := range tasks { if v.Level == i { thisTask = v break } } if thisTask == nil { // 当前等级还未创建 conTask := call.GetConfigShareLimitTask(i, a.Channel) if conTask != nil { thisTask = &common.ShareLimitTaskData{} thisTask.UID = a.UID thisTask.Level = i thisTask.CreateTime = now thisTask.Time = conTask.Time thisTask.Status = 0 thisTask.Reward = conTask.Reward db.Mysql().Create(thisTask) if i <= si.Level && task == nil { task = thisTask } } } else if thisTask.IsValid() && task == nil { task = thisTask } } exLevel := si.Level nextLevel := si.Level + 1 if task != nil { exLevel = task.Level nextLevel = task.Level + 1 resp.TimeLeft = task.CreateTime + task.Time*60 - now resp.Reward = task.Reward } conShareEx := call.GetConfigShare(exLevel, a.Channel) conShare := call.GetConfigShare(nextLevel, a.Channel) if conShare == nil { conShare = conShareEx } resp.NowLevel = conShareEx.GetLevelUpInfo() resp.NextLevel = conShare.GetLevelUpInfo() resp.Exp = si.Exp resp.LevelUpExp = conShare.Exp if resp.LevelUpExp < 0 { resp.LevelUpExp = resp.Exp } resp.CanDraw = task != nil && si.Exp >= resp.LevelUpExp } func ShareLimitTaskDraw(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareLimitTaskDrawReq) if !a.S(req) { return } resp := &values.ShareLimitTaskDrawResp{} a.Data = resp task := &common.ShareLimitTaskData{UID: a.UID, Level: req.NowLevel} db.Mysql().Get(task) if !task.IsValid() { a.Code = values.CodeParam a.Msg = "Invalid draw." return } si := call.GetShareInfo(a.UID) if si.Level <= task.Level { // 不可领取 a.Code = values.CodeParam a.Msg = "Invalid draw." return } rows, err := db.Mysql().UpdateWRes(&common.ShareLimitTaskData{}, map[string]interface{}{"status": 1}, fmt.Sprintf("uid = %d and level = %d and status = 0", a.UID, task.Level)) if err != nil || rows == 0 { a.Code = values.CodeParam a.Msg = "Invalid draw." return } db.Mysql().Update(&common.ShareInfo{UID: a.UID}, map[string]interface{}{"reward": gorm.Expr("reward + ?", task.Reward), "withdrawable": gorm.Expr("withdrawable + ?", task.Reward)}) call.WriteShareBalance(&common.ESShareBalance{ Event: common.ShareEventOther, // FriendUID: , AmountType: int(common.CurrencyINR), Amount: task.Reward, RefererUID: a.UID, Level: si.Level, Balance: si.Reward + task.Reward, }, true) resp.Reward = task.Reward } func ShareNewWithdrawInfo(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() resp := &values.ShareNewWithdrawInfoResp{Tips: call.GetConfigPlatform().WithdrawTips} a.Data = resp si := call.GetShareInfo(a.UID) resp.TotalBalance = si.Reward resp.Withdrawable = si.Withdrawable list := call.GetConfigWithdrawProduct(common.WithdrawSorceShare) db.Mysql().QueryList(0, 3, fmt.Sprintf("uid = %d and draw_type = '%s'", a.UID, common.WithdrawTypeBank), "id desc", &common.PayInfo{}, &resp.Accounts) sw := call.GetShareWithdrawInfo(a.UID) resp.WithDrawCount = sw.DayCount for _, v := range list { // todo one := &values.WithdrawProduct{ID: v.ProductID, Amount: v.Amount} resp.List = append(resp.List, one) } con := call.GetConfigShare(si.Level, a.Channel) if con == nil { a.Code = values.CodeRetry return } resp.TotalWithdrawCount = con.DayWithdrawCount channels := call.GetConfigWithdrawChannels() if len(channels) > 0 { resp.NewList = []*common.ConfigWithdrawChannels{channels[0]} } else { resp.NewList = []*common.ConfigWithdrawChannels{} } } func ShareNewWithdraw(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.WithdrawReq) if !a.S(req) { return } if req.CurrencyType != common.CurrencyINR { req.CurrencyType = common.CurrencyINR } one := call.GetConfigWithdrawProductByID(req.AmountID) if one == nil { a.Code = values.CodeParam a.Msg = "Withdraw product not found." return } uid := a.UID log.Debug("player %v withdraw %+v,one:%+v", uid, *req, *one) amount := one.Amount * 100 si := call.GetShareInfo(uid) if si.Withdrawable < amount { a.Code = values.CodeParam a.Msg = "Insufficient balance." return } con := call.GetConfigShare(si.Level, a.Channel) if con == nil { a.Code = values.CodeRetry return } sw := call.GetShareWithdrawInfo(uid) if sw.DayCount >= con.DayWithdrawCount { a.Code = values.CodeParam a.Msg = "Withdrawal limit." return } // 到游戏账户 if req.Type == 1 { tx := db.Mysql().Begin() defer a.MCommit(tx) // 更新余额 res := tx.Model(&common.ShareInfo{}).Where("uid = ? and reward >= ? and withdrawable >= ?", uid, amount, amount). Updates(map[string]interface{}{ "reward": gorm.Expr("reward - ?", amount), "withdrawable": gorm.Expr("withdrawable - ?", amount), }) if res.RowsAffected == 0 || res.Error != nil { log.Error("err:%v", res.Error) a.Code = values.CodeRetry return } // 更新次数 res = tx.Model(&common.ShareWithdrawInfo{}).Where("uid = ? and day_time = ?", uid, sw.DayTime). Updates(map[string]interface{}{"day_count": sw.DayCount + 1, "day_time": time.Now().Unix(), "total_withdraw": gorm.Expr("total_withdraw + ?", one.Amount)}) if res.RowsAffected == 0 || res.Error != nil { log.Error("err:%v", res.Error) a.Code = values.CodeRetry return } // 更新rechargeinfo,转移到游戏等同于充值 re := call.GetRechargeInfo(uid) if re.ID == 0 { res = tx.Model(&common.RechargeInfo{}).Create(&common.RechargeInfo{UID: uid, TotalRecharge: one.Amount}) } else { res = tx.Model(&common.RechargeInfo{}).Where("uid = ? ", uid). Updates(map[string]interface{}{ "total_charge": gorm.Expr("total_charge + ?", one.Amount), }) } if res.RowsAffected == 0 || res.Error != nil { log.Error("err:%v", res.Error) a.Code = values.CodeRetry return } db.Mysql().Create(&common.RechargeOrder{ UID: uid, OrderID: util.NewOrderID(uid), APIPayID: "", // ProductID: common.ActivityIDPddShare, Amount: one.Amount, WithdrawCash: amount, Status: common.StatusROrderFinish, PaySource: common.PaySourceModulePay, Event: int(common.CurrencyEventShareWithdraw), // PayAccount: payInfo, // Extra: strconv.FormatInt(serviceFee, 10), CallbackTime: time.Now().Unix(), ChannelID: a.Channel, UPI: -1, Scene: common.ActivityIDShare, }) _, err := call.UpdateCurrencyPro(&common.UpdateCurrency{ CurrencyBalance: &common.CurrencyBalance{ UID: uid, Value: amount * -1, Event: common.CurrencyEventShareWithdraw, Type: common.CurrencyINR, }, }) if err != nil { a.Code = values.CodeRetry return } a.Msg = "Withdraw to game successfully." return } ip := a.GetRemoteIP() payInfo, code := NewWithdraw(req, a.UID, ip, a.UUID) if code != values.CodeOK { a.Code = code a.Msg = payInfo return } tx := db.Mysql().Begin() defer a.MCommit(tx) // 发起tx // 更新余额 res := tx.Model(&common.ShareInfo{}).Where("uid = ? and reward >= ? and withdrawable >= ?", uid, amount, amount). Updates(map[string]interface{}{ "reward": gorm.Expr("reward - ?", amount), "withdrawable": gorm.Expr("withdrawable - ?", amount), }) if res.RowsAffected == 0 || res.Error != nil { log.Error("err:%v", res.Error) a.Code = values.CodeRetry return } // 更新次数 sw.SubRecord[one.Amount]++ byt, _ := json.Marshal(sw.SubRecord) res = tx.Model(&common.ShareWithdrawInfo{}).Where("uid = ? and day_time = ?", uid, sw.DayTime). Updates(map[string]interface{}{"day_count": sw.DayCount + 1, "day_time": time.Now().Unix(), "record": string(byt), "total_withdraw": gorm.Expr("total_withdraw + ?", one.Amount)}) if res.RowsAffected == 0 || res.Error != nil { log.Error("err:%v", res.Error) a.Code = values.CodeRetry return } orderID := util.NewOrderID(uid) order := &common.RechargeOrder{ UID: uid, OrderID: orderID, APIPayID: "", ProductID: one.ProductID, Amount: one.Amount, WithdrawCash: amount, Status: common.StatusROrderCreate, PaySource: common.PaySourceModulePay, Event: int(common.CurrencyEventWithDraw), PayAccount: payInfo, // Extra: strconv.FormatInt(serviceFee, 10), ChannelID: a.Channel, UPI: -1, Scene: common.ActivityIDShare, } if config.GetBase().Release && amount < con.WithdrawAudit { order.Status = common.StatusROrderWaitting } if err := tx.Model(order).Create(order).Error; err != nil { a.Code = values.CodeRetry log.Error("create withdraw order fail err:%v", err) return } a.Data = values.ShareNewWithdrawResp{TotalBalance: si.Reward - amount, Withdrawable: si.Withdrawable - amount} } func ShareNewWithdrawHis(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() req := new(values.ShareNewWithdrawHisReq) if !a.S(req) { return } if req.Num > 100 { req.Num = 100 } resp := &values.ShareNewWithdrawHisResp{} a.Data = resp list, count := call.GetShareWithdrawHis(a.UID, req.Page, req.Num) resp.Count = count for i, v := range list { if v.Status <= common.StatusROrderCreate { list[i].Status = common.StatusROrderPay } else if v.Status == common.StatusROrderRefuse || v.Status == common.StatusROrderCancel { list[i].Status = common.StatusROrderFail } one := common.WithdrawCommon{} if v.PayAccount != "" { err := json.Unmarshal([]byte(v.PayAccount), &one) if err != nil { log.Error("err:%v", err) continue } } list[i].PayAccount = one.BankCardNo resp.List = append(resp.List, values.OneShareNewWithdrawHis{ CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"), OrderID: v.OrderID, PayAccount: v.PayAccount, UID: v.UID, Amount: v.Amount, Event: v.Event, ProductID: v.ProductID, Status: v.Status, FailReason: v.FailReason, ChannelID: v.ChannelID, UPI: v.UPI, Scene: v.Scene, WithdrawCash: v.WithdrawCash, }) } } func ShareNewBroadcast(c *gin.Context) { a := app.NewApp(c) defer func() { a.Response() }() // req := new(values.ShareNewBroadcastReq) // if !a.S(req) { // return // } // if req.Num > 100 { // req.Num = 100 // } resp := &values.ShareNewBroadcastResp{List: values.ShareWithdrawBroadcast} a.Data = resp }