fusenapi/server/order/internal/logic/createorderlogic.go
2023-11-27 16:37:07 +08:00

120 lines
2.9 KiB
Go

package logic
import (
"fmt"
"fusenapi/constants"
"fusenapi/service/repositories"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"sync"
"time"
"context"
"fusenapi/server/order/internal/svc"
"fusenapi/server/order/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type CreateOrderLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
return &CreateOrderLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// 处理进入前逻辑w,r
// func (l *CreateOrderLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
var locks map[string]*sync.Mutex
var locksMutex sync.Mutex
func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq, userinfo *auth.UserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
if !userinfo.IsUser() {
// 如果是,返回未授权的错误码
return resp.SetStatus(basic.CodeUnAuth)
}
// var lockKey string
// for _, v := range req.CartIds {
// var vStr = strconv.Itoa(int(v))
// lockKey = lockKey + "|" + vStr
// }
// // 分布式锁--防止重复下单
// LockWith(lockKey) //获取锁
// fmt.Println("获取到了锁")
tPlus60Days := time.Now().AddDate(0, 0, 60).UTC()
res, err := l.svcCtx.Repositories.NewOrder.Create(l.ctx, &repositories.CreateReq{
ExpectedDeliveryTime: tPlus60Days,
CurrentCurrency: string(constants.CURRENCYUSD),
OriginalCurrency: string(constants.CURRENCYUSD),
UserId: userinfo.UserId,
CartIds: req.CartIds,
DeliveryMethod: constants.DELIVERYMETHODDSCLOUDSTORE,
})
// UnlockWith(lockKey) //释放锁
if err != nil {
return resp.SetStatus(&res.ErrorCode)
}
// 延时任务
time.AfterFunc(time.Minute*30, func() {
orderSn := res.OrderSn
fmt.Println("延时任务: OrderSn--", orderSn)
ctx := context.Background()
svcCtx := svc.ServiceContext{
Config: l.svcCtx.Config,
Repositories: l.svcCtx.Repositories,
}
svcCtx.Repositories.NewOrder.Close(ctx, &repositories.CloseReq{
OrderSn: orderSn,
Type: 1,
})
})
return resp.SetStatus(basic.CodeOK, map[string]interface{}{
"order_sn": res.OrderSn,
})
}
func LockWith(resource string) {
locksMutex.Lock()
lock, ok := locks[resource]
if !ok {
lock = &sync.Mutex{}
locks[resource] = lock
}
locksMutex.Unlock()
lock.Lock()
}
func UnlockWith(resource string) {
locksMutex.Lock()
lock, ok := locks[resource]
if ok {
lock.Unlock()
}
locksMutex.Unlock()
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *CreateOrderLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }