fix
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
Name: shopping-cart-confirmation
|
||||
Host: 0.0.0.0
|
||||
Port: 8892
|
||||
DataSource: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
|
||||
Auth:
|
||||
AccessSecret: fusen2023
|
||||
AccessExpire: 604800
|
||||
RefreshAfter: 345600
|
||||
12
server/shopping-cart-confirmation/internal/config/config.go
Normal file
12
server/shopping-cart-confirmation/internal/config/config.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/types"
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
rest.RestConf
|
||||
DataSource string
|
||||
Auth types.Auth
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/logic"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/svc"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/types"
|
||||
)
|
||||
|
||||
func CartAddHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// 解析jwtToken
|
||||
claims, err := svcCtx.ParseJwtToken(r)
|
||||
// 如果解析出错,则返回未授权的JSON响应并记录错误消息
|
||||
if err != nil {
|
||||
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
|
||||
Code: 401,
|
||||
Message: "unauthorized",
|
||||
})
|
||||
logx.Info("unauthorized:", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// 从Token里获取对应的信息
|
||||
userinfo, err := auth.GetUserInfoFormMapClaims(claims)
|
||||
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
|
||||
if err != nil {
|
||||
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
|
||||
Code: 401,
|
||||
Message: "unauthorized",
|
||||
})
|
||||
logx.Info("unauthorized:", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var req types.CartAddReq
|
||||
// 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
|
||||
Code: 510,
|
||||
Message: "parameter error",
|
||||
})
|
||||
logx.Info(err)
|
||||
return
|
||||
}
|
||||
// 创建一个业务逻辑层实例
|
||||
l := logic.NewCartAddLogic(r.Context(), svcCtx)
|
||||
resp := l.CartAdd(&req, userinfo)
|
||||
// 如果响应不为nil,则使用httpx.OkJsonCtx方法返回JSON响应;
|
||||
// 否则,发送500内部服务器错误的JSON响应并记录错误消息logx.Error。
|
||||
if resp != nil {
|
||||
httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
} else {
|
||||
err := errors.New("server logic is error, resp must not be nil")
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
logx.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
22
server/shopping-cart-confirmation/internal/handler/routes.go
Normal file
22
server/shopping-cart-confirmation/internal/handler/routes.go
Normal file
@@ -0,0 +1,22 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/svc"
|
||||
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
|
||||
server.AddRoutes(
|
||||
[]rest.Route{
|
||||
{
|
||||
Method: http.MethodPost,
|
||||
Path: "/cart/add",
|
||||
Handler: CartAddHandler(serverCtx),
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
126
server/shopping-cart-confirmation/internal/logic/cartaddlogic.go
Normal file
126
server/shopping-cart-confirmation/internal/logic/cartaddlogic.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package logic
|
||||
|
||||
import (
|
||||
"fusenapi/model/gmodel"
|
||||
"fusenapi/utils/auth"
|
||||
"fusenapi/utils/basic"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"context"
|
||||
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/svc"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
type CartAddLogic struct {
|
||||
logx.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
|
||||
return &CartAddLogic{
|
||||
Logger: logx.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
// 添加入购物车
|
||||
func (l *CartAddLogic) CartAdd(req *types.CartAddReq, userinfo *auth.UserInfo) (resp *basic.Response) {
|
||||
if req.BuyNum == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeApiErr, "param buy_num can`t be 0")
|
||||
}
|
||||
if req.IsCheck != 0 && req.IsCheck != 1 {
|
||||
return resp.SetStatusWithMessage(basic.CodeApiErr, "param is_check should be 0 or 1")
|
||||
}
|
||||
req.DesignId = strings.Trim(req.DesignId, " ")
|
||||
if req.DesignId == "" {
|
||||
return resp.SetStatusWithMessage(basic.CodeApiErr, "param design_id can`t be empty")
|
||||
}
|
||||
//查询是否有此设计
|
||||
productDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)
|
||||
productDesignInfo, err := productDesignModel.FindOneBySn(l.ctx, req.DesignId)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product design info")
|
||||
}
|
||||
if productDesignInfo.Id == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "product design info is not exists")
|
||||
}
|
||||
//查找是否有此材质、产品、大小id的阶梯价格
|
||||
productPriceModel := gmodel.NewFsProductPriceModel(l.svcCtx.MysqlConn)
|
||||
priceStatus := int64(1)
|
||||
priceReq := gmodel.FindOneProductPriceByParamsReq{
|
||||
ProductId: productDesignInfo.ProductId,
|
||||
MaterialId: productDesignInfo.MaterialId,
|
||||
SizeId: productDesignInfo.SizeId,
|
||||
Status: &priceStatus,
|
||||
}
|
||||
productPriceInfo, err := productPriceModel.FindOneProductPriceByParams(l.ctx, priceReq)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product price info")
|
||||
}
|
||||
if productPriceInfo.Id == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, " product price info is not exists")
|
||||
}
|
||||
if *productPriceInfo.EachBoxNum == 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, " product price info err: each box num can`t be zero")
|
||||
}
|
||||
//买的数量和每箱数量取余为0 且 份数大于等于最小购买数量才算满足条件
|
||||
if (int64(req.BuyNum) % *productPriceInfo.EachBoxNum) != 0 {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid buy number,please check")
|
||||
}
|
||||
if int64(float64(req.BuyNum)/float64(*productPriceInfo.EachBoxNum)) < *productPriceInfo.MinBuyNum {
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "invalid buy number,please check!")
|
||||
}
|
||||
//查询购物车
|
||||
cartModel := gmodel.NewFsCartModel(l.svcCtx.MysqlConn)
|
||||
cartStatus := int64(1)
|
||||
cartReq := gmodel.FindOneCartByParamsReq{
|
||||
UserId: &userinfo.UserId,
|
||||
ProductId: productDesignInfo.ProductId,
|
||||
TemplateId: productDesignInfo.TemplateId,
|
||||
PriceId: &productPriceInfo.Id,
|
||||
DesignId: &productDesignInfo.Id,
|
||||
MaterialId: productDesignInfo.MaterialId,
|
||||
Status: &cartStatus,
|
||||
}
|
||||
cartInfo, err := cartModel.FindOneCartByParams(l.ctx, cartReq)
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get cart info")
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
nowTime := time.Now()
|
||||
data := gmodel.FsCart{
|
||||
UserId: &userinfo.UserId,
|
||||
ProductId: productPriceInfo.ProductId,
|
||||
TemplateId: productDesignInfo.TemplateId,
|
||||
PriceId: &productPriceInfo.Id,
|
||||
MaterialId: productDesignInfo.MaterialId,
|
||||
SizeId: productDesignInfo.SizeId,
|
||||
BuyNum: &req.BuyNum,
|
||||
Cover: productDesignInfo.Cover,
|
||||
DesignId: &productDesignInfo.Id,
|
||||
Ctime: &now,
|
||||
Status: &cartStatus,
|
||||
OptionalId: productDesignInfo.OptionalId,
|
||||
IsCheck: &req.IsCheck,
|
||||
TsTime: &nowTime,
|
||||
}
|
||||
if cartInfo.Id == 0 {
|
||||
err = cartModel.Create(l.ctx, data)
|
||||
} else {
|
||||
err = cartModel.Update(l.ctx, cartInfo.Id, data)
|
||||
}
|
||||
if err != nil {
|
||||
logx.Error(err)
|
||||
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to add to cart")
|
||||
}
|
||||
return resp.SetStatus(basic.CodeOK)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"fusenapi/initalize"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/config"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ServiceContext struct {
|
||||
Config config.Config
|
||||
|
||||
MysqlConn *gorm.DB
|
||||
}
|
||||
|
||||
func NewServiceContext(c config.Config) *ServiceContext {
|
||||
|
||||
return &ServiceContext{
|
||||
Config: c,
|
||||
MysqlConn: initalize.InitMysql(c.DataSource),
|
||||
}
|
||||
}
|
||||
|
||||
func (svcCxt *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
|
||||
AuthKey := r.Header.Get("Authorization")
|
||||
if len(AuthKey) <= 50 {
|
||||
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
|
||||
// 检查签名方法是否为 HS256
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
// 返回用于验证签名的密钥
|
||||
return svcCxt.Config.Auth.AccessSecret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
|
||||
}
|
||||
|
||||
// 验证成功返回
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
return nil, errors.New(fmt.Sprint("Invalid token", err))
|
||||
}
|
||||
72
server/shopping-cart-confirmation/internal/types/types.go
Normal file
72
server/shopping-cart-confirmation/internal/types/types.go
Normal file
@@ -0,0 +1,72 @@
|
||||
// Code generated by goctl. DO NOT EDIT.
|
||||
package types
|
||||
|
||||
import (
|
||||
"fusenapi/utils/basic"
|
||||
)
|
||||
|
||||
type CartAddReq struct {
|
||||
DesignId string `json:"design_id"` //设计sn
|
||||
BuyNum int64 `json:"buy_num"` //购买数量
|
||||
IsCheck int64 `json:"isCheck,optional"`
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"msg"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
type ResponseJwt struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"msg"`
|
||||
Data interface{} `json:"data"`
|
||||
AccessSecret string `json:"accessSecret"`
|
||||
AccessExpire int64 `json:"accessExpire"`
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
AccessSecret string `json:"accessSecret"`
|
||||
AccessExpire int64 `json:"accessExpire"`
|
||||
RefreshAfter int64 `json:"refreshAfter"`
|
||||
}
|
||||
|
||||
// Set 设置Response的Code和Message值
|
||||
func (resp *Response) Set(Code int, Message string) *Response {
|
||||
return &Response{
|
||||
Code: Code,
|
||||
Message: Message,
|
||||
}
|
||||
}
|
||||
|
||||
// Set 设置整个Response
|
||||
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
|
||||
return &Response{
|
||||
Code: Code,
|
||||
Message: Message,
|
||||
Data: Data,
|
||||
}
|
||||
}
|
||||
|
||||
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
|
||||
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
|
||||
newResp := &Response{
|
||||
Code: sr.Code,
|
||||
}
|
||||
if len(data) == 1 {
|
||||
newResp.Data = data[0]
|
||||
}
|
||||
return newResp
|
||||
}
|
||||
|
||||
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
|
||||
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
|
||||
newResp := &Response{
|
||||
Code: sr.Code,
|
||||
Message: msg,
|
||||
}
|
||||
if len(data) == 1 {
|
||||
newResp.Data = data[0]
|
||||
}
|
||||
return newResp
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/config"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/handler"
|
||||
"fusenapi/server/shopping-cart-confirmation/internal/svc"
|
||||
|
||||
"github.com/zeromicro/go-zero/core/conf"
|
||||
"github.com/zeromicro/go-zero/rest"
|
||||
)
|
||||
|
||||
var configFile = flag.String("f", "etc/shopping-cart-confirmation.yaml", "the config file")
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
var c config.Config
|
||||
conf.MustLoad(*configFile, &c)
|
||||
|
||||
server := rest.MustNewServer(c.RestConf)
|
||||
defer server.Stop()
|
||||
|
||||
ctx := svc.NewServiceContext(c)
|
||||
handler.RegisterHandlers(server, ctx)
|
||||
|
||||
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
|
||||
server.Start()
|
||||
}
|
||||
|
||||
// var testConfigFile = flag.String("f", "../etc/shopping-cart-confirmation.yaml", "the config file")
|
||||
// var cnf config.Config
|
||||
|
||||
// func GetTestServer() *rest.Server {
|
||||
// flag.Parse()
|
||||
|
||||
// conf.MustLoad(*testConfigFile, &cnf)
|
||||
|
||||
// server := rest.MustNewServer(cnf.RestConf)
|
||||
// defer server.Stop()
|
||||
|
||||
// ctx := svc.NewServiceContext(cnf)
|
||||
// handler.RegisterHandlers(server, ctx)
|
||||
|
||||
// fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port)
|
||||
// return server
|
||||
// }
|
||||
Reference in New Issue
Block a user