You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

661 lines
20 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package users
import (
"encoding/json"
"fmt"
"recook/internal/back"
"recook/internal/cache"
"recook/internal/dbc"
"recook/internal/model/aftersales"
"recook/internal/model/coupon"
"recook/internal/model/goods"
"recook/internal/model/order"
"recook/internal/model/user"
"recook/internal/service/app/orders"
"recook/internal/service/app/tree"
"recook/internal/service/comFunc"
"recook/internal/v2/model/company"
"recook/internal/v2/model/jyy"
manage "recook/internal/v2/model/recook/order"
"recook/tools"
"time"
"github.com/astaxie/beego"
"github.com/golangkit/formatime"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/shopspring/decimal"
)
type MyInfoReq struct {
UserID uint `json:"userId" validate:"numeric"`
}
type MyInfoResp struct {
Balance decimal.Decimal `json:"balance"` // 余额
Notify Notify `json:"notify"` // 通知
RoleLevel int `json:"roleLevel"` // 角色
MyAssets MyAssets `json:"myAssets"`
MyShopping MyShopping `json:"myShopping"`
ShareIncome ShareIncome `json:"shareIncome"`
TeamIncome TeamIncome `json:"teamIncome"`
OrderCenter OrderCenter `json:"orderCenter"`
Identifier string `json:"identifier"` //编号
Secret uint `json:"secret"`
Level int `json:"level"`
IsOffline bool `json:"is_offline"`
Start *time.Time `json:"start"`
End *time.Time `json:"end"`
Deposit decimal.Decimal `json:"deposit"`
IsEnterprise bool `json:"is_enterprise"`
AllDeposit decimal.Decimal `json:"all_deposit"`
Tax string `json:"tax"`
}
type Notify struct {
IsNotify bool `json:"isNotify"`
NotifyType string `json:"notifyType"`
NotifyContent string `json:"notifyContent"`
}
type MyAssets struct {
CouponNum int `json:"couponNum"`
CoinNum decimal.Decimal `json:"coinNum"`
Cards int `json:"cards"`
}
type MyShopping struct {
OrderNum uint `json:"orderNum"`
Amount decimal.Decimal `json:"amount"`
HistoryIncome decimal.Decimal `json:"historyIncome"`
}
type ShareIncome struct {
OrderNum uint `json:"orderNum"`
Amount decimal.Decimal `json:"amount"`
HistoryIncome decimal.Decimal `json:"historyIncome"`
}
type TeamIncome struct {
OrderNum decimal.Decimal `json:"orderNum"` // 团队销售额
Amount decimal.Decimal `json:"amount"` // 累计收益
HistoryIncome int `json:"historyIncome"` // 团队成员
}
type OrderCenter struct {
WaitPay int `json:"waitPay"`
WaitSend int `json:"waitSend"`
WaitRecv int `json:"waitRecv"`
AfterSales int `json:"afterSales"`
EvaNum int `json:"eva_num"`
AfterNum int `json:"after_num"`
CollectionNum int `json:"collection_num"`
SaleWaitDeal int `json:"sale_wait_deal"`
SaleWaitPay int `json:"sale_wait_pay"`
SaleWaitSend int `json:"sale_wait_send"`
SaleWaitRecv int `json:"sale_wait_recv"`
}
//计算总金额用的
type tempAcount struct {
Amount decimal.Decimal `json:"amount"`
}
// MyInfo 我的 首页
func MyInfo(c *gin.Context) {
var p MyInfoReq
err := tools.ParseParams(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
// -- 特殊操作
if p.UserID == 0 {
back.Suc(c, "操作成功", nil)
return
}
var userInfo user.Information
if err := dbc.DB.First(&userInfo, p.UserID).Error; err != nil {
back.Fail(c, "用户错误1"+err.Error())
return
}
//var ur = user_role.UserRole{RbacID: userInfo.RoleId}
//_ = ur.GetRoleInfoByID()
var uWallet user.Wallet
if err := dbc.DB.Where("user_id = ?", p.UserID).First(&uWallet).Error; err != nil {
back.Fail(c, "用户错误"+err.Error())
return
}
var uWallet2 jyy.UserWallet
dbc.DB.Where("user_id = ?", p.UserID).First(&uWallet2)
allDeposit := make([]decimal.Decimal, 0)
dbc.DB.Table((&jyy.UserWalletApply{}).TableName()).Select("IFNULL(SUM(amount), 0) as total").
Where("user_id = ?", p.UserID).
Where("state = 2").
Pluck("total", &allDeposit)
// 优惠券是 未使用和未过期的
var couponNum int
dbc.DB.Model(&coupon.ReceiverMid{}).Where("user_id = ? and status = 0 and end_time > ?", p.UserID, time.Now()).Count(&couponNum)
var cards int
dbc.DB.Model(&user.IntroHistory{}).Where("intro_code = ? and up_code_used = ?", userInfo.IntroCode, user.TheCodeNotUsed).Count(&cards)
// ------- 自购收益
var msData = myShoppingData(p.UserID)
cache.SetTmpData(p.UserID, cache.TmpSelfType, msData)
juniors := tree.GetTheJuniorUsers(p.UserID)
// ---- ShareIncome 分享收益
var siData = shareIncomeData(p.UserID)
cache.SetTmpData(p.UserID, cache.TmpShareType, siData)
// ---- TeamIncome 团队收益
var tiData = teamIncomeData(p.UserID, juniors)
cache.SetTmpData(p.UserID, cache.TmpTeamType, siData)
//dbc.DB.Model(&order.Information{}).Select("sum(goods_total_amount) as amount").Where("user_id in (?) and status = 4", juniors).Scan(&tiData)
//
//dbc.DB.Model(&user.CoinHistory{}).Select("count(*) order_num, sum(coin_num) as history_income").Where("user_id in (?) and coin_type = ?", juniors, user.RoleTypeForCoinHistory).Scan(&tiData)
// ---- OrderCenter
var waitPay, waitSend, waitRecv, afterSalesCount = orders.Center(p.UserID)
var waitPay1, waitSend1, waitRecv1, waitDeal1 = orders.SaleCenter(p.UserID)
//评价数量
var evaNum int64
//dbc.DB.Table((&goods.Evaluation{}).TableName()).Where("user_id=?", userInfo.ID).Count(&evaNum)
dbc.DB.Table((&manage.RecookOrderGoodsDetailModel{}).TableName()).Where("user_id=?", userInfo.ID).
Where("evaluated_id=0").Where("pay_status=1").Where("express_status=2").Count(&evaNum)
//// 通知
//isNotify, content := cache.UpNotify(int(p.UserID))
//if isNotify == true {
// if len(content) == 0 {
// content = user_role.CongratulationWord(ur.Info.RoleLevel)
// }
//}
//售后中数量
var afterNum int64
dbc.DB.Table((&aftersales.Goods{}).TableName()).Where("user_id=?", p.UserID).Where("return_status<>5").Count(&afterNum)
//收藏数量
var collectNum int64
dbc.DB.Table((&goods.Favorites{}).TableName()).Where("user_id=?", p.UserID).Count(&collectNum)
var company company.Info
dbc.DB.First(&company, "user_id = ?", userInfo.ID)
// 组装返回
var res = MyInfoResp{
Balance: uWallet.Balance,
Deposit: uWallet2.Deposit,
AllDeposit: allDeposit[0],
Notify: Notify{
IsNotify: false,
NotifyType: "up", // 暂时只有升级类型,估计以后会加需求,保级之类的预留
NotifyContent: "",
},
RoleLevel: 0,
MyAssets: MyAssets{
CouponNum: couponNum,
CoinNum: uWallet.Coin,
Cards: cards,
},
MyShopping: MyShopping{
OrderNum: msData.OrderNum,
Amount: msData.Amount,
HistoryIncome: msData.HistoryIncome,
},
ShareIncome: ShareIncome{
OrderNum: siData.OrderNum,
Amount: siData.Amount,
HistoryIncome: siData.HistoryIncome,
},
TeamIncome: TeamIncome{
OrderNum: tiData.Amount,
Amount: tiData.OrderNum,
HistoryIncome: tiData.HistoryIncome,
},
OrderCenter: OrderCenter{
WaitPay: waitPay,
WaitSend: waitSend,
WaitRecv: waitRecv,
AfterSales: afterSalesCount,
EvaNum: int(evaNum),
AfterNum: int(afterNum),
CollectionNum: int(collectNum),
SaleWaitDeal: waitDeal1,
SaleWaitPay: waitPay1,
SaleWaitSend: waitSend1,
SaleWaitRecv: waitRecv1,
},
Identifier: userInfo.Identifier[:len(userInfo.Identifier)-2],
Secret: userInfo.Secret,
Level: userInfo.Level,
IsOffline: userInfo.IsOffline,
Start: &userInfo.VipUpgradeStart.Time,
End: &userInfo.VipUpgradeEnd.Time,
IsEnterprise: userInfo.IsEnterprise,
Tax: company.TaxType,
}
back.Suc(c, "操作成功", &res)
return
}
func myShoppingData(userId uint) (msData MyShopping) {
var shopCoin []user.CoinHistory
dbc.DB.Select("coin_num, order_id").Where("user_id = ? and coin_type = ?", userId,
user.SelfShoppingTypeForCoinHistory).Find(&shopCoin)
msData.OrderNum = uint(len(shopCoin))
var shopOrderIds []uint
for _, val := range shopCoin {
msData.HistoryIncome = msData.HistoryIncome.Add(val.CoinNum)
shopOrderIds = append(shopOrderIds, val.OrderId)
}
if msData.OrderNum > 0 {
dbc.DB.Model(&order.GoodsDetail{}).Select("sum(goods_amount) as amount").Where(" order_id in (?) and ass_type=0 ", shopOrderIds).Scan(&msData)
//dbc.DB.Model(&order.Information{}).Select("sum(goods_total_amount) as amount").Where("id in (?)", shopOrderIds).Scan(&msData)
}
return
}
func shareIncomeData(userId uint) (siData ShareIncome) {
var shareCoin []user.CoinHistory
dbc.DB.Select("coin_num, order_id").Where("user_id = ? and coin_type = ?", userId, user.RoleTypeForCoinHistory).Find(&shareCoin)
siData.OrderNum = uint(len(shareCoin))
var shareOrderIds []uint
for _, val := range shareCoin {
siData.HistoryIncome = siData.HistoryIncome.Add(val.CoinNum)
shareOrderIds = append(shareOrderIds, val.OrderId)
}
if siData.OrderNum > 0 {
dbc.DB.Model(&order.GoodsDetail{}).Select("sum(goods_amount) as amount").Where(" order_id in (?) and ass_type=0 ", shareOrderIds).Scan(&siData)
}
return
}
func teamIncomeData(userId uint, juniors []uint) (tiData TeamIncome) {
var coinHistory []user.CoinHistory
dbc.DB.Where("user_id = ? and coin_type = ?", userId, user.TeamTypeForCoinHistory).Find(&coinHistory)
tiData.HistoryIncome = len(juniors)
var orderIds = make([]uint, len(coinHistory))
for _, val := range coinHistory {
orderIds = append(orderIds, val.OrderId)
tiData.OrderNum = tiData.OrderNum.Add(val.CoinNum)
}
if len(orderIds) > 0 {
dbc.DB.Model(&order.Information{}).Select("SUM(actual_total_amount + coin_total_amount) as amount").
Where("status=4 and user_id IN (?) ", juniors).Scan(&tiData)
//dbc.DB.Model(&order.GoodsDetail{}).Select("sum(goods_amount) as amount").Where(" order_id in (?) and ass_type=0 ", orderIds).Scan(&tiData)
}
return
}
// IncomeFromSelfReq 自购二级页面
type IncomeFromSelfReq struct {
UserID uint `json:"userId" validate:"numeric"`
Date string `json:"date" validate:"omitempty,len=7"`
OrderBy string `json:"orderBy"`
}
type IncomeFromSelfResp struct {
MyShopping MyShopping `json:"myShopping"`
Date string `json:"date"`
CoinNum decimal.Decimal `json:"coinNum"`
List []MyShoppingWithTime `json:"list"`
}
type MyShoppingWithTime struct {
Time formatime.Date `json:"time"`
MyShopping
}
func IncomeFromSelf(c *gin.Context) {
var p IncomeFromSelfReq
err := tools.ParseParams(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
var beginDate, endDate time.Time
if len(p.Date) != 7 {
beginDate = comFunc.GetTheFirstDayOfMonth(time.Now())
endDate = comFunc.GetTheFirstDayOfMonth(time.Now().AddDate(0, 1, 0))
} else {
beginDate, err = time.Parse("2006-01", p.Date)
if err != nil {
back.Fail(c, "date error:"+err.Error())
return
}
if beginDate.After(time.Now()) {
back.Fail(c, "时间超出范围")
return
}
endDate = beginDate.AddDate(0, 1, 0)
}
var msData MyShopping
// if res, ok := cache.GetTmpData(p.UserID, cache.TMP_SELF_TYPE); !ok {
// msData = myShoppingData(p.UserID)
// } else {
// err := json.Unmarshal([]byte(res), &msData)
// if err != nil {
// comFunc.PrintErr("IncomeFromSelf json error:", err)
msData = myShoppingData(p.UserID)
// }
// }
// var uWallet user.Wallet
// if err := dbc.DB.Where("user_id = ?", p.UserID).First(&uWallet).Error; err != nil {
// http.Fail(c, "用户错误"+err.Error())
// return
// }
type CoinTotalHistory struct {
CoinTotal decimal.Decimal
}
var coinHistoryTotal CoinTotalHistory
if err := dbc.DB.Model(&user.CoinHistory{}).Select("sum(coin_num) as coin_total").Where("user_id = ? and coin_type = 3", p.UserID).Scan(&coinHistoryTotal).Error; err != nil {
back.Fail(c, "用户错误"+err.Error())
return
}
var coinTotalHistory decimal.Decimal
var cHistory []user.CoinHistory
dbc.DB.Where("user_id = ? and coin_type = ? and created_at between ? and ?", p.UserID, user.SelfShoppingTypeForCoinHistory, beginDate, endDate).Find(&cHistory)
// 组装数据
var list []MyShoppingWithTime
var myTempAcount tempAcount
for start := beginDate; endDate.After(start); start = start.AddDate(0, 0, 1) {
var tmpData MyShoppingWithTime
tmpData.Time = formatime.NewDateFrom(start)
for _, val := range cHistory {
if val.CreatedAt.Time.Day() == start.Day() {
tmpData.OrderNum++
//这边将退款的商品的金额排除recook_coin_historyorder_id
dbc.DB.Model(&order.GoodsDetail{}).Select("sum(goods_amount) as amount").Where(" order_id in (?) and ass_type=0 ", val.OrderId).Scan(&myTempAcount)
tmpData.Amount = tmpData.Amount.Add(myTempAcount.Amount)
tmpData.HistoryIncome = tmpData.HistoryIncome.Add(val.CoinNum)
coinTotalHistory = coinTotalHistory.Add(val.CoinNum)
fmt.Println(tmpData.HistoryIncome, val.CoinNum)
}
}
list = append(list, tmpData)
if start.AddDate(0, 0, 1).After(time.Now()) {
break
}
}
//如果是倒序
if p.OrderBy == "desc" {
length := len(list)
for i := 0; i < length/2; i++ {
temp := list[length-1-i]
list[length-1-i] = list[i]
list[i] = temp
}
}
bs, _ := json.Marshal(IncomeFromSelfResp{
MyShopping: msData,
Date: beginDate.Format("2006-01"),
CoinNum: coinTotalHistory,
List: list,
})
beego.Info(string(bs))
msData.HistoryIncome = coinHistoryTotal.CoinTotal
back.Suc(c, "操作成功", IncomeFromSelfResp{
MyShopping: msData,
Date: beginDate.Format("2006-01"),
CoinNum: coinTotalHistory,
List: list,
})
}
// IncomeFromShareReq 分享二级页面
type IncomeFromShareReq struct {
UserID uint `json:"userId" validate:"numeric"`
Date string `json:"date" validate:"omitempty,len=7"`
OrderBy string `json:"orderBy"`
}
type IncomeFromShareResp struct {
ShareIncome ShareIncome `json:"myShopping"`
Date string `json:"date"`
CoinNum decimal.Decimal `json:"coinNum"`
List []ShareIncomeWithTime `json:"list"`
}
type ShareIncomeWithTime struct {
Time formatime.Date `json:"time"`
ShareIncome
}
func IncomeFromShare(c *gin.Context) {
var p IncomeFromShareReq
err := tools.ParseParams(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
var beginDate, endDate time.Time
if len(p.Date) != 7 {
beginDate = comFunc.GetTheFirstDayOfMonth(time.Now())
endDate = comFunc.GetTheFirstDayOfMonth(time.Now().AddDate(0, 1, 0))
} else {
beginDate, err = time.Parse("2006-01", p.Date)
if err != nil {
back.Fail(c, "date error:"+err.Error())
return
}
if beginDate.After(time.Now()) {
back.Fail(c, "时间超出范围")
return
}
endDate = beginDate.AddDate(0, 1, 0)
}
var siData ShareIncome
// if res, ok := cache.GetTmpData(p.UserID, cache.TMP_SELF_TYPE); !ok {
// siData = shareIncomeData(p.UserID)
// } else {
// err := json.Unmarshal([]byte(res), &siData)
// if err != nil {
// comFunc.PrintErr("IncomeFromSelf json error:", err)
siData = shareIncomeData(p.UserID)
// }
// }
var totalCoin decimal.Decimal
// type CoinTotalHistory struct {
// CoinTotal decimal.Decimal
// }
// var coinHistoryTotal CoinTotalHistory
// if err := dbc.DB.Model(&user.CoinHistory{}).Select("sum(coin_num) as coin_total").Where("user_id = ? and coin_type = ?", p.UserID, user.ShareTypeForCoinHistory).Scan(&coinHistoryTotal).Error; err != nil {
// http.Fail(c, "用户错误"+err.Error())
// return
// }
var cHistory []user.CoinHistory
dbc.DB.Where("user_id = ? and coin_type = ? and created_at between ? and ?", p.UserID, user.ShareTypeForCoinHistory, beginDate, endDate).Find(&cHistory)
// 组装数据
var list []ShareIncomeWithTime
for start := beginDate; endDate.After(start); start = start.AddDate(0, 0, 1) {
var tmpData ShareIncomeWithTime
tmpData.Time = formatime.NewDateFrom(start)
var myTempAcount tempAcount
for _, val := range cHistory {
if val.CreatedAt.Time.Day() == start.Day() {
tmpData.OrderNum++
dbc.DB.Model(&order.GoodsDetail{}).Select("sum(goods_amount) as amount").Where(" order_id in (?) and ass_type=0 ", val.OrderId).Scan(&myTempAcount)
tmpData.Amount = tmpData.Amount.Add(myTempAcount.Amount)
tmpData.HistoryIncome = tmpData.HistoryIncome.Add(val.CoinNum)
totalCoin = totalCoin.Add(val.CoinNum)
}
}
list = append(list, tmpData)
if start.AddDate(0, 0, 1).After(time.Now()) {
break
}
}
//如果是倒序
if p.OrderBy == "desc" {
length := len(list)
for i := 0; i < length/2; i++ {
temp := list[length-1-i]
list[length-1-i] = list[i]
list[i] = temp
}
}
bs, _ := json.Marshal(IncomeFromShareResp{
ShareIncome: siData,
Date: beginDate.Format("2006-01"),
CoinNum: totalCoin,
List: list,
})
beego.Info(string(bs))
back.Suc(c, "操作成功", IncomeFromShareResp{
ShareIncome: siData,
Date: beginDate.Format("2006-01"),
CoinNum: totalCoin,
List: list,
})
}
// IncomeFromTeamReq 团队收益 二级页面
type IncomeFromTeamReq struct {
UserID uint `json:"userId" validate:"numeric"`
Date string `json:"date" validate:"len=7"`
OrderBy string `json:"orderBy" validate:"omitempty,oneof=asc desc"`
}
type IncomeFromTeamResp struct {
TeamIncomeSub TeamIncomeSub `json:"teamIncome"`
Date string `json:"date"`
IncomeDetail user.RecookUserBenefit `json:"incomeDetail"`
Billboard []billboard `json:"billboard"`
}
type TeamIncomeSub struct {
TeamAmount decimal.Decimal `json:"teamAmount"` // 团队销售额
HistoryIncome decimal.Decimal `json:"historyIncome"` // 累计收益
MemberNum int `json:"memberNum"` // 团队成员
}
type billboard struct {
UserId uint `json:"userId"`
HeadImgUrl string `json:"headImgUrl"`
Username string `json:"username"`
Mobile string `json:"mobile"`
RoleLevel int `json:"roleLevel"`
Amount decimal.Decimal `json:"amount"`
}
func IncomeFromTeam(c *gin.Context) {
var p IncomeFromTeamReq
err := tools.ParseParams(&p, c)
if err != nil {
back.Fail(c, err.Error())
return
}
//p.UserID = 13
var beginDate, endDate time.Time
if len(p.Date) != 7 {
beginDate = comFunc.GetTheFirstDayOfMonth(time.Now().AddDate(0, -1, 0))
endDate = comFunc.GetTheFirstDayOfMonth(time.Now())
} else {
beginDate, err = time.Parse("2006-01", p.Date)
if err != nil {
back.Fail(c, "date error:"+err.Error())
return
}
if beginDate.After(time.Now().AddDate(0, -1, 0)) {
back.Fail(c, "未到结算时间")
return
}
endDate = beginDate.AddDate(0, 1, 0)
}
juniors := tree.GetTheJuniorUsers(p.UserID)
var tiData TeamIncomeSub
var tiDataTmp TeamIncome
if res, ok := cache.GetTmpData(p.UserID, cache.TmpTeamType); !ok {
tiDataTmp = teamIncomeData(p.UserID, juniors)
tiData.HistoryIncome = tiDataTmp.OrderNum //这个是销售额
tiData.TeamAmount = tiDataTmp.Amount //这个是累计收益
tiData.MemberNum = tiDataTmp.HistoryIncome //这个是团队成员
} else {
err := json.Unmarshal([]byte(res), &tiDataTmp)
if err != nil {
comFunc.PrintErr("IncomeFromSelf json error:", err)
tiDataTmp = teamIncomeData(p.UserID, juniors)
}
tiData.HistoryIncome = tiDataTmp.OrderNum
tiData.TeamAmount = tiDataTmp.Amount
tiData.MemberNum = tiDataTmp.HistoryIncome
}
var userBenefit user.RecookUserBenefit
err = dbc.DB.Where("user_id = ? and period between ? and ?", p.UserID, beginDate, endDate).Find(&userBenefit).Error
ret := IncomeFromTeamResp{
TeamIncomeSub: tiData,
Date: beginDate.Format("2006-01"),
IncomeDetail: userBenefit,
}
if gin.Mode() == "debug" {
err = nil
}
if err == nil {
var bbd []billboard
if len(p.OrderBy) <= 0 {
p.OrderBy = "ASC"
} else {
}
dbc.DB.Model(&order.Information{}).
Select("`recook_user_info`.mobile, `recook_user_info`.nickname as username, `recook_user_info`.head_img_url as head_img_url, `recook_user_info`.id as user_id, SUM(actual_total_amount + coin_total_amount) as amount").
Where("status=4 and user_id IN (?) and pay_time >= ? and pay_time < ? ", juniors, beginDate, endDate).
Joins("left join `recook_user_info` on `recook_user_info`.id = `recook_order_info`.user_id").
Joins("left join `recook_user_rbac_role` on `recook_user_info`.role_id = `recook_user_rbac_role`.id").
Group("`recook_order_info`.user_id").Order("amount " + p.OrderBy).Limit(50).Scan(&bbd)
ret.Billboard = bbd
} else if err == gorm.ErrRecordNotFound {
} else {
back.Fail(c, "操作失败")
return
}
ret.IncomeDetail.Percent = ret.IncomeDetail.Percent.Mul(decimal.NewFromInt(100))
back.Suc(c, "操作成功", &ret)
}