Merge branch 'develop' of https://gitee.com/fusenpack/fusenapi into develop

This commit is contained in:
eson
2023-06-14 18:20:04 +08:00
39 changed files with 1878 additions and 10 deletions

View File

@@ -31,7 +31,7 @@ func NewSaveCanteenTypeProductLogic(ctx context.Context, svcCtx *svc.ServiceCont
// 保存餐厅类型的关联产品
func (l *SaveCanteenTypeProductLogic) SaveCanteenTypeProduct(req *types.SaveCanteenTypeProductReq, loginInfo *auth.UserInfo) (resp *basic.Response) {
if len(req.ProductList) == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "product list can`t be empty")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "product list can`t be empty")
}
canteenProductModel := gmodel.NewFsCanteenProductModel(l.svcCtx.MysqlConn)
//获取原有餐厅类型的所有产品

View File

@@ -0,0 +1,8 @@
Name: map-library
Host: 0.0.0.0
Port: 8893
SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest
Auth:
AccessSecret: fusen2023
AccessExpire: 60
RefreshAfter: 60

View File

@@ -0,0 +1,12 @@
package config
import (
"fusenapi/server/map_library/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
SourceMysql string
Auth types.Auth
}

View File

@@ -0,0 +1,55 @@
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/map_library/internal/logic"
"fusenapi/server/map_library/internal/svc"
)
func GetMapLibraryListHandler(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
}
l := logic.NewGetMapLibraryListLogic(r.Context(), svcCtx)
resp := l.GetMapLibraryList(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)
}
}
}

View File

@@ -0,0 +1,22 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/map_library/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/map-library/list",
Handler: GetMapLibraryListHandler(serverCtx),
},
},
)
}

View File

@@ -0,0 +1,79 @@
package logic
import (
"encoding/json"
"fusenapi/model/gmodel"
"fusenapi/server/map_library/internal/types"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"time"
"context"
"fusenapi/server/map_library/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetMapLibraryListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetMapLibraryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMapLibraryListLogic {
return &GetMapLibraryListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMapLibraryListLogic) GetMapLibraryList(userinfo *auth.UserInfo) (resp *basic.Response) {
mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn)
mapLibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get map library list")
}
if len(mapLibraryList) == 0 {
return resp.SetStatus(basic.CodeOK)
}
productTemplateTagIds := make([]int64, 0, len(mapLibraryList))
for _, v := range mapLibraryList {
productTemplateTagIds = append(productTemplateTagIds, *v.TagId)
}
//获取标签列表
productTemplateTagsModel := gmodel.NewFsProductTemplateTagsModel(l.svcCtx.MysqlConn)
templateTagList, err := productTemplateTagsModel.GetListByIds(l.ctx, productTemplateTagIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product template tags")
}
mapTag := make(map[int64]int)
for k, v := range templateTagList {
mapTag[v.Id] = k
}
list := make([]types.GetMapLibraryListRsp, 0, len(mapLibraryList))
for _, v := range mapLibraryList {
data := types.GetMapLibraryListRsp{
Mid: v.Id,
Ctime: time.Unix(*v.Ctime, 0).Format("2006-01-02 15:04:05"),
}
//tag拼装
if tagIndex, ok := mapTag[*v.TagId]; ok {
data.Tag = types.MapLibraryListTag{
Id: templateTagList[tagIndex].Id,
Title: *templateTagList[tagIndex].Title,
}
}
//解析info
var info types.MapLibraryListInfo
if err = json.Unmarshal([]byte(*v.Info), &info); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "json parse info err")
}
data.Info = info
list = append(list, data)
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", list)
}

View File

@@ -0,0 +1,51 @@
package svc
import (
"errors"
"fmt"
"fusenapi/initalize"
"fusenapi/server/map_library/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.SourceMysql),
}
}
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))
}

View File

@@ -0,0 +1,138 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type GetMapLibraryListRsp struct {
Mid int64 `json:"mid"`
Ctime string `json:"ctime"`
Tag MapLibraryListTag `json:"tag"`
Info MapLibraryListInfo `json:"info"`
}
type MapLibraryListInfo struct {
Id string `json:"id"`
Tag string `json:"tag"`
Title string `json:"title"`
Type string `json:"type"`
Text string `json:"text"`
Fill string `json:"fill"`
FontSize int64 `json:"fontSize"`
FontFamily string `json:"fontFamily"`
IfBr bool `json:"ifBr"`
IfShow bool `json:"ifShow"`
IfGroup bool `json:"ifGroup"`
MaxNum int64 `json:"maxNum"`
Rotation int64 `json:"rotation"`
Align string `json:"align"`
VerticalAlign string `json:"verticalAlign"`
Material string `json:"material"`
QRcodeType int64 `json:"QRcodeType"`
Width float64 `json:"width"`
Height float64 `json:"height"`
X float64 `json:"x"`
Y float64 `json:"y"`
Opacity float64 `json:"opacity"`
OptionalColor []MapLibraryListOptionalColorItem `json:"optionalColor"`
ZIndex int64 `json:"zIndex"`
SvgPath string `json:"svgPath"`
Follow MapLibraryListFollow `json:"follow"`
Group []MapLibraryListGroup `json:"group"`
CameraStand MapLibraryListCameraStand `json:"cameraStand"`
MaterialTime string `json:"materialTime"`
MaterialName string `json:"materialName"`
}
type MapLibraryListCameraStand struct {
X int64 `json:"x"`
Y int64 `json:"y"`
Z int64 `json:"z"`
}
type MapLibraryListGroup struct {
Tag string `json:"tag"`
Text string `json:"text"`
Title string `json:"title"`
IfBr bool `json:"ifBr"`
IfShow bool `json:"ifShow"`
MaxNum int64 `json:"maxNum"`
}
type MapLibraryListFollow struct {
Fill string `json:"fill"`
IfShow string `json:"ifShow"`
Content string `json:"content"`
}
type MapLibraryListOptionalColorItem struct {
Color string `json:"color"`
Name string `json:"name"`
Default bool `json:"default"`
}
type MapLibraryListTag struct {
Id int64 `json:"id"`
Title string `json:"title"`
}
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
}

View File

@@ -0,0 +1,49 @@
package main
import (
"flag"
"fmt"
"fusenapi/server/map_library/internal/config"
"fusenapi/server/map_library/internal/handler"
"fusenapi/server/map_library/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/map-library.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/map-library.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
// }

View File

@@ -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 CartOrderDetailHandler(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.CartOrderDetailReq
// 如果端点有请求结构体则使用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.NewCartOrderDetailLogic(r.Context(), svcCtx)
resp := l.CartOrderDetail(&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)
}
}
}

View File

@@ -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 ChangeOrderMethodHandler(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.ChangeOrderMethodReq
// 如果端点有请求结构体则使用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.NewChangeOrderMethodLogic(r.Context(), svcCtx)
resp := l.ChangeOrderMethod(&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)
}
}
}

View File

@@ -32,6 +32,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/cart/list",
Handler: CartListHandler(serverCtx),
},
{
Method: http.MethodGet,
Path: "/cart/order-detail",
Handler: CartOrderDetailHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/cart/chang-order-method",
Handler: ChangeOrderMethodHandler(serverCtx),
},
},
)
}

View File

@@ -32,14 +32,14 @@ func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLo
// 添加入购物车
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")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "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")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "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")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param design_id can`t be empty")
}
//查询是否有此设计
productDesignModel := gmodel.NewFsProductDesignModel(l.svcCtx.MysqlConn)

View File

@@ -29,7 +29,7 @@ func NewCartDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartDe
func (l *CartDeleteLogic) CartDelete(req *types.CartDeleteReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if req.Id <= 0 {
return resp.SetStatusWithMessage(basic.CodeApiErr, "invalid param id")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid param id")
}
cartModel := gmodel.NewFsCartModel(l.svcCtx.MysqlConn)
status := int64(0)

View File

@@ -0,0 +1,175 @@
package logic
import (
"fmt"
"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 CartOrderDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCartOrderDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartOrderDetailLogic {
return &CartOrderDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *CartOrderDetailLogic) CartOrderDetail(req *types.CartOrderDetailReq, userinfo *auth.UserInfo) (resp *basic.Response) {
req.Sn = strings.Trim(req.Sn, " ")
if req.Sn == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required")
}
//获取订单数据
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
}
if orderInfo.Id == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the order is not exists")
}
//获取订单详细数据
orderDetailModel := gmodel.NewFsOrderDetailModel(l.svcCtx.MysqlConn)
orderDetailList, err := orderDetailModel.GetOrderDetailsByOrderId(l.ctx, orderInfo.Id)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order details")
}
if len(orderDetailList) == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "order details is empty")
}
orderDetailTemplateIds := make([]int64, 0, len(orderDetailList))
productIds := make([]int64, 0, len(orderDetailList))
for _, v := range orderDetailList {
orderDetailTemplateIds = append(orderDetailTemplateIds, *v.OrderDetailTemplateId)
productIds = append(productIds, *v.ProductId)
}
//获取订单详情对应模板信息
orderDetailTemplateModel := gmodel.NewFsOrderDetailTemplateModel(l.svcCtx.MysqlConn)
orderDetailTemplateList, err := orderDetailTemplateModel.GetListByIds(l.ctx, orderDetailTemplateIds)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order details templates")
}
sizeIds := make([]int64, 0, len(orderDetailTemplateList))
mapDetailTemplate := make(map[int64]int)
for k, v := range orderDetailTemplateList {
sizeIds = append(sizeIds, *v.SizeId)
mapDetailTemplate[v.Id] = k
}
//获取尺寸信息
productSizeModel := gmodel.NewFsProductSizeModel(l.svcCtx.MysqlConn)
productSizeList, err := productSizeModel.GetAllByIds(l.ctx, sizeIds, "")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get product size list")
}
mapProductSize := make(map[int64]int)
for k, v := range productSizeList {
mapProductSize[v.Id] = k
}
//获取产品信息
productModel := gmodel.NewFsProductModel(l.svcCtx.MysqlConn)
productList, err := productModel.GetProductListByIds(l.ctx, productIds, "")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order products")
}
mapProduct := make(map[int64]int)
for k, v := range productList {
mapProduct[v.Id] = k
}
//获取用户地址信息
addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn)
addressList, err := addressModel.GetUserAllAddress(l.ctx, userinfo.UserId)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address")
}
//处理订单数据
addressItems := make([]types.CartAddr, 0, len(addressList))
for _, v := range addressList {
addressItems = append(addressItems, types.CartAddr{
Id: v.Id,
Name: *v.Name,
FirstName: *v.FirstName,
LastName: *v.LastName,
Mobile: *v.Mobile,
Street: *v.Street,
Suite: *v.Suite,
City: *v.City,
State: *v.State,
ZipCode: *v.ZipCode,
IsDefault: *v.IsDefault,
})
}
items := make([]types.CartDetailItem, 0, len(orderDetailList))
totalAmount := int64(0) //订单总金额
for _, v := range orderDetailList {
thisTotal := (*v.BuyNum) * (*v.Amount)
size := ""
if detailTemplateIndex, ok := mapDetailTemplate[*v.OrderDetailTemplateId]; ok {
detailTemplate := orderDetailTemplateList[detailTemplateIndex]
if sizeIndex, ok := mapProductSize[*detailTemplate.SizeId]; ok {
size = *productSizeList[sizeIndex].Capacity
}
}
name := ""
if productIndex, ok := mapProduct[*v.ProductId]; ok {
name = *productList[productIndex].Title
}
items = append(items, types.CartDetailItem{
Cover: *v.Cover,
Pcs: *v.BuyNum,
Amount: fmt.Sprintf("$ %.2f", float64(thisTotal)/100),
Option: *v.OptionalTitle,
Size: size,
Name: name,
})
totalAmount += thisTotal
}
//首付50%
total := totalAmount / 2
//尾款
remaining := totalAmount - total
payStep := int64(0) //未支付
if *orderInfo.PayedAmount == *orderInfo.TotalAmount/2 {
payStep = 1 //已支付首款
}
if *orderInfo.PayedAmount == *orderInfo.TotalAmount {
payStep = 2 //已支付尾款
}
payTime := ""
if *orderInfo.Ptime != 0 {
payTime = time.Unix(*orderInfo.Ptime, 0).Format("2006-01-02 15:04:05")
}
return resp.SetStatusWithMessage(basic.CodeOK, "success", types.CartOrderDetailRsp{
DeliveryMethod: 1,
AddressId: 0,
PayTime: payTime,
PayMethod: 1,
PayStep: payStep,
Subtotal: fmt.Sprintf("$%.2f", float64(totalAmount)/100),
Total: fmt.Sprintf("$%.2f", float64(total)/100),
Remaining: fmt.Sprintf("$%.2f", float64(remaining)/100),
AddrList: addressItems,
Items: items,
})
}

View File

@@ -0,0 +1,74 @@
package logic
import (
"encoding/json"
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"strings"
"context"
"fusenapi/server/shopping-cart-confirmation/internal/svc"
"fusenapi/server/shopping-cart-confirmation/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ChangeOrderMethodLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewChangeOrderMethodLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangeOrderMethodLogic {
return &ChangeOrderMethodLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ChangeOrderMethodLogic) ChangeOrderMethod(req *types.ChangeOrderMethodReq, userinfo *auth.UserInfo) (resp *basic.Response) {
req.Sn = strings.Trim(req.Sn, " ")
if req.Sn == "" {
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "param sn is required")
}
//查询订单信息
orderModel := gmodel.NewFsOrderModel(l.svcCtx.MysqlConn)
orderInfo, err := orderModel.FindOneBySn(l.ctx, userinfo.UserId, req.Sn)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get order info")
}
if orderInfo.Id == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "the order is not exists")
}
if *orderInfo.PayedAmount > 0 {
return resp.SetStatusWithMessage(basic.CodeApiErr, "the order`s address cannot be changed for it is paid")
}
updData := gmodel.FsOrder{}
//地址
if req.AddressId > 0 {
addressModel := gmodel.NewFsAddressModel(l.svcCtx.MysqlConn)
addr, err := addressModel.GetOne(l.ctx, req.AddressId, userinfo.UserId)
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get address info")
}
if addr.Id == 0 {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "address is not exists")
}
infoJsonByte, _ := json.Marshal(addr)
strInfoJson := string(infoJsonByte)
updData.AddressInfo = &strInfoJson
}
updData.DeliveryMethod = &req.DeliveryMethod
updData.AddressId = &req.AddressId
updData.PayMethod = &req.PayMethod
if err = orderModel.Update(l.ctx, orderInfo.Id, updData); err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to save data")
}
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}

View File

@@ -57,6 +57,53 @@ type CartSizeItem struct {
Inch string `json:"inch"`
}
type CartOrderDetailReq struct {
Sn string `form:"sn"`
}
type CartOrderDetailRsp struct {
DeliveryMethod int64 `json:"delivery_method"`
AddressId int64 `json:"address_id"`
PayTime string `json:"pay_time"`
PayMethod int64 `json:"pay_method"`
PayStep int64 `json:"pay_step"`
Subtotal string `json:"subtotal"`
Total string `json:"total"`
Remaining string `json:"remaining"`
AddrList []CartAddr `json:"addr_list"`
Items []CartDetailItem `json:"items"`
}
type CartDetailItem struct {
Cover string `json:"cover"`
Pcs int64 `json:"pcs"`
Amount string `json:"amount"`
Option string `json:"option"`
Size string `json:"size"`
Name string `json:"name"`
}
type CartAddr struct {
Id int64 `json:"id"`
Name string `json:"name"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Mobile string `json:"mobile"`
Street string `json:"street"`
Suite string `json:"suite"`
City string `json:"city"`
State string `json:"state"`
ZipCode string `json:"zip_code"`
IsDefault int64 `json:"is_default"`
}
type ChangeOrderMethodReq struct {
Sn string `json:"sn"`
DeliveryMethod int64 `json:"delivery_method , options=1|2"`
AddressId int64 `json:"address_id"`
PayMethod int64 `json:"pay_method"`
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`