From 9dce358f22d138d7e623ceeef3594a74039534da Mon Sep 17 00:00:00 2001 From: tommy <3405129587@qq.com> Date: Fri, 31 Jul 2020 12:04:46 +0800 Subject: [PATCH] fix:bug --- controllers/client/good.go | 11 +- controllers/client/login.go | 6 +- controllers/client/order_entry.go | 307 ++++++++++++++++++++++++++++++-------- controllers/pc/order_draw.go | 10 +- go.mod | 1 + models/base.go | 2 +- models/customer_goods.go | 2 +- models/customer_order.go | 19 ++- models/customer_order_option.go | 26 ++-- models/customer_order_sub.go | 18 +-- models/user.go | 47 +++--- services/pay/handle.go | 3 +- services/pay/loop.go | 208 -------------------------- utils/code/code.go | 1 + 14 files changed, 314 insertions(+), 347 deletions(-) delete mode 100644 services/pay/loop.go diff --git a/controllers/client/good.go b/controllers/client/good.go index 71b4512..eb82664 100644 --- a/controllers/client/good.go +++ b/controllers/client/good.go @@ -88,17 +88,17 @@ func (t *GoodCtl) ListOrder() { orders, err := models.GetCustomerOrdersByActivityId(uid, activity.Id, activity.RehearsalId, areaId, statusList, t.Page, t.PageSize, activity.ArchId) t.CheckErr(err) - orderNos := make([]string, 0) + orderIds := make([]int64, 0) for _, order := range orders { - orderNos = append(orderNos, order.OrderNo) + orderIds = append(orderIds, order.Id) } - subs, err := models.GetCustomerOrderSubsByOrderNos(orderNos...) + subs, err := models.GetCustomerOrderSubsByOrderIds(orderIds) t.CheckErr(err) for index, order := range orders { order.ServicePhone = option.MainServicePhone for _, sub := range subs { - if order.OrderNo == sub["order_no"] { + if fmt.Sprint(order.Id) == sub["order_id"] { orders[index].SubOrders = append(orders[index].SubOrders, sub) } } @@ -188,7 +188,6 @@ func (t *GoodCtl) Order() { IsDelete: false, CreatedAt: time.Now(), UpdatedAt: time.Now(), - OrderNo: "", GoodsId: good.Id, GoodsNum: g["num"], GoodName: good.Name, @@ -243,7 +242,7 @@ func (t *GoodCtl) Order() { // 批量插入 beans := make([]interface{}, 0) for _, subOrder := range subOrders { - subOrder.OrderNo = order.OrderNo + subOrder.OrderId = order.Id beans = append(beans, subOrder) } session.Insert(beans...) diff --git a/controllers/client/login.go b/controllers/client/login.go index 089e36d..f870541 100644 --- a/controllers/client/login.go +++ b/controllers/client/login.go @@ -89,9 +89,9 @@ func (t *UserCtl) WxLogin() { exist, err = user.GetUserByOpenid(info.OpenId) t.CheckErr(err) - user.ActivityId = activityId - user.AreaId = area.Id - user.AreaName = area.Name + //user.ActivityId = activityId + //user.AreaId = area.Id + //user.AreaName = area.Name user.Nickname = info.Nickname user.Openid = info.OpenId user.Gender = func() string { diff --git a/controllers/client/order_entry.go b/controllers/client/order_entry.go index a9e3e3f..5cba9f0 100644 --- a/controllers/client/order_entry.go +++ b/controllers/client/order_entry.go @@ -2,33 +2,26 @@ package client import ( "fmt" + "github.com/ouxuanserver/osmanthuswine/src/core" "hudongzhuanjia/controllers" "hudongzhuanjia/models" invitation_service "hudongzhuanjia/services/invitation" "hudongzhuanjia/utils" "hudongzhuanjia/utils/code" "hudongzhuanjia/utils/define" - "time" - - "github.com/ouxuanserver/osmanthuswine/src/core" ) type OrderEntryCtl struct { controllers.AuthorCtl } -// 录入人员 -// 商品 == > 用户查看所有商品 +// 用户查看所有商品 func (t *OrderEntryCtl) List() { uid := t.MustGetUID() activityId := t.MustGetInt64("activity_id") + areaId := t.MustGetInt64("area_id") - entryPerson := new(models.OrderEntryPerson) - exist, err := models.Get(entryPerson, uid) - t.CheckErr(err) - t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在") - - goods, err := models.GetGoodsByActivityId(activityId, entryPerson.AreaId) + goods, err := models.GetGoodsByActivityId(activityId, areaId) t.CheckErr(err) for index := range goods { url := fmt.Sprintf("%s/PcClient/Client/OrderEntryCtl/order?"+ @@ -44,107 +37,291 @@ func (t *OrderEntryCtl) List() { }) } -// 下订单 == > 二维码跳转 +// 扫二维码下单 func (t *OrderEntryCtl) Order() { userId := t.MustGetInt64("user_id") - activityId := t.MustGetInt64("activity_id") goodId := t.MustGetInt64("good_id") entryId := t.MustGetUID() - activity := new(models.Activity) - exist, err := models.Get(activity, activityId) + entryPerson := models.OrderEntryPerson{} + exist, err := models.Get(&entryPerson, entryId) t.CheckErr(err) - t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在") - t.CheckRunning(activity.Status) + t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在") - entryPerson := new(models.OrderEntryPerson) - exist, err = models.Get(entryPerson, entryId) + activity := models.Activity{} + exist, err = models.Get(&activity, entryPerson.ActivityId) t.CheckErr(err) - t.Assert(exist, code.MSG_ENTRYPEOPLE_NOT_EXIST, "录入人员不存在") + t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在") + t.CheckRunning(activity.Status) - area := new(models.AreaStore) - exist, err = area.GetAreaStoreById(entryPerson.AreaId) + area := models.AreaStore{} + exist, err = models.Get(&area, entryPerson.AreaId) t.CheckErr(err) t.Assert(exist, code.MSG_AREASTORE_NOT_EXIST, "地区不存在") - good := new(models.CustomerGoods) - exist, err = models.Get(good, goodId) + good := models.CustomerGoods{} + exist, err = models.Get(&good, goodId) t.CheckErr(err) t.Assert(exist, code.MSG_DATA_NOT_EXIST, "商品不存在") - session := core.GetXormAuto().NewSession() - defer session.Close() - session.Begin() + s := core.GetXormAuto().NewSession() + defer s.Close() + err = s.Begin() + if err != nil { + s.Rollback() + t.CheckErr(err) + } + order := models.CustomerOrder{} + total, err := s.Where("is_delete=0").Count(&order) // 订单总数 + if err != nil { + s.Rollback() + t.CheckErr(err) + } - gift := new(models.OrderGift) - exist, err = session.Where("is_delete=0 and activity_id=?", activityId).Get(gift) + 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.TotalAmount = good.Price + order.OutTradeNo = utils.RandomStr(32) + order.OrderNo = fmt.Sprint(define.DefaultOrderNo + int(total)) + order.Status = 1 + _, err = s.InsertOne(&order) if err != nil { - session.Rollback() + 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) } - prize := new(models.UserPrize) - prize.UserId = userId - prize.ActivityId = activityId - prize.RehearsalId = activity.RehearsalId - prize.ActivityName = activity.Name - prize.PrizeName = gift.GiftName - prize.PrizeImg = gift.GiftPicUrl - prize.ArchId = activity.ArchId - prize.PrizeType = 3 - prize.IsDelete = false - prize.CreatedAt = time.Now() - prize.UpdatedAt = time.Now() + 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 = session.InsertOne(prize) + _, err = s.InsertOne(&prize) if err != nil { - session.Rollback() + s.Rollback() t.CheckErr(err) } } else if gift.Num > 0 { - count, err := core.GetXormAuto().Where("activity_id=? and rehearsal_id=? and arch_id=? and is_delete=0", - activityId, activity.RehearsalId, activity.ArchId).Count(new(models.CustomerOrder)) + 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 { - session.Rollback() + s.Rollback() t.CheckErr(err) } - if gift.Num > int(count) { - _, err = session.InsertOne(prize) + if gift.Num >= int(count) { // 大于等于 + _, err = s.InsertOne(&prize) if err != nil { - session.Rollback() + 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) + } + } } - order := new(models.CustomerOrder) - order.UserPrizeId = prize.Id + err = s.Commit() + if err != nil { + s.Rollback() + t.CheckErr(err) + } + t.SUCCESS("成功录入订单") +} + +type ManualOrderGood struct { + GoodId int + GoodNum int +} +type ManualOrderParam struct { + Name string `json:"name"` + Phone string `json:"phone"` + Goods []*ManualOrderGood `json:"goods"` +} + +// 手动下单 +func (t *OrderEntryCtl) ManualOrder() { + entryId := t.MustGetUID() // 录入人员id + param := &ManualOrderParam{} + err := t.Bind(param) + 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, "地区不存在") + + subs := make([]*models.CustomerOrderSub, 0) + totalAmount := 0.00 + for _, g := range param.Goods { + good := models.CustomerGoods{} + exist, err = models.Get(&good, g.GoodId) + t.CheckErr(err) + t.Assert(exist, code.MSG_DATA_NOT_EXIST, "商品不存在") + subs = append(subs, &models.CustomerOrderSub{ + GoodsId: good.Id, + GoodsNum: g.GoodNum, + GoodName: good.Name, + GoodPrice: good.Price, + }) + totalAmount += good.Price * float64(g.GoodNum) + } + + s := core.GetXormAuto().NewSession() + defer s.Close() + err = s.Begin() + if err != nil { + s.Rollback() + t.CheckErr(err) + } + user := models.User{ + Phone: param.Phone, + Nickname: param.Name, + Password: utils.RandomStr(6), + } + _, err = models.Add(&user) + if err != nil { + s.Rollback() + t.CheckErr(err) + } + + 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.ArchId = activity.ArchId order.AreaName = area.Name - order.BuyerId = userId - order.GoodsId = goodId + order.ArchId = activity.ArchId + order.BuyerId = user.Id order.Type = 0 - order.ActivityId = activityId + order.ActivityId = activity.Id order.RehearsalId = activity.RehearsalId order.OrderEntryPersonId = entryPerson.Id - order.GoodsName = good.Name - order.TotalAmount = good.Price + order.TotalAmount = totalAmount order.OutTradeNo = utils.RandomStr(32) - order.IsDelete = false - _, err = session.InsertOne(order) + order.OrderNo = fmt.Sprint(define.DefaultOrderNo + int(count)) + order.Status = 1 + _, err = s.InsertOne(&order) if err != nil { - session.Rollback() + 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) + } + } - err = session.Commit() - t.CheckErr(err) - t.SUCCESS("success") -} + 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.MustGetInt64("order_id") order := new(models.CustomerOrder) diff --git a/controllers/pc/order_draw.go b/controllers/pc/order_draw.go index 639f0d4..e64ac24 100644 --- a/controllers/pc/order_draw.go +++ b/controllers/pc/order_draw.go @@ -23,12 +23,12 @@ func (t *OrderDrawCtl) Switch() { activityId := t.MustGetInt64("activity_id") status := t.MustGetInt("status") - activity := new(models.Activity) - exist, err := models.Get(activity, activityId) + activity := models.Activity{} + exist, err := models.Get(&activity, activityId) t.CheckErr(err) t.Assert(exist, code.MSG_ACTIVITY_NOT_EXIST, "互动不存在") - option := new(models.CustomerOrderOption) + option := &models.CustomerOrderOption{} exist, err = option.GetByActivityId(activityId) t.CheckErr(err) t.Assert(exist, code.MSG_MODULE_NOT_EXIST, "订单活动不存在") @@ -38,8 +38,8 @@ func (t *OrderDrawCtl) Switch() { return } - _, err = option.Switch(activityId, status) - t.CheckErr(err) + option.Status = status + _, err = models.Update(option.Id, option, "status") t.CheckErr(err) t.SUCCESS("操作成功") } diff --git a/go.mod b/go.mod index 4f448e6..00c2f94 100644 --- a/go.mod +++ b/go.mod @@ -31,6 +31,7 @@ require ( github.com/smartystreets/goconvey v1.6.4 github.com/swaggo/http-swagger v0.0.0-20190614090009-c2865af9083e // indirect github.com/swaggo/swag v1.6.3 // indirect + github.com/syndtr/goleveldb v1.0.0 github.com/tealeg/xlsx v1.0.5 // indirect github.com/tencentyun/cos-go-sdk-v5 v0.7.7 github.com/tencentyun/tls-sig-api-v2-golang v1.0.0 diff --git a/models/base.go b/models/base.go index d1d0e27..2932c8b 100644 --- a/models/base.go +++ b/models/base.go @@ -140,7 +140,7 @@ func Alias(bean interface{}, alias string) string { return fmt.Sprintf("%s as %s", tn, alias) } -func Get(bean interface{}, id int64) (bool, error) { +func Get(bean interface{}, id interface{}) (bool, error) { return core.GetXormAuto().NoAutoCondition().Where("is_delete=0 and id=?", id).Get(bean) } diff --git a/models/customer_goods.go b/models/customer_goods.go index 3b9825b..557609d 100644 --- a/models/customer_goods.go +++ b/models/customer_goods.go @@ -20,7 +20,7 @@ type CustomerGoods struct { FixedField string `json:"fixed_field" xorm:"not null default '' comment('固定不可改字段,|分隔') VARCHAR(255)"` Stock int `json:"stock" xorm:"not null default 0 comment('库存-1的时候无上限') INT(18)"` Name string `json:"name" xorm:"not null default '' comment('商品名称') VARCHAR(255)"` - Price float64 `json:"price" xorm:"not null default 0.00 comment('商品单价')"` + Price float64 `json:"price" xorm:"not null default 0.00 comment('商品单价') DECIMAL(18,2)"` Desc string `json:"desc" xorm:"not null default '' comment('商品介绍') VARCHAR(255)"` //// 无关变量 diff --git a/models/customer_order.go b/models/customer_order.go index 0af8038..c57c9e6 100644 --- a/models/customer_order.go +++ b/models/customer_order.go @@ -24,9 +24,6 @@ type CustomerOrder struct { OutTradeNo string `json:"out_trade_no" xorm:"not null default '' comment('微信订单流水号') VARCHAR(255)"` OrderEntryPersonId int64 `json:"order_enter_person_id" xorm:"not null default 0 comment('订单录入人员id') BIGINT(20)"` BuyerId int64 `json:"buyer_id" xorm:"not null default 0 comment('user表id') BIGINT(20)"` - GoodsId int64 `json:"goods_id,omitempty" xorm:"not null default 0 comment('customer_goods表id') BIGINT(20)"` - GoodsName string `json:"goods_name,omitempty" xorm:"not null default '' comment('商品名字') VARCHAR(255)"` - GoodsNum int `json:"goods_num,omitempty" xorm:"not null default 0 comment('商品数量') INT(11)"` TotalAmount float64 `json:"total_amount" xorm:"not null default 0.00 comment('订单总额')"` PayAmount float64 `json:"pay_amount" xorm:"not null default 0.00 comment('支付金额')"` Postage float64 `json:"postage" xorm:"not null default 0.00 comment('邮费[0免邮]')"` @@ -46,13 +43,15 @@ type CustomerOrder struct { AutoReceiveTime time.Time `json:"auto_receive_time" xorm:"comment('自动收货时间') DATETIME"` // 无关变量 - OrderTime string `json:"order_time,omitempty" xorm:"-"` - Good *CustomerGoods `json:"good,omitempty" xorm:"-"` - User *User `json:"user,omitempty" xorm:"-"` - OrderEntryPersonName string `json:"order_entry_person_name,omitempty" xorm:"-"` - ServicePhone string `json:"service_phone" xorm:"-"` - //SubOrders []*CustomerOrderSub `json:"sub_orders" xorm:"-"` - SubOrders []map[string]string `json:"sub_orders,omitempty" xorm:"-"` + //GoodsId int64 `json:"goods_id,omitempty" xorm:"not null default 0 comment('customer_goods表id') BIGINT(20)"` + //GoodsName string `json:"goods_name,omitempty" xorm:"not null default '' comment('商品名字') VARCHAR(255)"` + //GoodsNum int `json:"goods_num,omitempty" xorm:"not null default 0 comment('商品数量') INT(11)"` + OrderTime string `json:"order_time,omitempty" xorm:"-"` + Good *CustomerGoods `json:"good,omitempty" xorm:"-"` + User *User `json:"user,omitempty" xorm:"-"` + OrderEntryPersonName string `json:"order_entry_person_name,omitempty" xorm:"-"` + ServicePhone string `json:"service_phone" xorm:"-"` + SubOrders []map[string]string `json:"sub_orders,omitempty" xorm:"-"` } func (t *CustomerOrder) TableName() string { diff --git a/models/customer_order_option.go b/models/customer_order_option.go index 4d665b7..7f80d11 100644 --- a/models/customer_order_option.go +++ b/models/customer_order_option.go @@ -9,17 +9,18 @@ import ( const CustomerOrderOptionTableName = TableNamePrefix + "customer_order_option" type CustomerOrderOption struct { - Id int64 `json:"id" xorm:"not null pk INT(11)"` - ActivityId int64 `json:"activity_id" xorm:"not null default 0 comment('互动id') INT(11)"` - SettingBox string `json:"setting_box" xorm:"not null comment('json格式 选中的表单项') TEXT"` - SelfBox string `json:"self_box" xorm:"not null comment('json格式 邀请函选中的表单项') TEXT"` - Status int `json:"status" xorm:"not null default 0 comment('订单活动的开启1|关闭0') TINYINT(1)"` - PostFeeType int `json:"post_fee_type" xorm:"not null default 0 comment('直播订单运费设置0包邮1货到付款2收费') TINYINT(1)"` - PostFee float64 `json:"post_fee" xorm:"not null default 0.00 comment('直播订单运费') DECIMAL(18)"` - MainServicePhone string `json:"main_service_phone" xorm:"not null default '' comment('客服电话') VARCHAR(128)"` - IsDelete int `json:"-" xorm:"not null default 0 comment('删除') TINYINT(1)"` - CreatedAt time.Time `json:"-" xorm:"created"` - UpdatedAt time.Time `json:"-" xorm:"updated"` + Id int64 `json:"id" xorm:"not null pk INT(11)"` + IsDelete int `json:"-" xorm:"not null default 0 comment('删除') TINYINT(1)"` + CreatedAt time.Time `json:"-" xorm:"created"` + UpdatedAt time.Time `json:"-" xorm:"updated"` + + ActivityId int64 `json:"activity_id" xorm:"not null default 0 comment('互动id') INT(11)"` + SettingBox string `json:"setting_box" xorm:"not null comment('json格式 选中的表单项') TEXT"` + SelfBox string `json:"self_box" xorm:"not null comment('json格式 邀请函选中的表单项') TEXT"` + Status int `json:"status" xorm:"not null default 0 comment('订单活动的开启1|关闭0') TINYINT(1)"` + PostFeeType int `json:"post_fee_type" xorm:"not null default 0 comment('直播订单运费设置0包邮1货到付款2收费') TINYINT(1)"` + PostFee float64 `json:"post_fee" xorm:"not null default 0.00 comment('直播订单运费') DECIMAL(18)"` + MainServicePhone string `json:"main_service_phone" xorm:"not null default '' comment('客服电话') VARCHAR(128)"` } func (t *CustomerOrderOption) TableName() string { @@ -41,6 +42,5 @@ func (t *CustomerOrderOption) GetOpen(aid int64) (bool, error) { func (t *CustomerOrderOption) Switch(aid int64, status int) (int64, error) { t.Status = status - return core.GetXormAuto().Where("is_delete=0 and activity_id=?", aid). - Cols("status").Update(t) + return core.GetXormAuto().Where("is_delete=0 and activity_id=?", aid).Cols("status").Update(t) } diff --git a/models/customer_order_sub.go b/models/customer_order_sub.go index 6520749..7216629 100644 --- a/models/customer_order_sub.go +++ b/models/customer_order_sub.go @@ -14,11 +14,11 @@ type CustomerOrderSub struct { CreatedAt time.Time `json:"created_at" xorm:"not null created comment('创建时间') DATETIME"` UpdatedAt time.Time `json:"updated_at" xorm:"not null updated comment('更新时间') DATETIME"` - OrderNo string `json:"order_no" xorm:"not null default 0 comment('订单号') VARCHAR(128)"` + OrderId int64 `json:"order_id" xorm:"not null default 0 comment('订单id') VARCHAR(128)"` GoodsId int64 `json:"goods_id" xorm:"not null default 0 comment('商品id') INT(11)"` GoodsNum int `json:"goods_num" xorm:"not null default 0 comment('商品数量') INT(11)"` GoodName string `json:"good_name" xorm:"not null default '' comment('商品名字') VARCHAR(128)"` - GoodPrice float64 `json:"good_price" xorm:"not null default 0.00 comment('商品价格') DECIMAL(18)"` + GoodPrice float64 `json:"good_price" xorm:"not null default 0.00 comment('商品价格') DECIMAL(18,2)"` // 无关变量 GoodsPicUrl string `json:"goods_pic_url" xorm:"extends"` @@ -32,20 +32,16 @@ func (t *CustomerOrderSub) Alias(n string) string { return fmt.Sprintf("%s as %s", t.TableName(), n) } -func GetCustomerOrderSubsByOrderNos(orderNos ...string) (subs []map[string]string, err error) { +func GetCustomerOrderSubsByOrderIds(orderIds interface{}) (subs []map[string]string, err error) { err = core.GetXormAuto().Table(new(CustomerOrderSub)).Alias("s"). - Select("s.order_no, s.goods_id, s.goods_num, s.good_name, s.good_price, g.goods_pic_url"). + Select("s.order_id, s.goods_id, s.goods_num, s.good_name, s.good_price, g.goods_pic_url"). Join("left", new(CustomerGoods).Alias("g"), "g.id=s.goods_id"). - Where("s.is_delete=0").In("s.order_no", orderNos).Desc("s.created_at").Find(&subs) + Where("s.is_delete=0").In("s.order_id", orderIds).Desc("s.created_at").Find(&subs) return } -func GetSubOrdersByOrderNo(orderNo string) ([]*CustomerOrderSub, error) { +func GetSubOrdersByOrderId(orderId interface{}) ([]*CustomerOrderSub, error) { subs := make([]*CustomerOrderSub, 0) - err := core.GetXormAuto().Where("is_delete=0 and order_no=?", orderNo).Find(&subs) + err := core.GetXormAuto().Where("is_delete=0 and order_id=?", orderId).Find(&subs) return subs, err } - -func (t *CustomerOrderSub) IncrStock() { - -} diff --git a/models/user.go b/models/user.go index 805cba9..3f51c30 100644 --- a/models/user.go +++ b/models/user.go @@ -1,35 +1,38 @@ package models import ( - "time" - "github.com/ouxuanserver/osmanthuswine/src/core" + "time" ) const UserTN = TableNamePrefix + "user" //用户 type User struct { - Id int64 `json:"id" xorm:"not null pk autoincr INT(11)"` - Phone string `json:"phone" description:"手机号码"` - Code string `json:"code" description:"验证码"` - City string `json:"city" xorm:"not null"` - Province string `json:"province" xorm:"not null"` - Country string `json:"country"` - Unionid string `json:"unionid" description:"unionid"` - Openid string `json:"openid" description:"openid"` - AccessToken string `json:"access_token" description:"token"` - Nickname string `json:"nickname" description:"昵称"` - Avatar string `json:"avatar" description:"头像"` - Gender string `json:"gender" description:"性别[男,女]"` - Balance float64 `json:"balance" description:"余额"` - ActivityId int64 `json:"activity_id" description:"主活动id"` // 不存在 - AreaId int64 `json:"area_id" description:"地区id"` // 不存在 - AreaName string `json:"area_name" description:"地区名字"` - Sig string `json:"sig" xorm:"-"` - IsDelete bool `json:"is_delete" xorm:"default(0)" description:"是否删除"` - CreatedAt time.Time `json:"created_at" xorm:"created" description:"创建时间"` - UpdatedAt time.Time `json:"updated_at" xorm:"updated" description:"更新时间"` + Id int64 `json:"id" xorm:"not null pk autoincr INT(11)"` + IsDelete bool `json:"is_delete" xorm:"default(0)" description:"是否删除"` + CreatedAt time.Time `json:"created_at" xorm:"created" description:"创建时间"` + UpdatedAt time.Time `json:"updated_at" xorm:"updated" description:"更新时间"` + + Username string `json:"username" xorm:"not null default '' comment('用户名') VARCHAR(128)"` + Phone string `json:"phone" xorm:"not null default '' comment('手机号码') VARCHAR(128)"` + Password string `json:"password" xorm:"not null default '' comment('密码') VARCHAR(128)"` + Code string `json:"code" xorm:"not null default '' comment('验证码') VARCHAR(128)"` + City string `json:"city" xorm:"not null default '' comment('城市') VARCHAR(128)"` + Province string `json:"province" xorm:"not null default '' comment('省份') VARCHAR(128)"` + Country string `json:"country" xorm:"not null default '' comment('国家') VARCHAR(128)"` + Unionid string `json:"unionid" xorm:"not null default '' comment('unionid') VARCHAR(128)"` + Openid string `json:"openid" xorm:"not null default '' comment('openid') VARCHAR(128)"` + Nickname string `json:"nickname" xorm:"not null default '' comment('昵称') VARCHAR(128)"` + Avatar string `json:"avatar" xorm:"not null default '' comment('头像') VARCHAR(128)"` + Gender string `json:"gender" xorm:"not null default '' comment('性别[男,女]') VARCHAR(128)"` + Balance float64 `json:"balance" xorm:"not null default 0.00 comment('余额') DECIMAL(18,2)"` + //ActivityId int64 `json:"activity_id" description:"主活动id"` // 不存在 + //AreaId int64 `json:"area_id" description:"地区id"` // 不存在 + //AreaName string `json:"area_name" description:"地区名字"` + + // 无关变量 + Sig string `json:"sig" xorm:"-"` } func (t *User) TableName() string { diff --git a/services/pay/handle.go b/services/pay/handle.go index db92cf2..761db37 100644 --- a/services/pay/handle.go +++ b/services/pay/handle.go @@ -12,7 +12,6 @@ import ( ) func init() { - //go loopOrder() go utils.HandleTicker(30*time.Minute, HandleReward) // 打赏24小时退款 go utils.HandleTicker(30*time.Second, HandleGoodOrder) // 订单关闭信息 } @@ -201,7 +200,7 @@ func HandleGoodOrder() error { } } - subs, err := models.GetSubOrdersByOrderNo(v.OrderNo) + subs, err := models.GetSubOrdersByOrderId(v.Id) if err != nil { return err } diff --git a/services/pay/loop.go b/services/pay/loop.go deleted file mode 100644 index b098241..0000000 --- a/services/pay/loop.go +++ /dev/null @@ -1,208 +0,0 @@ -package pay_service - -import ( - "go.uber.org/zap" - "hudongzhuanjia/logger" - "hudongzhuanjia/models" - "hudongzhuanjia/utils/define" - "math" - "time" -) - -var orderDelayQueue = make(chan *models.UserOrder, math.MaxInt8) - -func PutOrderDelayQueue(order *models.UserOrder) { - orderDelayQueue <- order -} - -func loopOrder() { - orders, err := models.GetUserOrdersByStatus(0, 3) - if err != nil { - panic(err) - } - - for _, order := range orders { - PutOrderDelayQueue(order) - } - - defer func() { - if err := recover(); err != nil { - logger.Error("订单轮询查询: panic 恢复错误", err) - } - // 重启 - time.Sleep(5 * time.Second) - loopOrder() - }() - for { - select { - case order, ok := <-orderDelayQueue: - if !ok { - panic("通道异常关闭") - } - if order.ExpireAt <= time.Now().Unix() { // 订单超时 - if order.Status == 0 { - go HandleTimeout(order) - } - continue - } - - if order.Status == 0 { - res, err := OrderQuery(order.OutTradeNo) - if err != nil { - logger.Error("查询订单出现错误: 错误原因-->", err.Error(), "交易订单号-->", order.OutTradeNo) - orderDelayQueue <- order // 重新进入队列 - continue - } - - if res["trade_state"] == define.CODE_TRADE_SUCCESS { - go HandleSuccess(order) - } else if res["trade_state"] == define.CODE_TRADE_REFUND { - order.Status = 3 - orderDelayQueue <- order - continue - } else { - orderDelayQueue <- order - continue - } - } else if order.Status == 3 { - res, err := QueryRefund(order.OutTradeNo) - if err != nil { - logger.Error("退款订单查询错误: 错误原因-->", err.Error(), "交易订单号-->", order.OutTradeNo) - continue - } - order.RefundAccount = res.RefundList[0].RefundAccount - order.RefundRecvAccount = res.RefundList[0].RefundRecvAccout - order.Status = 4 - _, err = models.Update(order.Id, order, "refund_account", "refund_recv_account", "status") - if err != nil { - logger.Error("退款状态改变错误: 错误原因-->", err, "交易订单号-->", order.OutTradeNo) - continue - } - } - } - } -} - -func HandleTimeout(order *models.UserOrder) error { - // 退还库存 - if order.GoodType == 4 { - err := HandleCancelOrder(order.OutTradeNo) - if err != nil { - logger.Error(err) - } - } - return nil -} - -func init() { - //go loopTransfer() -} - -var transferDelayQueue = make(chan *transferDelayQueueParam, math.MaxInt8) - -type transferDelayQueueParam struct { - first bool // 首次跳过 - Retries int `json:"retries"` // 尝试次数 - Delay int `json:"delay"` // 延迟时间, 单位second - Amount int `json:"amount"` // 转账金额 - Desc string `json:"desc"` // 转账描述 - OpenId string `json:"open_id"` // 被转账人 - PartnerTradeNo string `json:"partner_trade_no"` // 转账账单单号 -} - -func loopTransfer() { - //初始化 - transfers, err := models.GetUserTransferByStatus(0, 1, 3) - if err != nil { - panic(err) - } - - transferDelayQueue = make(chan *transferDelayQueueParam, math.MaxInt8) - for _, transfer := range transfers { - transferDelayQueue <- &transferDelayQueueParam{ - first: true, - Retries: 5, - Delay: 2 * 60, - Amount: transfer.PaymentAmount, - Desc: transfer.Desc, - OpenId: transfer.OpenId, - PartnerTradeNo: transfer.PartnerTradeNo, - } - } - - defer func() { - if errRec := recover(); errRec != nil { - logger.Error("转账轮询 loop transfer panic", zap.Any("错误原因", errRec)) - } - loopTransfer() - }() - for { - select { - case param, ok := <-transferDelayQueue: - if !ok { - panic("转账延迟通道异常关闭") - } - - // 尝试次数 - if param.Retries <= 0 { - logger.Info("微信转账尝试3次失败", zap.String("转账账单单号", param.PartnerTradeNo)) - userTransfer := new(models.UserTransfer) - userTransfer.Status = 4 - _, err = userTransfer.UpdateByPartnerTradeNo(param.PartnerTradeNo) - if err != nil { - logger.Info("微信转账更新状态失败", zap.String("失败原因", err.Error()), - zap.String("转账账单单号", param.PartnerTradeNo)) - } - continue - } else { - param.Retries-- - } - - if !param.first { - time.Sleep(time.Duration(param.Delay) * time.Second) - } - param.first = false - res, err := TransferInfo(param.PartnerTradeNo) - if err != nil { - logger.Error("微信转账查询出现的错误", zap.String("错误原因", err.Error()), - zap.String("转账账单", param.PartnerTradeNo)) - transferDelayQueue <- param - continue - } - - if res.Status == define.CODE_SUCCESS { - continue - } else if res.Status == define.CODE_TRANSFER_PROCESSING { - transferDelayQueue <- param - continue - } else { - //失败 --> 重新转账 - _, err = Transfer(param.Desc, param.OpenId, param.PartnerTradeNo, param.Amount) - if err != nil { - logger.Error("微信转账出现的错误", zap.String("错误原因", err.Error()), - zap.String("转账账单", param.PartnerTradeNo)) - } - transferDelayQueue <- param // 重新确认 - continue - } - } - } -} - -func PutTransferDelayQueue(desc, openId, partnerTradeNo string, amount, retries, delay int) { - if retries <= 0 { - retries = 3 - } - if delay == 0 { - delay = 30 - } - transferDelayQueue <- &transferDelayQueueParam{ - first: true, - Retries: retries, - Delay: delay, - Amount: amount, - Desc: desc, - OpenId: openId, - PartnerTradeNo: partnerTradeNo, - } -} diff --git a/utils/code/code.go b/utils/code/code.go index c6618fc..728fb37 100644 --- a/utils/code/code.go +++ b/utils/code/code.go @@ -38,6 +38,7 @@ const ( MSG_LOTTERY_DRAW_LADDER_NOT_EXIST = 4011 // 中奖阶梯规则不存在 MSG_LOTTERY_DRAW_RECORD_NOT_EXIST = 4012 // 中奖记录不存在 MSG_CUSTOMER_GOOD_NOT_EXIST = 4013 // 商品不存在 + MSG_CUSTOMER_GOOD_NOT_ENOUGH = 4014 // 商品不存在 MSG_ORDER_NOT_EXIST = 5000 // 订单活动不存在 MSG_CUSTOMER_ORDER_ERROR = 5001 // 订单已完成 MSG_SIGN_UP_NOT_EXIST = 5000 // 签到规则不存在