互动
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.

610 lines
17 KiB

package client
import (
"encoding/json"
"fmt"
"hudongzhuanjia/controllers"
"hudongzhuanjia/models"
"hudongzhuanjia/utils"
"hudongzhuanjia/utils/code"
"hudongzhuanjia/utils/define"
"strings"
"git.ouxuan.net/tommy/osmanthuswine/src/core"
)
type OrderEntryCtl struct {
controllers.AuthorCtl
}
// 用户查看所有商品
func (t *OrderEntryCtl) List() {
_type := t.GetAccountType()
uid := t.GetAccountId()
activityId := t.MustGetInt("activity_id")
areaId := 0
if _type == define.TYPE_ENTRYPEOPLE {
entryPerson := models.OrderEntryPerson{}
exist, err := models.Get(&entryPerson, uid)
t.CheckErr(err)
t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员信息异常")
areaId = entryPerson.AreaId
} else {
areaId = t.MustGetInt("area_id")
}
area := &models.AreaStore{}
exist, err := models.Get(area, areaId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
if area.IsMainArea != 1 && area.AreaGoodsRuleSwitch != 1 {
exist, err = area.GetMainAreaById(activityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
}
// 库存
goods, err := models.GetGoodsByActivityId(activityId, area.Id)
t.CheckErr(err)
goodIds := make([]int, 0)
for _, g := range goods {
goodIds = append(goodIds, g.Id)
}
res, err := models.GetSubOrderGoodNum(goodIds)
t.CheckErr(err)
for index := range goods {
url := fmt.Sprintf("%s/PcClient/Client/OrderEntryCtl/order?"+
"user_id=%d&activity_id=%d&good_id=%d", define.HOST, uid, activityId, goods[index].Id)
qrcode, err := utils.Qrcode2Base64(url)
t.CheckErr(err)
goods[index].Qrcode = qrcode
if goods[index].Stock == -1 {
for _, v := range res {
if goods[index].Id == v.GoodsId {
goods[index].Stock -= v.GoodsNum
}
}
}
}
t.JSON(map[string]interface{}{
"list": goods,
"total": len(goods),
})
}
// 扫二维码下单
func (t *OrderEntryCtl) Order() {
userId := t.MustGetInt("user_id")
goodId := t.MustGetInt("good_id")
entryId := t.GetAccountId()
entryPerson := models.OrderEntryPerson{}
exist, err := models.Get(&entryPerson, entryId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在")
activity := models.Activity{}
exist, err = models.Get(&activity, entryPerson.ActivityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
t.CheckRunning(activity.Status)
area := models.AreaStore{}
exist, err = models.Get(&area, entryPerson.AreaId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
letter := &models.InvitationLetter{}
exist, err = letter.GetByUserIdAndActivityId(userId, activity.Id, activity.ArchId, activity.RehearsalId)
t.CheckErr(err)
t.Assert(exist, code.MSG_INVITE_LETTER_NOT_EXIST, "邀请函不存在")
values := make([]map[string]interface{}, 0)
err = json.Unmarshal([]byte(strings.Trim(letter.ExtraData, `"`)), &values)
t.CheckErr(err)
var name, phone, address = "", "", ""
for _, value := range values {
if value["name"] == "姓名" {
name = fmt.Sprint(value["val"])
} else if value["name"] == "手机" {
phone = fmt.Sprint(value["val"])
} else if value["name"] == "地址" {
address = fmt.Sprint(value["val"])
}
}
s := core.GetXormAuto().NewSession()
defer s.Close()
err = s.Begin()
if err != nil {
s.Rollback()
t.CheckErr(err)
}
good := models.CustomerGoods{}
exist, err = s.Where("is_delete=0 and id=?", goodId).Get(&good)
if err != nil || !exist {
s.Rollback()
t.ERROR("商品信息异常", code.MSG_ERR_Param)
return
}
if good.Stock > -1 { // 库存
// 找出商品库存
ms, err := models.GetSubOrderGoodNumBySession(s, good.Id)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
for _, m := range ms {
if m.GoodsNum == good.Id && good.Stock-m.GoodsNum <= 0 {
s.Rollback()
t.ERROR(good.Name+"商品库存不足", code.MSG_CUSTOMER_GOOD_NOT_ENOUGH)
return
}
}
}
order := models.CustomerOrder{}
// 查询库存
total, err := s.Where("is_delete=0").Count(&order) // 订单总数
if err != nil {
s.Rollback()
t.CheckErr(err)
}
order.AreaId = entryPerson.AreaId
order.ArchId = activity.ArchId
order.AreaName = area.Name
order.BuyerId = userId
order.Type = 0
order.ActivityId = activity.Id
order.RehearsalId = activity.RehearsalId
order.OrderEntryPersonId = entryPerson.Id
order.OrderEntryPersonName = entryPerson.Name
order.TotalAmount = good.Price
order.Receiver = name
order.Phone = phone
order.Address = address
order.GoodsName = good.Name
order.GoodsId = good.Id
order.GoodsNum = 1
order.OutTradeNo = utils.RandomStr(32)
order.OrderNo = fmt.Sprint(define.DefaultOrderNo + int(total))
order.Status = 1
_, err = s.InsertOne(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
sub := models.CustomerOrderSub{}
sub.GoodsId = good.Id
sub.GoodName = good.Name
sub.GoodPrice = good.Price
sub.GoodsNum = 1
sub.OrderId = order.Id
_, err = models.Add(&sub) // 存入子订单
if err != nil {
s.Rollback()
t.CheckErr(err)
}
gift := models.OrderGift{}
exist, err = s.Where("is_delete=0 and activity_id=?", activity.Id).Get(&gift)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if exist {
prize := models.UserPrize{}
prize.UserId = userId
prize.ActivityId = activity.Id
prize.RehearsalId = activity.RehearsalId
prize.ActivityName = activity.Name
prize.PrizeName = gift.GiftName
prize.PrizeImg = gift.GiftPicUrl
prize.ArchId = activity.ArchId
prize.CustomerOrderId = order.Id
prize.PrizeType = 3
if gift.Num == 0 {
_, err = s.InsertOne(&prize)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
} else if gift.Num > 0 {
count, err := s.Where("activity_id=? and rehearsal_id=? and arch_id=? and is_delete=0",
activity.Id, activity.RehearsalId, activity.ArchId).NoAutoCondition().Count(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if gift.Num >= int(count) { // 大于等于
_, err = s.InsertOne(&prize)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
}
if prize.Id > 0 {
order.UserPrizeId = prize.Id
_, err = s.ID(order.Id).NoAutoCondition().Cols("user_prize_id").Update(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
}
err = s.Commit()
if err != nil {
s.Rollback()
t.CheckErr(err)
}
t.SUCCESS("成功录入订单")
}
// 手动下单
type ManualOrderGood struct {
GoodId int `json:"good_id"`
GoodNum int `json:"good_num"`
}
type ManualOrderParam struct {
Name string `json:"name"`
Phone string `json:"phone"`
Goods []*ManualOrderGood `json:"goods"`
}
func (t *OrderEntryCtl) ManualOrder() {
entryId := t.GetAccountId() // 录入人员id
param := &ManualOrderParam{}
t.Bind(param)
param.Goods = make([]*ManualOrderGood, 0)
err := json.Unmarshal([]byte(t.Request.REQUEST["goods"]), &param.Goods)
t.CheckErr(err)
if len(param.Goods) <= 0 {
t.ERROR("商品不能为空", code.MSG_CUSTOMER_GOOD_NOT_EXIST)
return
}
entryPerson := models.OrderEntryPerson{}
exist, err := models.Get(&entryPerson, entryId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在")
activity := models.Activity{}
exist, err = models.Get(&activity, entryPerson.ActivityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
t.CheckRunning(activity.Status)
area := models.AreaStore{}
exist, err = models.Get(&area, entryPerson.AreaId)
t.CheckErr(err)
t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在")
goodIds := make([]int, 0)
for _, g := range param.Goods {
goodIds = append(goodIds, g.GoodId)
}
s := core.GetXormAuto().NewSession()
defer s.Close()
err = s.Begin()
if err != nil {
s.Rollback()
t.CheckErr(err)
}
user := models.User{}
exist, err = s.Where("is_delete=0 and phone=?", param.Phone).NoAutoCondition().Get(&user)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if !exist {
user.Phone = param.Phone
user.Nickname = param.Name
user.Password = utils.RandomStr(8)
_, err = s.InsertOne(&user)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
// 校验库存
goods := make([]*models.CustomerGoods, 0)
err = s.Where("is_delete=0").In("id", goodIds).Find(&goods)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if len(goods) != len(param.Goods) {
s.Rollback()
t.ERROR("商品信息异常", code.MSG_ERR_Param)
return
}
subs := make([]*models.CustomerOrderSub, 0)
totalAmount := 0.00
goodNum := 0
for _, g := range param.Goods {
for _, good := range goods {
if g.GoodId == good.Id {
subs = append(subs, &models.CustomerOrderSub{
GoodsId: good.Id,
GoodsNum: g.GoodNum,
GoodName: good.Name,
GoodPrice: good.Price,
})
totalAmount += good.Price * float64(g.GoodNum)
goodNum += g.GoodNum
}
}
}
// ms := make([]map[string]int, 0)
// err = s.Table(&models.CustomerOrderSub{}).Alias("s").Select("s.goods_id, COALESCE(SUM(s.goods_num), 0) as goods_num").
// Join("left", (&models.CustomerOrder{}).Alias("o"), "o.id=s.order_id").
// Where("o.activity_id=? and o.rehearsal_id=? and o.arch_id=?", activity.Id, activity.RehearsalId, activity.ArchId).
// In("s.goods_id", goodIds).GroupBy("s.goods_id").Find(&ms)
ms, err := models.GetSubOrderGoodNumBySession(s, goodIds)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
for _, m := range ms {
for _, g := range goods {
if g.Stock == -1 { // 无上限
break
}
if m.GoodsId == g.Id && g.Stock-m.GoodsNum <= 0 {
s.Rollback()
t.ERROR(g.Name+"商品库存不足", code.MSG_CUSTOMER_GOOD_NOT_ENOUGH)
return
}
}
}
order := models.CustomerOrder{}
count, err := s.Where("is_delete=0").Count(&order) // 查看订单所在
if err != nil {
s.Rollback()
t.CheckErr(err)
}
order.AreaId = entryPerson.AreaId
order.AreaName = area.Name
order.ArchId = activity.ArchId
order.BuyerId = user.Id
order.Type = 0
order.ActivityId = activity.Id
order.RehearsalId = activity.RehearsalId
order.OrderEntryPersonId = entryPerson.Id
order.OrderEntryPersonName = entryPerson.Name
order.TotalAmount = totalAmount
order.Receiver = param.Name
order.Phone = param.Phone
order.GoodsNum = goodNum
order.GoodsId = subs[0].GoodsId
order.GoodsName = subs[0].GoodName
order.OutTradeNo = utils.RandomStr(32)
order.OrderNo = fmt.Sprint(define.DefaultOrderNo + int(count))
order.Status = 1
_, err = s.InsertOne(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
for _, sub := range subs {
sub.OrderId = order.Id
_, err = models.Add(sub) // 存入子订单
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
gift := models.OrderGift{}
exist, err = s.Where("is_delete=0 and activity_id=?", activity.Id).Get(&gift)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if exist {
prize := models.UserPrize{}
prize.UserId = user.Id
prize.ActivityId = activity.Id
prize.RehearsalId = activity.RehearsalId
prize.ActivityName = activity.Name
prize.PrizeName = gift.GiftName
prize.PrizeImg = gift.GiftPicUrl
prize.ArchId = activity.ArchId
prize.CustomerOrderId = order.Id
prize.PrizeType = 3
if gift.Num == 0 {
_, err = s.InsertOne(&prize)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
} else if gift.Num > 0 {
count, err := s.Where("activity_id=? and rehearsal_id=? and arch_id=? and is_delete=0",
activity.Id, activity.RehearsalId, activity.ArchId).NoAutoCondition().Count(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
if gift.Num >= int(count) { // 大于等于
_, err = s.InsertOne(&prize)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
}
if prize.Id > 0 {
order.UserPrizeId = prize.Id
_, err = s.ID(order.Id).NoAutoCondition().Cols("user_prize_id").Update(&order)
if err != nil {
s.Rollback()
t.CheckErr(err)
}
}
}
err = s.Commit()
if err != nil {
s.Rollback()
t.CheckErr(err)
}
t.SUCCESS("成功录入订单")
}
func (t *OrderEntryCtl) DeleteOrder() {
orderId := t.MustGetInt("order_id")
order := new(models.CustomerOrder)
exist, err := models.Get(order, orderId)
t.CheckErr(err)
t.Assert(exist, code.MSG_DATA_NOT_EXIST, "订单不存在")
_, err = models.Del(order, order.Id)
t.CheckErr(err)
if order.UserPrizeId > 0 {
_, err = models.Del(&models.UserPrize{}, order.UserPrizeId)
t.CheckErr(err)
}
t.SUCCESS("删除成功")
}
type OrderListResult struct {
OrderId int `json:"order_id"`
UserId int `json:"user_id"`
EntryName string `json:"entry_name"`
GoodName string `json:"-"`
OrderTime string `json:"order_time"`
OrderMoney float64 `json:"order_money"`
Receiver string `json:"receiver"`
Phone string `json:"phone"`
Address string `json:"address"`
Extra interface{} `json:"extra"` // 额外信息
ExtraData string `json:"-"`
}
func (t *OrderEntryCtl) EntryOrders() {
uid := t.GetAccountId()
entry := models.OrderEntryPerson{}
exist, err := models.Get(&entry, uid)
t.CheckErr(err)
t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在")
activity := models.Activity{}
exist, err = models.Get(&activity, entry.ActivityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
customer := models.Customer{}
exist, err = models.Get(&customer, activity.CustomerId)
t.CheckErr(err)
t.Assert(exist, code.MSG_CUSTOMER_NOT_EXIST, "客户不存在")
list := make([]*OrderListResult, 0)
//if customer.IsSpecial == 0 {
// // 添加邀请函的内容
// err = core.GetXormAuto().Table(&models.CustomerOrder{}).Alias("o").
// Select("o.receiver as receiver, o.phone as phone, o.address as address,l.extra_data as extra_data, "+
// " g.name as good_name, o.buyer_id as user_id, o.total_amount as order_money, o.id as order_id, "+
// " DATE_FORMAT(o.created_at, '%Y-%m-%d %H:%i:%S') AS order_time").Join("LEFT",
// (&models.CustomerGoods{}).Alias("g"), "o.goods_id=g.id and o.activity_id=g.activity_id").
// Join("LEFT", (&models.InvitationLetter{}).Alias("l"), "l.user_id = o.buyer_id and o.activity_id=l.activity_id and o.arch_id=l.arch_id and l.is_delete=0").
// Where("o.activity_id=? and o.order_entry_person_id=? and o.rehearsal_id=? and o.arch_id=? "+
// " and o.is_delete=0", activity.Id, uid, activity.RehearsalId, activity.ArchId).
// Desc("o.created_at").Find(&list)
// t.CheckErr(err)
// optionItems, err := invitation_service.GetOptionItem(activity.Id)
// t.CheckErr(err)
// for i := range list {
// data, err := invitation_service.GetOptionValue(optionItems, list[i].ExtraData)
// t.CheckErr(err)
// list[i].Extra = data
// list[i].EntryName = entry.Name
// }
//} else if customer.IsSpecial == 2 {
err = core.GetXormAuto().Table(&models.CustomerOrder{}).Alias("o").Select("o.id as order_id, "+
" o.receiver as receiver, o.phone as phone, o.address as address, o.buyer_id as user_id, o.order_entry_person_name as entry_name, "+
" o.total_amount as order_money, DATE_FORMAT(o.created_at, '%Y-%m-%d %H:%i:%S') AS order_time").
Where("o.activity_id=? and o.rehearsal_id=? and o.order_entry_person_id=? and o.arch_id=?",
activity.Id, activity.RehearsalId, uid, activity.ArchId).Desc("o.created_at").Find(&list)
t.CheckErr(err)
orderIds := make([]int, 0)
for _, v := range list {
orderIds = append(orderIds, v.OrderId)
}
subs, err := models.GetCustomerOrderSubsByOrderIds(orderIds)
t.CheckErr(err)
for i := range list {
s := make([]interface{}, 0)
for _, sub := range subs {
if sub.OrderId == list[i].OrderId {
s = append(s, sub)
}
}
list[i].Extra = s
}
//}
t.JSON(map[string]interface{}{
"list": list,
"total": len(list),
})
}
// 用户订单列表
type UserOrdersResult struct {
models.CustomerOrder `xorm:"extends"`
Good *models.CustomerGoods `json:"good" xorm:"extends"`
}
// 用户查看订单列表
func (t *OrderEntryCtl) UserOrders() {
uid := t.GetAccountId()
activityId := t.MustGetInt("activity_id")
activity := new(models.Activity)
exist, err := models.Get(activity, activityId)
t.CheckErr(err)
t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在")
orders := make([]UserOrdersResult, 0)
s := core.GetXormAuto().Table(new(models.CustomerOrder)).Alias("o").
Join("LEFT", new(models.CustomerGoods).Alias("g"),
"o.goods_id=g.id and g.is_delete=0").
Where("o.buyer_id=? and o.is_delete=0 and o.activity_id=? and o.rehearsal_id=? and o.arch_id=?",
uid, activity.Id, activity.RehearsalId, activity.ArchId)
if t.PageSize > 0 {
s = s.Limit(t.PageSize, t.Page*t.PageSize)
}
total, err := s.Desc("o.created_at").FindAndCount(&orders)
t.CheckErr(err)
t.JSON(map[string]interface{}{
"list": orders,
"total": total,
})
}
// 二维码
func (t *OrderEntryCtl) Qrcode() {
userId := t.MustGetInt("user_id")
activityId := t.MustGetInt("activity_id")
goodId := t.MustGetInt("good_id")
Url := fmt.Sprintf("%s/PcClient/Client/OrderEntryCtl/order?user_id=%d&activity_id=%d&good_id=%d",
define.HOST, userId, activityId, goodId)
qr, err := utils.Qrcode2Base64(Url)
t.CheckErr(err)
t.JSON(map[string]interface{}{
"qrcode": qr,
})
}