YouChuKoffee/app/services/OrderService.go

301 lines
11 KiB
Go
Raw Normal View History

2024-06-19 18:32:34 +08:00
package services
import (
2024-06-24 11:44:38 +08:00
"encoding/json"
2024-09-09 10:20:54 +08:00
"github.com/gin-gonic/gin"
2024-06-19 18:32:34 +08:00
"qteam/app/constants/common"
"qteam/app/constants/errorcode"
"qteam/app/http/entities/front"
"qteam/app/models/ordersmodel"
"qteam/app/models/productsmodel"
"qteam/app/models/usersmodel"
2024-06-24 11:44:38 +08:00
"qteam/app/third/market"
"qteam/app/third/youchu"
2024-06-19 18:32:34 +08:00
"qteam/app/utils"
redis_util "qteam/app/utils/redis"
"qteam/config"
"strconv"
"time"
"xorm.io/builder"
)
func CreateOrderService(userId int, productId int) (code int, data front.InsertOrderResponse) {
var err error
{ // redis保证用户当前抽奖结束才能开始下次抽奖
key := utils.GetRealKey("lottery_code:" + strconv.Itoa(userId) + strconv.Itoa(productId))
ok, err := redis_util.AcquireLock(key, time.Second*10)
if ok {
defer redis_util.Del(key)
} else {
if err != nil {
utils.Log(nil, "CreateOrderService", err.Error())
}
code = errorcode.OrderLottery
return code, data
}
}
session := ordersmodel.GetInstance().GetDb().NewSession()
defer func() {
if err != nil {
_ = session.Rollback()
return
}
_ = session.Close()
}()
var product productsmodel.Products
2024-07-16 14:13:30 +08:00
has, err := productsmodel.GetInstance().GetDb().Where("id = ? and status = 1", productId).Get(&product)
if !has {
2024-07-17 14:42:32 +08:00
return errorcode.ProdcutDiscard, data
}
2024-06-19 18:32:34 +08:00
if err != nil {
return errorcode.SystemError, data
}
if !has {
2024-06-25 18:31:16 +08:00
return errorcode.UserNotExist, data
2024-06-19 18:32:34 +08:00
}
2024-06-24 11:44:38 +08:00
stock, _ := strconv.Atoi(product.Stock)
if stock <= 0 {
return errorcode.ProductStockFAIL, data
}
2024-06-19 18:32:34 +08:00
var user usersmodel.Users
2024-06-25 18:31:16 +08:00
has, err = usersmodel.GetInstance().GetDb().Where("id =?", userId).Get(&user)
2024-06-19 18:32:34 +08:00
if err != nil {
return errorcode.SystemError, data
}
order := ordersmodel.Orders{
OrderNo: utils.GenerateOrderNumber(),
UserId: userId,
ProductId: productId,
ProductName: product.Name,
2024-06-25 10:12:48 +08:00
CustNo: user.CustNo,
2024-06-19 18:32:34 +08:00
Price: product.Price,
VoucherId: product.ThirdProductId,
State: common.STATUSABLED,
CreateTime: time.Now(),
}
if err = session.Begin(); err != nil {
return errorcode.SystemError, data
}
if _, err := session.Insert(order); err != nil {
utils.Log(nil, "CreateOrderService", err.Error())
return errorcode.SystemError, data
} else {
2024-09-04 17:09:32 +08:00
rs, err := session.Exec("update products set stock = stock-1 where stock >= 1 and id = ?", product.Id)
var affect, _ = rs.RowsAffected()
if err != nil || affect < 1 {
session.Rollback()
2024-07-18 09:34:11 +08:00
return errorcode.ProductStockFAIL, data
} else {
_ = session.Commit()
}
2024-06-19 18:32:34 +08:00
}
2024-10-08 11:02:32 +08:00
data.PlainText = config.GetConf().YouChu.MchtNo + "|" + order.OrderNo + "|" + order.Price
2024-09-30 18:10:31 +08:00
data.Sign = utils.HmacSha256To16(config.GetConf().YouChu.Sha, data.PlainText)
2024-06-19 18:32:34 +08:00
data.OrderNo = order.OrderNo
data.NotifyUrl = config.GetConf().YouChu.NotifyUrl
return errorcode.Success, data
}
2024-06-24 11:44:38 +08:00
func OrderQueryService(userId int, OrderRequest *front.OrderListRequest) (code int, data []ordersmodel.OrdersProductsList, count int64) {
2024-06-19 18:32:34 +08:00
repo := ordersmodel.GetInstance().GetDb()
2024-06-24 11:44:38 +08:00
conn := builder.NewCond()
2024-07-31 12:48:45 +08:00
conn = conn.And(builder.IsNull{"a.Deleted"})
2024-09-04 16:28:58 +08:00
conn = conn.And(builder.Eq{"a.user_id": userId})
2024-06-24 11:44:38 +08:00
if OrderRequest.State != 0 {
conn = conn.And(builder.Eq{"a.state": OrderRequest.State})
}
count, err := repo.Where(conn).Alias("a").
2024-09-30 15:43:48 +08:00
Join("INNER", "products b", "a.product_id = b.id").Select("a.*,b.main_image,b.brand").
2024-06-19 18:32:34 +08:00
Desc("id").Limit(OrderRequest.PageSize, (OrderRequest.Page-1)*OrderRequest.PageSize).FindAndCount(&data)
code = handErr(err)
return
}
2024-09-30 15:43:48 +08:00
func OrderDetailService(order *ordersmodel.OrdersProductsList) (has bool, err error) {
2024-06-19 18:32:34 +08:00
repo := ordersmodel.GetInstance().GetDb()
conn := builder.NewCond()
2024-07-11 15:54:47 +08:00
if config.GetConf().Debug == false {
conn.And(builder.Eq{"user_id": order.UserId})
}
2024-06-19 18:32:34 +08:00
if order.Id != 0 {
2024-10-17 23:03:31 +08:00
conn = conn.And(builder.Eq{"a.id": order.Id})
2024-06-19 18:32:34 +08:00
}
if order.OrderNo != "" {
conn = conn.And(builder.Eq{"order_no": order.OrderNo})
}
2024-09-30 15:43:48 +08:00
return repo.Where(conn).Alias("a").Join("INNER", "products b", "a.product_id = b.id").Select("a.*,b.main_image,b.brand").Get(order)
2024-06-19 18:32:34 +08:00
}
func OrdersUpdateService(req front.OrdersUpdateRequest) (err error) {
repo := ordersmodel.GetInstance().GetDb()
var order ordersmodel.Orders
if req.Id != 0 {
order.Id = req.Id
}
if req.Status != 0 {
order.State = req.Status
}
if req.VoucherLink != "" {
order.VoucherLink = req.VoucherLink
}
2024-06-27 15:56:47 +08:00
if req.OrgTxnSeq != "" {
order.OrgTxnSeq = req.OrgTxnSeq
}
2024-06-19 18:32:34 +08:00
_, err = repo.Where("Id = ?", req.Id).Update(&order)
return
}
func OrderRefundService(userId int, orderId int) (code int) {
{ // redis保证用户当前抽奖结束才能开始下次抽奖
key := utils.GetRealKey("lottery_code:" + strconv.Itoa(userId) + strconv.Itoa(orderId))
ok, err := redis_util.AcquireLock(key, time.Second*10)
if ok {
defer redis_util.Del(key)
} else {
if err != nil {
utils.Log(nil, "CreateOrderService", err.Error())
}
return errorcode.SystemError
}
}
2024-09-30 15:43:48 +08:00
order := ordersmodel.OrdersProductsList{}
2024-06-24 11:44:38 +08:00
order.Id = orderId
2024-06-19 18:32:34 +08:00
has, err := OrderDetailService(&order)
if err != nil || !has {
return errorcode.NotFound
}
2024-08-02 09:53:46 +08:00
if order.State != common.ORDER_STATUS_FAIL {
2024-06-19 18:32:34 +08:00
return errorcode.OrderNOTAuthREFUND
}
2024-09-30 15:43:48 +08:00
code, response := YouChuOrderRefund(order.Orders)
2024-06-19 18:32:34 +08:00
if code != errorcode.Success {
return code
} else {
if response.RefundOrderSta != "03" {
return errorcode.OrderRefundFail
} else {
2024-07-31 15:45:02 +08:00
order.State = common.ORDER_STATUS_ReFUNDEND
2024-06-19 18:32:34 +08:00
order.RefundOrderNo = response.RefundOrderNo
order.RefundOrderSta = response.RefundOrderSta
order.RefundTime = time.Now()
2024-10-22 18:07:17 +08:00
_, err := ordersmodel.GetInstance().GetDb().Where("id = ?", order.Id).Update(order.Orders)
2024-08-02 11:37:56 +08:00
//增加库存
if err == nil {
2024-09-04 16:17:57 +08:00
_, err = ordersmodel.GetInstance().GetDb().Exec("update products set stock=stock+1 where id = " + strconv.Itoa(order.ProductId))
2024-08-02 11:37:56 +08:00
return errorcode.Success
} else {
2024-06-19 18:32:34 +08:00
return errorcode.OrderRefundUpdateFail
}
}
}
}
2024-06-24 11:44:38 +08:00
2024-07-31 09:22:18 +08:00
func OrderDelete(id string) error {
_, err := ordersmodel.GetInstance().GetDb().Where("id = ?", id).Update(ordersmodel.Orders{Deleted: time.Now()})
return err
}
2024-09-09 10:20:54 +08:00
func OrderNotify(request front.YouChuRequest, c *gin.Context) (NotifyResponse front.YouChuOrderNotifyResponse) {
2024-06-24 11:44:38 +08:00
requestStr, _ := json.Marshal(request)
2024-06-28 09:27:17 +08:00
utils.Log(nil, "订单回调请求--原始数据:", string(requestStr))
2024-07-03 18:30:53 +08:00
response := youchu.DecryptResponse(string(requestStr), true)
2024-06-28 09:27:17 +08:00
utils.Log(nil, "订单回调请求--解密数据:", response)
2024-06-24 11:44:38 +08:00
var YouChuOrderNotifyRequest front.YouChuOrderNotifyRequest
err := json.Unmarshal([]byte(response), &YouChuOrderNotifyRequest)
if err != nil {
return front.YouChuOrderNotifyResponse{RespCode: "000001", RespMsg: "解析失败"}
}
// 03-支付成功 04-支付失败 05-检查失败
if YouChuOrderNotifyRequest.OrderSta != "03" {
return front.YouChuOrderNotifyResponse{RespCode: "000002", RespMsg: "交易失败"}
} else {
//支付成功
utils.Log(nil, "OrderNotify-success", YouChuOrderNotifyRequest)
var orderDetail ordersmodel.Orders
var order ordersmodel.Orders
2024-07-03 18:30:53 +08:00
has, err := ordersmodel.GetInstance().GetDb().Where("voucher_link = ?", "").Where("order_no = ?", YouChuOrderNotifyRequest.ReqTraceId).Get(&orderDetail)
2024-09-09 10:20:54 +08:00
//金额对不上
if orderDetail.Price != YouChuOrderNotifyRequest.TxnAmt {
ip, _ := c.RemoteIP()
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_TIMEOUT})
if ip != nil {
utils.Log(nil, "OrderNotify-fail", ip.String())
}
return front.YouChuOrderNotifyResponse{RespCode: "000004", RespMsg: "金额不匹配"}
}
2024-06-24 11:44:38 +08:00
if err != nil || !has {
2024-07-18 17:19:45 +08:00
utils.Log(nil, "notify err", err, YouChuOrderNotifyRequest.ReqTraceId, YouChuOrderNotifyRequest.OrderNo)
2024-06-24 11:44:38 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000003", RespMsg: "订单不存在"}
}
2024-07-31 14:17:48 +08:00
2024-08-02 10:38:08 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{ExchangeTime: time.Now()})
2024-08-02 10:43:37 +08:00
order.ExchangeTime = time.Now()
2024-08-02 10:38:08 +08:00
utils.Log(nil, "更新订单err", orderDetail.Id, err)
2024-06-24 11:44:38 +08:00
var productDetail productsmodel.Products
has, err = productsmodel.GetInstance().GetDb().Where("id = ?", orderDetail.ProductId).Get(&productDetail)
if err != nil || !has {
2024-08-02 11:17:04 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_FAIL})
2024-07-18 17:19:45 +08:00
utils.Log(nil, "notify err", err, orderDetail.ProductId)
2024-06-24 11:44:38 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000003", RespMsg: "商品不存在"}
}
2024-07-03 18:30:53 +08:00
session := ordersmodel.GetInstance().GetDb().NewSession()
defer func() {
if err != nil {
2024-08-02 11:17:04 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_FAIL})
2024-07-18 17:04:45 +08:00
utils.Log(nil, "notify err", err)
2024-07-03 18:30:53 +08:00
_ = session.Rollback()
return
}
_ = session.Close()
}()
2024-06-24 11:44:38 +08:00
//01-消费 03-退货
if YouChuOrderNotifyRequest.TxnFlag == "01" {
2024-07-03 18:30:53 +08:00
_, err = session.Where("id = ?", orderDetail.ProductId).Where("stock >= ?", common.ORDER_STATUS_DEFAULT).Update(&productDetail)
if err = session.Begin(); err != nil {
2024-07-18 17:04:45 +08:00
utils.Log(nil, "notify err", err)
2024-07-03 18:30:53 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000004", RespMsg: "库存不足"}
}
2024-07-31 14:17:48 +08:00
2024-06-24 11:44:38 +08:00
client := market.NewMarketClient(config.GetConf().OpenApiMarketConfig)
2024-08-05 16:21:29 +08:00
send, err := client.MarketSend(orderDetail.OrderNo, orderDetail.VoucherId, "", "2")
2024-07-11 15:28:25 +08:00
utils.Log(nil, "OrderNotify-MarketSend", send, err)
2024-06-24 11:44:38 +08:00
if err != nil {
2024-08-02 11:17:04 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_FAIL})
2024-07-18 17:04:45 +08:00
utils.Log(nil, "notify err", err)
2024-06-24 11:44:38 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000004", RespMsg: "充值失败"}
}
order.OrgTxnSeq = YouChuOrderNotifyRequest.OrderNo
2024-08-01 17:44:53 +08:00
if send.ErrCode != "00" || send.Data.ShortUrl == "" {
2024-06-24 11:44:38 +08:00
order.State = common.ORDER_STATUS_FAIL
} else {
order.State = common.ORDER_STATUS_FINISH
order.VoucherLink = send.Data.ShortUrl
2024-07-25 14:22:09 +08:00
order.ExchangeTime = time.Now()
2024-07-18 17:04:45 +08:00
utils.Log(nil, "nitifydata", send.Data.ShortUrl, "***", send.Data.VoucherId)
//Stock, _ := strconv.Atoi(productDetail.Stock)
//productDetail.Stock = strconv.Itoa(Stock - 1)
2024-06-24 11:44:38 +08:00
}
2024-07-03 18:32:26 +08:00
2024-06-24 11:44:38 +08:00
} else {
//order.RefundOrderNo = YouChuOrderNotifyRequest.OrgTxnSeq
//order.RefundOrderSta = YouChuOrderNotifyRequest.OrderSta
2024-08-02 11:17:04 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_FAIL})
2024-06-24 11:44:38 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000005", RespMsg: "订单标识错误"}
}
2024-07-30 09:04:08 +08:00
_, err = session.Cols("stock,state,voucher_link,orgTxnSeq,exchange_time").Where("order_no = ?", YouChuOrderNotifyRequest.ReqTraceId).Update(&order)
2024-06-24 11:44:38 +08:00
if err != nil {
2024-08-02 11:17:04 +08:00
_, err = ordersmodel.GetInstance().GetDb().Where("id = ?", orderDetail.Id).Update(ordersmodel.Orders{State: common.ORDER_STATUS_FAIL})
2024-06-24 11:44:38 +08:00
utils.Log(nil, "OrderNotify-MarketSend", err.Error())
2024-07-03 18:30:53 +08:00
_ = session.Rollback()
2024-06-24 11:44:38 +08:00
return front.YouChuOrderNotifyResponse{RespCode: "000004", RespMsg: "操作失败"}
2024-07-03 18:30:53 +08:00
} else {
_ = session.Commit()
NotifyResponse.RespCode = "000000"
NotifyResponse.RespMsg = "交易成功"
2024-06-24 11:44:38 +08:00
}
}
return
}